@vkontakte/videoplayer-core 2.0.95 → 2.0.96
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 +5 -5
- package/es2015.esm.js +5 -5
- package/es2018.cjs.js +5 -5
- package/es2018.esm.js +5 -5
- package/esnext.cjs.js +5 -5
- package/esnext.esm.js +5 -5
- package/evergreen.esm.js +5 -5
- package/package.json +1 -1
package/es2018.esm.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.96
|
|
3
|
+
* Wed, 13 Dec 2023 12:11:59 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-96/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{ValueSubject as S,Subject as L,Subscription as re,isNonNullable as _,ErrorCategory as C,isNullable as te,fromEvent as B,assertNever as V,merge as U,tap as ts,map as w,observableFrom as ke,filterChanged as fe,assertNonNullable as P,debounce as Me,getHighestQuality as hd,timeout as fd,getCurrentBrowser as Br,CurrentClientBrowser as Mn,combine as Ie,once as me,mapTo as Wt,filter as se,now as pe,videoSizeToQuality as Rt,isInvariantQuality as vi,isHigher as pi,isLower as Ki,isHigherOrEqual as Tr,isLowerOrEqual as Nn,Observable as cs,interval as is,VideoQuality as Ce,videoQualityToHeight as pd,abortable as Re,getExponentialDelay as fa,throttle as md,CurrentClientDevice as vd,safeStorage as Cs,fillWithDefault as gd,Logger as Sd}from"@vkontakte/videoplayer-shared/es2018.esm.js";import{Observable as Zv,Subject as eg,Subscription as tg,ValueSubject as ig,VideoQuality as sg}from"@vkontakte/videoplayer-shared/es2018.esm.js";import bd from"lodash/debounce.js";const yd="2.0.95";var p;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(p||(p={}));var y;(function(s){s.MPEG="MPEG",s.DASH="DASH",s.DASH_SEP="DASH_SEP",s.DASH_SEP_VK="DASH_SEP",s.DASH_WEBM="DASH_WEBM",s.DASH_WEBM_AV1="DASH_WEBM_AV1",s.DASH_WEBM_VK="DASH_WEBM",s.DASH_ONDEMAND="DASH_ONDEMAND",s.DASH_ONDEMAND_VK="DASH_ONDEMAND",s.DASH_LIVE="DASH_LIVE",s.DASH_LIVE_CMAF="DASH_LIVE_CMAF",s.DASH_LIVE_WEBM="DASH_LIVE_WEBM",s.HLS="HLS",s.HLS_ONDEMAND="HLS_ONDEMAND",s.HLS_JS="HLS",s.HLS_LIVE="HLS_LIVE",s.HLS_LIVE_CMAF="HLS_LIVE_CMAF",s.WEB_RTC_LIVE="WEB_RTC_LIVE"})(y||(y={}));var Ee;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(Ee||(Ee={}));var ye;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})(ye||(ye={}));var gi;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(gi||(gi={}));var z;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(z||(z={}));var gt;(function(s){s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip"})(gt||(gt={}));var Td=s=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class Ed{constructor(e){var t;this.connection$=new S(void 0),this.castState$=new S(ye.NOT_AVAILABLE),this.errorEvent$=new L,this.realCastState$=new S(ye.NOT_AVAILABLE),this.subscription=new re,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const i="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${i}`}),e.isDisabled||!i)return;const r=_((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||Td("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:C.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())===null||i===void 0?void 0:i.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||a===void 0||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){_(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();te(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();te(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(B(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(a=i.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return V(r.sessionState)}})).add(U(B(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(ts(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),w(r=>r.castState)),ke([i.getCastState()])).pipe(fe(),w($d),ts(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===ye.CONNECTED,o=_(this.connection$.getValue());if(n&&!o){const u=i.getCurrentSession();P(u);const d=u.getCastDevice(),l=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(te(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===ye.CONNECTED?_(this.connection$.getValue())?ye.CONNECTED:ye.AVAILABLE:r)}))}initializeCastApi(){var e;let t,i,r;try{t=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:i,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:C.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const $d=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return ye.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return ye.AVAILABLE;case cast.framework.CastState.CONNECTING:return ye.CONNECTING;case cast.framework.CastState.CONNECTED:return ye.CONNECTED;default:return V(s)}};var Os=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Mr(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var nt=function(s){try{return!!s()}catch(e){return!0}},Ad=nt,hs=!Ad(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),Fn=hs,Un=Function.prototype,Er=Un.call,kd=Fn&&Un.bind.bind(Er,Er),ot=Fn?kd:function(s){return function(){return Er.apply(s,arguments)}},Vn=ot,wd=Vn({}.toString),_d=Vn("".slice),fs=function(s){return _d(wd(s),8,-1)},Pd=ot,Dd=nt,Rd=fs,Bs=Object,Id=Pd("".split),xd=Dd(function(){return!Bs("z").propertyIsEnumerable(0)})?function(s){return Rd(s)=="String"?Id(s,""):Bs(s)}:Bs,ps=function(s){return s==null},Ld=ps,Cd=TypeError,Nr=function(s){if(Ld(s))throw Cd("Can't call method on "+s);return s},Od=xd,Bd=Nr,Ti=function(s){return Od(Bd(s))},Zt={},xi=function(s){return s&&s.Math==Math&&s},Ye=xi(typeof globalThis=="object"&&globalThis)||xi(typeof window=="object"&&window)||xi(typeof self=="object"&&self)||xi(typeof Os=="object"&&Os)||function(){return this}()||Os||Function("return this")(),$r=typeof document=="object"&&document.all,Md=typeof $r=="undefined"&&$r!==void 0,Hn={all:$r,IS_HTMLDDA:Md},Gn=Hn,Nd=Gn.all,Ne=Gn.IS_HTMLDDA?function(s){return typeof s=="function"||s===Nd}:function(s){return typeof s=="function"},Fd=Ye,Ud=Ne,pa=Fd.WeakMap,Vd=Ud(pa)&&/native code/.test(String(pa)),ma=Ne,Yn=Hn,Hd=Yn.all,It=Yn.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:ma(s)||s===Hd}:function(s){return typeof s=="object"?s!==null:ma(s)},Gd=nt,xt=!Gd(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),ei={},Yd=Ye,va=It,Ar=Yd.document,qd=va(Ar)&&va(Ar.createElement),qn=function(s){return qd?Ar.createElement(s):{}},jd=xt,zd=nt,Wd=qn,jn=!jd&&!zd(function(){return Object.defineProperty(Wd("div"),"a",{get:function(){return 7}}).a!=7}),Qd=xt,Kd=nt,zn=Qd&&Kd(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Jd=It,Xd=String,Zd=TypeError,Lt=function(s){if(Jd(s))return s;throw Zd(Xd(s)+" is not an object")},eu=hs,Li=Function.prototype.call,dt=eu?Li.bind(Li):function(){return Li.apply(Li,arguments)},Fr={},Ms=Fr,Ns=Ye,tu=Ne,ga=function(s){return tu(s)?s:void 0},Ur=function(s,e){return arguments.length<2?ga(Ms[s])||ga(Ns[s]):Ms[s]&&Ms[s][e]||Ns[s]&&Ns[s][e]},iu=ot,Vr=iu({}.isPrototypeOf),su=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Wn=Ye,Fs=su,Sa=Wn.process,ba=Wn.Deno,ya=Sa&&Sa.versions||ba&&ba.version,Ta=ya&&ya.v8,Ve,ss;Ta&&(Ve=Ta.split("."),ss=Ve[0]>0&&Ve[0]<4?1:+(Ve[0]+Ve[1]));!ss&&Fs&&(Ve=Fs.match(/Edge\/(\d+)/),(!Ve||Ve[1]>=74)&&(Ve=Fs.match(/Chrome\/(\d+)/),Ve&&(ss=+Ve[1])));var ru=ss,Ea=ru,au=nt,nu=Ye,ou=nu.String,Qn=!!Object.getOwnPropertySymbols&&!au(function(){var s=Symbol();return!ou(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Ea&&Ea<41}),du=Qn,Kn=du&&!Symbol.sham&&typeof Symbol.iterator=="symbol",uu=Ur,lu=Ne,cu=Vr,hu=Kn,fu=Object,Jn=hu?function(s){return typeof s=="symbol"}:function(s){var e=uu("Symbol");return lu(e)&&cu(e.prototype,fu(s))},pu=String,Hr=function(s){try{return pu(s)}catch(e){return"Object"}},mu=Ne,vu=Hr,gu=TypeError,Gr=function(s){if(mu(s))return s;throw gu(vu(s)+" is not a function")},Su=Gr,bu=ps,ms=function(s,e){var t=s[e];return bu(t)?void 0:Su(t)},Us=dt,Vs=Ne,Hs=It,yu=TypeError,Tu=function(s,e){var t,i;if(e==="string"&&Vs(t=s.toString)&&!Hs(i=Us(t,s))||Vs(t=s.valueOf)&&!Hs(i=Us(t,s))||e!=="string"&&Vs(t=s.toString)&&!Hs(i=Us(t,s)))return i;throw yu("Can't convert object to primitive value")},Xn={exports:{}},$a=Ye,Eu=Object.defineProperty,$u=function(s,e){try{Eu($a,s,{value:e,configurable:!0,writable:!0})}catch(t){$a[s]=e}return e},Au=Ye,ku=$u,Aa="__core-js_shared__",wu=Au[Aa]||ku(Aa,{}),Zn=wu,ka=Zn;(Xn.exports=function(s,e){return ka[s]||(ka[s]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"});var eo=Xn.exports,_u=Nr,Pu=Object,vs=function(s){return Pu(_u(s))},Du=ot,Ru=vs,Iu=Du({}.hasOwnProperty),ut=Object.hasOwn||function(e,t){return Iu(Ru(e),t)},xu=ot,Lu=0,Cu=Math.random(),Ou=xu(1 .toString),to=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Ou(++Lu+Cu,36)},Bu=Ye,Mu=eo,wa=ut,Nu=to,Fu=Qn,Uu=Kn,qt=Bu.Symbol,Gs=Mu("wks"),Vu=Uu?qt.for||qt:qt&&qt.withoutSetter||Nu,qe=function(s){return wa(Gs,s)||(Gs[s]=Fu&&wa(qt,s)?qt[s]:Vu("Symbol."+s)),Gs[s]},Hu=dt,_a=It,Pa=Jn,Gu=ms,Yu=Tu,qu=qe,ju=TypeError,zu=qu("toPrimitive"),Wu=function(s,e){if(!_a(s)||Pa(s))return s;var t=Gu(s,zu),i;if(t){if(e===void 0&&(e="default"),i=Hu(t,s,e),!_a(i)||Pa(i))return i;throw ju("Can't convert object to primitive value")}return e===void 0&&(e="number"),Yu(s,e)},Qu=Wu,Ku=Jn,Yr=function(s){var e=Qu(s,"string");return Ku(e)?e:e+""},Ju=xt,Xu=jn,Zu=zn,Ci=Lt,Da=Yr,el=TypeError,Ys=Object.defineProperty,tl=Object.getOwnPropertyDescriptor,qs="enumerable",js="configurable",zs="writable";ei.f=Ju?Zu?function(e,t,i){if(Ci(e),t=Da(t),Ci(i),typeof e=="function"&&t==="prototype"&&"value"in i&&zs in i&&!i[zs]){var r=tl(e,t);r&&r[zs]&&(e[t]=i.value,i={configurable:js in i?i[js]:r[js],enumerable:qs in i?i[qs]:r[qs],writable:!1})}return Ys(e,t,i)}:Ys:function(e,t,i){if(Ci(e),t=Da(t),Ci(i),Xu)try{return Ys(e,t,i)}catch(r){}if("get"in i||"set"in i)throw el("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var gs=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},il=xt,sl=ei,rl=gs,Ei=il?function(s,e,t){return sl.f(s,e,rl(1,t))}:function(s,e,t){return s[e]=t,s},al=eo,nl=to,Ra=al("keys"),qr=function(s){return Ra[s]||(Ra[s]=nl(s))},jr={},ol=Vd,io=Ye,dl=It,ul=Ei,Ws=ut,Qs=Zn,ll=qr,cl=jr,Ia="Object already initialized",kr=io.TypeError,hl=io.WeakMap,rs,Si,as,fl=function(s){return as(s)?Si(s):rs(s,{})},pl=function(s){return function(e){var t;if(!dl(e)||(t=Si(e)).type!==s)throw kr("Incompatible receiver, "+s+" required");return t}};if(ol||Qs.state){var ze=Qs.state||(Qs.state=new hl);ze.get=ze.get,ze.has=ze.has,ze.set=ze.set,rs=function(s,e){if(ze.has(s))throw kr(Ia);return e.facade=s,ze.set(s,e),e},Si=function(s){return ze.get(s)||{}},as=function(s){return ze.has(s)}}else{var Ut=ll("state");cl[Ut]=!0,rs=function(s,e){if(Ws(s,Ut))throw kr(Ia);return e.facade=s,ul(s,Ut,e),e},Si=function(s){return Ws(s,Ut)?s[Ut]:{}},as=function(s){return Ws(s,Ut)}}var ml={set:rs,get:Si,has:as,enforce:fl,getterFor:pl},vl=hs,so=Function.prototype,xa=so.apply,La=so.call,gl=typeof Reflect=="object"&&Reflect.apply||(vl?La.bind(xa):function(){return La.apply(xa,arguments)}),Sl=fs,bl=ot,ro=function(s){if(Sl(s)==="Function")return bl(s)},ao={},no={},oo={}.propertyIsEnumerable,uo=Object.getOwnPropertyDescriptor,yl=uo&&!oo.call({1:2},1);no.f=yl?function(e){var t=uo(this,e);return!!t&&t.enumerable}:oo;var Tl=xt,El=dt,$l=no,Al=gs,kl=Ti,wl=Yr,_l=ut,Pl=jn,Ca=Object.getOwnPropertyDescriptor;ao.f=Tl?Ca:function(e,t){if(e=kl(e),t=wl(t),Pl)try{return Ca(e,t)}catch(i){}if(_l(e,t))return Al(!El($l.f,e,t),e[t])};var Dl=nt,Rl=Ne,Il=/#|\.prototype\./,$i=function(s,e){var t=Ll[xl(s)];return t==Ol?!0:t==Cl?!1:Rl(e)?Dl(e):!!e},xl=$i.normalize=function(s){return String(s).replace(Il,".").toLowerCase()},Ll=$i.data={},Cl=$i.NATIVE="N",Ol=$i.POLYFILL="P",Bl=$i,Oa=ro,Ml=Gr,Nl=hs,Fl=Oa(Oa.bind),lo=function(s,e){return Ml(s),e===void 0?s:Nl?Fl(s,e):function(){return s.apply(e,arguments)}},Oi=Ye,Ul=gl,Vl=ro,Hl=Ne,Gl=ao.f,Yl=Bl,Vt=Fr,ql=lo,Ht=Ei,Ba=ut,jl=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return Ul(s,this,arguments)};return e.prototype=s.prototype,e},Ss=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?Oi:r?Oi[t]:(Oi[t]||{}).prototype,o=i?Vt:Vt[t]||Ht(Vt,t,{})[t],u=o.prototype,d,l,c,h,f,m,g,T,A;for(h in e)d=Yl(i?h:t+(r?".":"#")+h,s.forced),l=!d&&n&&Ba(n,h),m=o[h],l&&(s.dontCallGetSet?(A=Gl(n,h),g=A&&A.value):g=n[h]),f=l&&g?g:e[h],!(l&&typeof m==typeof f)&&(s.bind&&l?T=ql(f,Oi):s.wrap&&l?T=jl(f):a&&Hl(f)?T=Vl(f):T=f,(s.sham||f&&f.sham||m&&m.sham)&&Ht(T,"sham",!0),Ht(o,h,T),a&&(c=t+"Prototype",Ba(Vt,c)||Ht(Vt,c,{}),Ht(Vt[c],h,f),s.real&&u&&(d||!u[h])&&Ht(u,h,f)))},wr=xt,zl=ut,co=Function.prototype,Wl=wr&&Object.getOwnPropertyDescriptor,zr=zl(co,"name"),Ql=zr&&function(){}.name==="something",Kl=zr&&(!wr||wr&&Wl(co,"name").configurable),Jl={EXISTS:zr,PROPER:Ql,CONFIGURABLE:Kl},ho={},Xl=Math.ceil,Zl=Math.floor,ec=Math.trunc||function(e){var t=+e;return(t>0?Zl:Xl)(t)},tc=ec,Wr=function(s){var e=+s;return e!==e||e===0?0:tc(e)},ic=Wr,sc=Math.max,rc=Math.min,ac=function(s,e){var t=ic(s);return t<0?sc(t+e,0):rc(t,e)},nc=Wr,oc=Math.min,dc=function(s){return s>0?oc(nc(s),9007199254740991):0},uc=dc,Qr=function(s){return uc(s.length)},lc=Ti,cc=ac,hc=Qr,Ma=function(s){return function(e,t,i){var r=lc(e),a=hc(r),n=cc(i,a),o;if(s&&t!=t){for(;a>n;)if(o=r[n++],o!=o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}},fc={includes:Ma(!0),indexOf:Ma(!1)},pc=ot,Ks=ut,mc=Ti,vc=fc.indexOf,gc=jr,Na=pc([].push),Sc=function(s,e){var t=mc(s),i=0,r=[],a;for(a in t)!Ks(gc,a)&&Ks(t,a)&&Na(r,a);for(;e.length>i;)Ks(t,a=e[i++])&&(~vc(r,a)||Na(r,a));return r},fo=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],bc=Sc,yc=fo,Tc=Object.keys||function(e){return bc(e,yc)},Ec=xt,$c=zn,Ac=ei,kc=Lt,wc=Ti,_c=Tc;ho.f=Ec&&!$c?Object.defineProperties:function(e,t){kc(e);for(var i=wc(t),r=_c(t),a=r.length,n=0,o;a>n;)Ac.f(e,o=r[n++],i[o]);return e};var Pc=Ur,Dc=Pc("document","documentElement"),Rc=Lt,Ic=ho,Fa=fo,xc=jr,Lc=Dc,Cc=qn,Oc=qr,Ua=">",Va="<",_r="prototype",Pr="script",po=Oc("IE_PROTO"),Js=function(){},mo=function(s){return Va+Pr+Ua+s+Va+"/"+Pr+Ua},Ha=function(s){s.write(mo("")),s.close();var e=s.parentWindow.Object;return s=null,e},Bc=function(){var s=Cc("iframe"),e="java"+Pr+":",t;return s.style.display="none",Lc.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(mo("document.F=Object")),t.close(),t.F},Bi,Ji=function(){try{Bi=new ActiveXObject("htmlfile")}catch(e){}Ji=typeof document!="undefined"?document.domain&&Bi?Ha(Bi):Bc():Ha(Bi);for(var s=Fa.length;s--;)delete Ji[_r][Fa[s]];return Ji()};xc[po]=!0;var vo=Object.create||function(e,t){var i;return e!==null?(Js[_r]=Rc(e),i=new Js,Js[_r]=null,i[po]=e):i=Ji(),t===void 0?i:Ic.f(i,t)},Mc=nt,Nc=!Mc(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),Fc=ut,Uc=Ne,Vc=vs,Hc=qr,Gc=Nc,Ga=Hc("IE_PROTO"),Dr=Object,Yc=Dr.prototype,go=Gc?Dr.getPrototypeOf:function(s){var e=Vc(s);if(Fc(e,Ga))return e[Ga];var t=e.constructor;return Uc(t)&&e instanceof t?t.prototype:e instanceof Dr?Yc:null},qc=Ei,So=function(s,e,t,i){return i&&i.enumerable?s[e]=t:qc(s,e,t),s},jc=nt,zc=Ne,Wc=It,Qc=vo,Ya=go,Kc=So,Jc=qe,Rr=Jc("iterator"),bo=!1,st,Xs,Zs;[].keys&&(Zs=[].keys(),"next"in Zs?(Xs=Ya(Ya(Zs)),Xs!==Object.prototype&&(st=Xs)):bo=!0);var Xc=!Wc(st)||jc(function(){var s={};return st[Rr].call(s)!==s});Xc?st={}:st=Qc(st);zc(st[Rr])||Kc(st,Rr,function(){return this});var yo={IteratorPrototype:st,BUGGY_SAFARI_ITERATORS:bo},Zc=qe,eh=Zc("toStringTag"),To={};To[eh]="z";var Kr=String(To)==="[object z]",th=Kr,ih=Ne,Xi=fs,sh=qe,rh=sh("toStringTag"),ah=Object,nh=Xi(function(){return arguments}())=="Arguments",oh=function(s,e){try{return s[e]}catch(t){}},bs=th?Xi:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=oh(e=ah(s),rh))=="string"?t:nh?Xi(e):(i=Xi(e))=="Object"&&ih(e.callee)?"Arguments":i},dh=Kr,uh=bs,lh=dh?{}.toString:function(){return"[object "+uh(this)+"]"},ch=Kr,hh=ei.f,fh=Ei,ph=ut,mh=lh,vh=qe,qa=vh("toStringTag"),Eo=function(s,e,t,i){if(s){var r=t?s:s.prototype;ph(r,qa)||hh(r,qa,{configurable:!0,value:e}),i&&!ch&&fh(r,"toString",mh)}},gh=yo.IteratorPrototype,Sh=vo,bh=gs,yh=Eo,Th=Zt,Eh=function(){return this},$h=function(s,e,t,i){var r=e+" Iterator";return s.prototype=Sh(gh,{next:bh(+!i,t)}),yh(s,r,!1,!0),Th[r]=Eh,s},Ah=Ss,kh=dt,$o=Jl,wh=$h,_h=go,Ph=Eo,ja=So,Dh=qe,za=Zt,Ao=yo,Rh=$o.PROPER;$o.CONFIGURABLE;Ao.IteratorPrototype;var Mi=Ao.BUGGY_SAFARI_ITERATORS,er=Dh("iterator"),Wa="keys",Ni="values",Qa="entries",Ih=function(){return this},xh=function(s,e,t,i,r,a,n){wh(t,e,i);var o=function(A){if(A===r&&h)return h;if(!Mi&&A in l)return l[A];switch(A){case Wa:return function(){return new t(this,A)};case Ni:return function(){return new t(this,A)};case Qa:return function(){return new t(this,A)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,l=s.prototype,c=l[er]||l["@@iterator"]||r&&l[r],h=!Mi&&c||o(r),f=e=="Array"&&l.entries||c,m,g,T;if(f&&(m=_h(f.call(new s)),m!==Object.prototype&&m.next&&(Ph(m,u,!0,!0),za[u]=Ih)),Rh&&r==Ni&&c&&c.name!==Ni&&(d=!0,h=function(){return kh(c,this)}),r)if(g={values:o(Ni),keys:a?h:o(Wa),entries:o(Qa)},n)for(T in g)(Mi||d||!(T in l))&&ja(l,T,g[T]);else Ah({target:e,proto:!0,forced:Mi||d},g);return n&&l[er]!==h&&ja(l,er,h,{name:r}),za[e]=h,g},Lh=function(s,e){return{value:s,done:e}},Ch=Ti,Ka=Zt,ko=ml;ei.f;var Oh=xh,Fi=Lh,wo="Array Iterator",Bh=ko.set,Mh=ko.getterFor(wo);Oh(Array,"Array",function(s,e){Bh(this,{type:wo,target:Ch(s),index:0,kind:e})},function(){var s=Mh(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,Fi(void 0,!0)):t=="keys"?Fi(i,!1):t=="values"?Fi(e[i],!1):Fi([i,e[i]],!1)},"values");Ka.Arguments=Ka.Array;var Nh=qe,Fh=Zt,Uh=Nh("iterator"),Vh=Array.prototype,Hh=function(s){return s!==void 0&&(Fh.Array===s||Vh[Uh]===s)},Gh=bs,Ja=ms,Yh=ps,qh=Zt,jh=qe,zh=jh("iterator"),_o=function(s){if(!Yh(s))return Ja(s,zh)||Ja(s,"@@iterator")||qh[Gh(s)]},Wh=dt,Qh=Gr,Kh=Lt,Jh=Hr,Xh=_o,Zh=TypeError,ef=function(s,e){var t=arguments.length<2?Xh(s):e;if(Qh(t))return Kh(Wh(t,s));throw Zh(Jh(s)+" is not iterable")},tf=dt,Xa=Lt,sf=ms,rf=function(s,e,t){var i,r;Xa(s);try{if(i=sf(s,"return"),!i){if(e==="throw")throw t;return t}i=tf(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return Xa(i),t},af=lo,nf=dt,of=Lt,df=Hr,uf=Hh,lf=Qr,Za=Vr,cf=ef,hf=_o,en=rf,ff=TypeError,Zi=function(s,e){this.stopped=s,this.result=e},tn=Zi.prototype,pf=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=af(e,i),d,l,c,h,f,m,g,T=function(E){return d&&en(d,"normal",E),new Zi(!0,E)},A=function(E){return r?(of(E),o?u(E[0],E[1],T):u(E[0],E[1])):o?u(E,T):u(E)};if(a)d=s.iterator;else if(n)d=s;else{if(l=hf(s),!l)throw ff(df(s)+" is not iterable");if(uf(l)){for(c=0,h=lf(s);h>c;c++)if(f=A(s[c]),f&&Za(tn,f))return f;return new Zi(!1)}d=cf(s,l)}for(m=a?s.next:d.next;!(g=nf(m,d)).done;){try{f=A(g.value)}catch(E){en(d,"throw",E)}if(typeof f=="object"&&f&&Za(tn,f))return f}return new Zi(!1)},mf=Yr,vf=ei,gf=gs,Sf=function(s,e,t){var i=mf(e);i in s?vf.f(s,i,gf(0,t)):s[i]=t},bf=Ss,yf=pf,Tf=Sf;bf({target:"Object",stat:!0},{fromEntries:function(e){var t={};return yf(e,function(i,r){Tf(t,i,r)},{AS_ENTRIES:!0}),t}});var Ef=Fr,$f=Ef.Object.fromEntries,Af={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},kf=Af,wf=Ye,_f=bs,Pf=Ei,sn=Zt,Df=qe,rn=Df("toStringTag");for(var tr in kf){var an=wf[tr],ir=an&&an.prototype;ir&&_f(ir)!==rn&&Pf(ir,rn,tr),sn[tr]=sn.Array}var Rf=$f,If=Rf,xf=If,Lf=xf,Qt=Mr(Lf),be;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",s[s.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(be||(be={}));var He=(s,e=0,t=be.OFFSET_P)=>{switch(t){case be.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case be.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case be.DASH_CMAF_OFFSET_P:{if(e===0)return s;const i=new URL(s);return i.searchParams.set("offset_p",e.toFixed(0)),i.toString()}default:V(t)}return s};const nn=(s,e)=>{var t;switch(e){case be.OFFSET_P:return NaN;case be.PLAYBACK_SHIFT:{const i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case be.DASH_CMAF_OFFSET_P:{const i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:V(e)}};var R=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};class ue{constructor(e){this.transitionStarted$=new L,this.transitionEnded$=new L,this.transitionUpdated$=new L,this.forceChanged$=new L,this.stateChangeStarted$=U(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=U(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||_(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const Cf=s=>{switch(s){case y.MPEG:case y.DASH:case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.HLS:case y.HLS_ONDEMAND:return!1;case y.DASH_LIVE:case y.DASH_LIVE_CMAF:case y.HLS_LIVE:case y.HLS_LIVE_CMAF:case y.DASH_LIVE_WEBM:case y.WEB_RTC_LIVE:return!0;default:return V(s)}};var q;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(q||(q={}));const Of=5,Bf=5,Mf=500,on=7e3;class Nf{constructor(e){this.subscription=new re,this.loadMediaTimeoutSubscription=new re,this.videoState=new ue(q.STOPPED),this.syncPlayback=()=>{const i=this.videoState.getState(),r=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${a}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(o)};`}),a===p.STOPPED){i!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==p.PAUSED&&o.state===z.Requested&&i!==q.STOPPED){this.seek(o.position/1e3);return}switch(a){case p.READY:{switch(i){case q.PLAYING:case q.PAUSED:case q.READY:break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:V(i)}break}case p.PLAYING:{switch(i){case q.PLAYING:break;case q.PAUSED:this.videoState.startTransitionTo(q.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case q.READY:this.videoState.startTransitionTo(q.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:V(i)}break}case p.PAUSED:{switch(i){case q.PLAYING:this.videoState.startTransitionTo(q.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case q.PAUSED:break;case q.READY:this.videoState.startTransitionTo(q.PAUSED),this.videoState.setState(q.PAUSED);break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:V(i)}break}default:V(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Cf(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new re;this.subscription.add(e),this.subscription.add(U(this.videoState.stateChangeStarted$.pipe(w(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(w(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));const t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const r=new L;e.add(r.pipe(Me(Mf)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===z.Applying||Math.abs(o-a)>Of)&&r.next(o),a=o})),e.add(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<Bf&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),R(this.params.desiredState.playbackState,p.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:V(n)}}),t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const i=U(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Me(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(q.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED)):(this.videoState.setState(q.PLAYING),R(this.params.desiredState.playbackState,p.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:z.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===q.PAUSED||e===q.PLAYING)&&(this.videoState.setState(q.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===q.PLAYING||e===q.PAUSED)&&(this.videoState.setState(q.PLAYING),R(this.params.desiredState.playbackState,p.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===q.READY&&this.videoState.setState(q.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===p.READY&&R(this.params.desiredState.playbackState,p.READY)}handleRemoteStop(){this.videoState.getState()!==q.STOPPED&&this.videoState.setState(q.STOPPED)}handleRemoteVolumeChange(e){var t,i;const r=this.params.output.volume$.getValue(),a={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(i=e.muted)!==null&&i!==void 0?i:r.muted};(a.volume!==r.volume||a.muted!==a.muted)&&this.params.output.volume$.next(a)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const i=this.params.source;let r,a,n;switch(e){case y.MPEG:{const l=i[e];P(l);const c=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 y.HLS:case y.HLS_ONDEMAND:{const l=i[e];P(l),r=l.url,a="application/x-mpegurl",n=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.DASH_WEBM_AV1:{const l=i[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_LIVE_CMAF:{const l=i[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const l=i[e];P(l),r=He(l.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case y.DASH:case y.DASH_LIVE:case y.WEB_RTC_LIVE:{const l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:C.VIDEO_PIPELINE,message:l,thrown:c}),c}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return V(e)}const o=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,a);o.contentUrl=r,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return _(u)&&(o.metadata.title=u),_(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===z.Applying||i.state===z.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(fd(on).subscribe(()=>a(`timeout(${on})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===z.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{const a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:C.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}var Ff=s=>{let e,t=!1,i=!1;s.on("playbackTimeUpdated",({timeToEnd:r})=>{i=r<=3,t&&i&&(e==null||e())}),s.extend("MediaSourceController",function(){const{parent:r}=this,a=r.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>a(n),t&&i&&(e==null||e())}}},!0)},Uf=s=>{const e=new S(1/0),t=new L,i=new S(void 0),r=new S(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},u=l=>{var c,h,f,m,g;const T=Qt(l.getAllResponseHeaders().trim().split(/[\n\r]+/).map(v=>v.split(": ")));if("x-playback-duration"in T||"x-playback-duration-millis"in T){const v=parseInt((c=l.getResponseHeader("X-Playback-Duration"))!==null&&c!==void 0?c:"",10),b=parseInt((h=l.getResponseHeader("X-Playback-Duration-Millis"))!==null&&h!==void 0?h:"",10),$=(f=b!=null?b:v*1e3)!==null&&f!==void 0?f:NaN;_($)&&!isNaN($)&&e.next($)}const A=(m=T["x-delivery-type"])!==null&&m!==void 0?m:gi.HTTP1,E=(g={1:!0,0:!1}[T["x-reused"]])!==null&&g!==void 0?g:void 0;i.next(A),r.next(E)},d=l=>{l.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return s.extend("XHRLoader",function(){const{parent:l}=this,c=l.load.bind(l);return{load:function(h){if(h.request.type==="MPD"){const f=h.onload,m=h.progress;h.onload=function(...g){return u(this),f(...g)},h.progress=function(...g){return d(this),m(...g)},o()}return c(h)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:i}},Kt=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},Vf=s=>s.extend("RequestModifier",()=>({modifyRequestURL:Kt}),!0),Hf=s=>{s.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[r,a]=i.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(i.request.url,location.href);n.searchParams.append("bytes",`${r}-${a}`),i.request.url=n.toString(),i.request.range=void 0}t(i)}}},!0)};const Ge=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=s.getState(),o=e(),u=te(r),d=new re;return r&&d.add(r.subscribe(l=>{const c=s.getState();i(l,c)&&s.setState(l)},a)),i(o,n)||(t(n),u&&s.setState(n)),d.add(s.stateChangeStarted$.subscribe(l=>{t(l.to),u&&s.setState(l.to)},a)),d},Ct=(s,e,t)=>Ge(e,()=>s.loop,i=>{_(i)&&(s.loop=i)},{onError:t}),lt=(s,e,t,i)=>Ge(e,()=>({muted:s.muted,volume:s.volume}),r=>{_(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),Tt=(s,e,t,i)=>Ge(e,()=>s.playbackRate,r=>{_(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Gf=s=>["__",s.language,s.label].join("|"),Yf=(s,e)=>{if(s.id===e)return!0;const[t,i,r]=e.split("|");return s.language===i&&s.label===r};class Ze{constructor(){this.available$=new L,this.current$=new S(void 0),this.error$=new L,this.subscription=new re,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:C.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Ge(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{_(a)&&this.setInternal(a)},{equal:(a,n)=>_(a)&&_(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(w(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Ge(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{_(a)&&this.setExternal(a)},{equal:(a,n)=>_(a)&&_(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(w(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Ge(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(Ge(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){P(this.video);const{textTracks:e}=this.video;this.subscription.add(B(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(U(B(e,"addtrack"),B(e,"removetrack"),ke(["init"])).pipe(w(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),fe((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(U(B(e,"change"),ke(["init"])).pipe(w(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),w(i=>i&&this.htmlTextTrackToITextTrack(i).id),fe()).subscribe(this.current$));const t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(B(e,"addtrack").subscribe(i=>{var r,a;(r=i.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var u,d,l,c,h;const f=(d=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&d!==void 0?d:null;f&&f.length&&(this.applyCueSettings((c=(l=o.target)===null||l===void 0?void 0:l.cues)!==null&&c!==void 0?c:null),(h=o.target)===null||h===void 0||h.removeEventListener("cuechange",n))};(a=i.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(B(e,"removetrack").subscribe(i=>{var r;(r=i.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const r=i;_(t.align)&&(r.align=t.align),_(t.position)&&(r.position=t.position),_(t.size)&&(r.size=t.size),_(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){P(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Ze.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,i;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:(i=this.internalTracks.get(n))===null||i===void 0?void 0:i.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){P(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(te(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"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const Jr=s=>{s.removeAttribute("src"),s.load()},qf=s=>{try{s.pause(),s.playbackRate=0,Jr(s),s.remove()}catch(e){console.error(e)}};class jf{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 Ir=window.WeakMap?new WeakMap:new jf,ct=s=>{let e=s.querySelector("video");const t=!!e;return e?Jr(e):(e=document.createElement("video"),s.appendChild(e)),Ir.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},ht=s=>{const e=Ir.get(s);Ir.delete(s),e?Jr(s):qf(s)};class ys{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=s=>{var e;let t=s;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},dn=s=>{const e=Po(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},zf=s=>{const e=Po(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)},xr=3;class Wf{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let r=this._source.buffered.start(t);const a=this._source.buffered.end(t);r>e&&r-e<xr&&(r=e),this._buffer.push({from:r,to:a,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||xr))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:r,to:a})=>{const n=r>=e&&r<t,o=a>=e&&a<t;n&&o||(n?i(t,a):o?i(r,e):r<e&&a>t?(i(t,a),i(r,e)):i(r,a))})}destroy(){this._buffer=[]}}var Do=(s,e,t=xr)=>{let i=0,r=0;for(let a=0;a<s.length;a++){const n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};const ft=s=>{const e=v=>B(s,v).pipe(Wt(void 0)),i=U(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>B(s,v))).pipe(w(v=>v.type==="ended"?s.readyState<2:s.readyState<3),fe()),r=U(B(s,"progress"),B(s,"timeupdate")).pipe(w(()=>Do(s.buffered,s.currentTime))),n=Br().browser===Mn.Safari?Ie({play:e("play").pipe(me()),playing:e("playing")}).pipe(Wt(void 0)):e("playing"),o=B(s,"volumechange").pipe(w(()=>({muted:s.muted,volume:s.volume}))),u=B(s,"ratechange").pipe(w(()=>s.playbackRate)),d=B(s,"error").pipe(se(()=>!!(s.error||s.played.length)),w(()=>{var v;const b=s.error;return{id:b?`MediaError#${b.code}`:"HtmlVideoError",category:C.VIDEO_PIPELINE,message:b?b.message:"Error event from HTML video element",thrown:(v=s.error)!==null&&v!==void 0?v:void 0}})),l=B(s,"timeupdate").pipe(w(()=>s.currentTime)),c=new L,h=.3;let f;l.subscribe(v=>{s.loop&&_(f)&&_(v)&&f>=s.duration-h&&v<=h&&c.next(f),f=v});const m=B(s,"enterpictureinpicture"),g=B(s,"leavepictureinpicture"),T=new S(zf(s));m.subscribe(()=>T.next(!0)),g.subscribe(()=>T.next(!1));const A=new S(dn(s));return B(s,"fullscreenchange").pipe(w(()=>dn(s))).subscribe(A),{playing$:n,pause$:e("pause").pipe(se(()=>!s.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:B(s,"durationchange").pipe(w(()=>s.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:o,playbackRateState$:u,inPiP$:T,inFullscreen$:A}},Xr=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var Qf=Ss,Kf=vs,Jf=Qr,Xf=Wr;Qf({target:"Array",proto:!0},{at:function(e){var t=Kf(this),i=Jf(t),r=Xf(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});var Zf=Ur,Ro=Zf,ep=Ro,tp=ep("Array","at"),ip=tp,sp=ip,rp=sp,ap=rp,Qe=Mr(ap);let Zr=!1,it={};const np=s=>{Zr=s},op=()=>{it={}},dp=s=>{s(it)},Ui=(s,e)=>{var t;Zr&&(it.meta=(t=it.meta)!==null&&t!==void 0?t:{},it.meta[s]=e)};class Ke{constructor(e){this.name=e}next(e){var t,i;if(!Zr)return;it.series=(t=it.series)!==null&&t!==void 0?t:{};const r=(i=it.series[this.name])!==null&&i!==void 0?i:[];r.push([Date.now(),e]),it.series[this.name]=r}}var Pt;(function(s){s.FitsContainer="FitsContainer",s.FitsThroughput="FitsThroughput",s.Buffer="Buffer",s.DroppedFramesLimit="DroppedFramesLimit",s.FitsQualityLimits="FitsQualityLimits"})(Pt||(Pt={}));const up=new Ke("best_bitrate"),lp=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class cp{constructor(){this.history={}}recordSelection(e){this.history[e.id]=pe()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const ti=(s,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:d,droppedVideoMaxQualityLimit:l,abrLogger:c})=>{var h,f,m,g,T;const A=i.usePixelRatio&&(h=window.devicePixelRatio)!==null&&h!==void 0?h:1,E=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*A*i.containerSizeFactor,height:e.height*A*i.containerSizeFactor},v=E&&Rt(E),b=i.considerPlaybackRate&&_(o)?o:1,$=s.filter(F=>!vi(F.quality)).sort((F,I)=>pi(F.quality,I.quality)?-1:1),D=(f=Qe($,-1))===null||f===void 0?void 0:f.quality,Y=(m=Qe($,0))===null||m===void 0?void 0:m.quality,J=te(r)||_(r.min)&&_(r.max)&&Ki(r.max,r.min)||_(r.min)&&Y&&pi(r.min,Y)||_(r.max)&&D&&Ki(r.max,D),N=b*lp(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),G={},O=$.filter(F=>(v?Ki(F.quality,v):!0)?(_(t)&&isFinite(t)&&_(F.bitrate)?t-a>=F.bitrate*N:!0)?i.lazyQualitySwitch&&_(i.minBufferToSwitchUp)&&u&&!vi(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&pi(F.quality,u.quality)?(G[F.quality]=Pt.Buffer,!1):!!l&&Tr(F.quality,l)?(G[F.quality]=Pt.DroppedFramesLimit,!1):J||(te(r.max)||Nn(F.quality,r.max))&&(te(r.min)||Tr(F.quality,r.min))?!0:(G[F.quality]=Pt.FitsQualityLimits,!1):(G[F.quality]=Pt.FitsThroughput,!1):(G[F.quality]=Pt.FitsContainer,!1))[0];O&&O.bitrate&&up.next(O.bitrate);const H=(g=O!=null?O:$[Math.ceil(($.length-1)/2)])!==null&&g!==void 0?g:s[0];H.quality!==((T=d==null?void 0:d.last)===null||T===void 0?void 0:T.quality)&&c({message:`
|
|
6
|
+
import{ValueSubject as S,Subject as L,Subscription as re,isNonNullable as _,ErrorCategory as C,isNullable as te,fromEvent as B,assertNever as V,merge as U,tap as ts,map as w,observableFrom as ke,filterChanged as fe,assertNonNullable as P,debounce as Me,getHighestQuality as hd,timeout as fd,getCurrentBrowser as Br,CurrentClientBrowser as Mn,combine as Ie,once as me,mapTo as Wt,filter as se,now as pe,videoSizeToQuality as Rt,isInvariantQuality as vi,isHigher as pi,isLower as Ki,isHigherOrEqual as Tr,isLowerOrEqual as Nn,Observable as cs,interval as is,VideoQuality as Ce,videoQualityToHeight as pd,abortable as Re,getExponentialDelay as fa,throttle as md,CurrentClientDevice as vd,safeStorage as Cs,fillWithDefault as gd,Logger as Sd}from"@vkontakte/videoplayer-shared/es2018.esm.js";import{Observable as Zv,Subject as eg,Subscription as tg,ValueSubject as ig,VideoQuality as sg}from"@vkontakte/videoplayer-shared/es2018.esm.js";import bd from"lodash/debounce.js";const yd="2.0.96";var p;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(p||(p={}));var y;(function(s){s.MPEG="MPEG",s.DASH="DASH",s.DASH_SEP="DASH_SEP",s.DASH_SEP_VK="DASH_SEP",s.DASH_WEBM="DASH_WEBM",s.DASH_WEBM_AV1="DASH_WEBM_AV1",s.DASH_WEBM_VK="DASH_WEBM",s.DASH_ONDEMAND="DASH_ONDEMAND",s.DASH_ONDEMAND_VK="DASH_ONDEMAND",s.DASH_LIVE="DASH_LIVE",s.DASH_LIVE_CMAF="DASH_LIVE_CMAF",s.DASH_LIVE_WEBM="DASH_LIVE_WEBM",s.HLS="HLS",s.HLS_ONDEMAND="HLS_ONDEMAND",s.HLS_JS="HLS",s.HLS_LIVE="HLS_LIVE",s.HLS_LIVE_CMAF="HLS_LIVE_CMAF",s.WEB_RTC_LIVE="WEB_RTC_LIVE"})(y||(y={}));var Ee;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(Ee||(Ee={}));var ye;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})(ye||(ye={}));var gi;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(gi||(gi={}));var z;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(z||(z={}));var gt;(function(s){s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip"})(gt||(gt={}));var Td=s=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class Ed{constructor(e){var t;this.connection$=new S(void 0),this.castState$=new S(ye.NOT_AVAILABLE),this.errorEvent$=new L,this.realCastState$=new S(ye.NOT_AVAILABLE),this.subscription=new re,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const i="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${i}`}),e.isDisabled||!i)return;const r=_((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||Td("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:C.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())===null||i===void 0?void 0:i.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||a===void 0||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){_(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();te(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();te(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(B(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(a=i.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return V(r.sessionState)}})).add(U(B(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(ts(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),w(r=>r.castState)),ke([i.getCastState()])).pipe(fe(),w($d),ts(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===ye.CONNECTED,o=_(this.connection$.getValue());if(n&&!o){const u=i.getCurrentSession();P(u);const d=u.getCastDevice(),l=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(te(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===ye.CONNECTED?_(this.connection$.getValue())?ye.CONNECTED:ye.AVAILABLE:r)}))}initializeCastApi(){var e;let t,i,r;try{t=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:i,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:C.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const $d=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return ye.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return ye.AVAILABLE;case cast.framework.CastState.CONNECTING:return ye.CONNECTING;case cast.framework.CastState.CONNECTED:return ye.CONNECTED;default:return V(s)}};var Os=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Mr(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var nt=function(s){try{return!!s()}catch(e){return!0}},Ad=nt,hs=!Ad(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),Fn=hs,Un=Function.prototype,Er=Un.call,kd=Fn&&Un.bind.bind(Er,Er),ot=Fn?kd:function(s){return function(){return Er.apply(s,arguments)}},Vn=ot,wd=Vn({}.toString),_d=Vn("".slice),fs=function(s){return _d(wd(s),8,-1)},Pd=ot,Dd=nt,Rd=fs,Bs=Object,Id=Pd("".split),xd=Dd(function(){return!Bs("z").propertyIsEnumerable(0)})?function(s){return Rd(s)=="String"?Id(s,""):Bs(s)}:Bs,ps=function(s){return s==null},Ld=ps,Cd=TypeError,Nr=function(s){if(Ld(s))throw Cd("Can't call method on "+s);return s},Od=xd,Bd=Nr,Ti=function(s){return Od(Bd(s))},Zt={},xi=function(s){return s&&s.Math==Math&&s},Ye=xi(typeof globalThis=="object"&&globalThis)||xi(typeof window=="object"&&window)||xi(typeof self=="object"&&self)||xi(typeof Os=="object"&&Os)||function(){return this}()||Os||Function("return this")(),$r=typeof document=="object"&&document.all,Md=typeof $r=="undefined"&&$r!==void 0,Hn={all:$r,IS_HTMLDDA:Md},Gn=Hn,Nd=Gn.all,Ne=Gn.IS_HTMLDDA?function(s){return typeof s=="function"||s===Nd}:function(s){return typeof s=="function"},Fd=Ye,Ud=Ne,pa=Fd.WeakMap,Vd=Ud(pa)&&/native code/.test(String(pa)),ma=Ne,Yn=Hn,Hd=Yn.all,It=Yn.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:ma(s)||s===Hd}:function(s){return typeof s=="object"?s!==null:ma(s)},Gd=nt,xt=!Gd(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),ei={},Yd=Ye,va=It,Ar=Yd.document,qd=va(Ar)&&va(Ar.createElement),qn=function(s){return qd?Ar.createElement(s):{}},jd=xt,zd=nt,Wd=qn,jn=!jd&&!zd(function(){return Object.defineProperty(Wd("div"),"a",{get:function(){return 7}}).a!=7}),Qd=xt,Kd=nt,zn=Qd&&Kd(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Jd=It,Xd=String,Zd=TypeError,Lt=function(s){if(Jd(s))return s;throw Zd(Xd(s)+" is not an object")},eu=hs,Li=Function.prototype.call,dt=eu?Li.bind(Li):function(){return Li.apply(Li,arguments)},Fr={},Ms=Fr,Ns=Ye,tu=Ne,ga=function(s){return tu(s)?s:void 0},Ur=function(s,e){return arguments.length<2?ga(Ms[s])||ga(Ns[s]):Ms[s]&&Ms[s][e]||Ns[s]&&Ns[s][e]},iu=ot,Vr=iu({}.isPrototypeOf),su=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Wn=Ye,Fs=su,Sa=Wn.process,ba=Wn.Deno,ya=Sa&&Sa.versions||ba&&ba.version,Ta=ya&&ya.v8,Ve,ss;Ta&&(Ve=Ta.split("."),ss=Ve[0]>0&&Ve[0]<4?1:+(Ve[0]+Ve[1]));!ss&&Fs&&(Ve=Fs.match(/Edge\/(\d+)/),(!Ve||Ve[1]>=74)&&(Ve=Fs.match(/Chrome\/(\d+)/),Ve&&(ss=+Ve[1])));var ru=ss,Ea=ru,au=nt,nu=Ye,ou=nu.String,Qn=!!Object.getOwnPropertySymbols&&!au(function(){var s=Symbol();return!ou(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Ea&&Ea<41}),du=Qn,Kn=du&&!Symbol.sham&&typeof Symbol.iterator=="symbol",uu=Ur,lu=Ne,cu=Vr,hu=Kn,fu=Object,Jn=hu?function(s){return typeof s=="symbol"}:function(s){var e=uu("Symbol");return lu(e)&&cu(e.prototype,fu(s))},pu=String,Hr=function(s){try{return pu(s)}catch(e){return"Object"}},mu=Ne,vu=Hr,gu=TypeError,Gr=function(s){if(mu(s))return s;throw gu(vu(s)+" is not a function")},Su=Gr,bu=ps,ms=function(s,e){var t=s[e];return bu(t)?void 0:Su(t)},Us=dt,Vs=Ne,Hs=It,yu=TypeError,Tu=function(s,e){var t,i;if(e==="string"&&Vs(t=s.toString)&&!Hs(i=Us(t,s))||Vs(t=s.valueOf)&&!Hs(i=Us(t,s))||e!=="string"&&Vs(t=s.toString)&&!Hs(i=Us(t,s)))return i;throw yu("Can't convert object to primitive value")},Xn={exports:{}},$a=Ye,Eu=Object.defineProperty,$u=function(s,e){try{Eu($a,s,{value:e,configurable:!0,writable:!0})}catch(t){$a[s]=e}return e},Au=Ye,ku=$u,Aa="__core-js_shared__",wu=Au[Aa]||ku(Aa,{}),Zn=wu,ka=Zn;(Xn.exports=function(s,e){return ka[s]||(ka[s]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"});var eo=Xn.exports,_u=Nr,Pu=Object,vs=function(s){return Pu(_u(s))},Du=ot,Ru=vs,Iu=Du({}.hasOwnProperty),ut=Object.hasOwn||function(e,t){return Iu(Ru(e),t)},xu=ot,Lu=0,Cu=Math.random(),Ou=xu(1 .toString),to=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Ou(++Lu+Cu,36)},Bu=Ye,Mu=eo,wa=ut,Nu=to,Fu=Qn,Uu=Kn,qt=Bu.Symbol,Gs=Mu("wks"),Vu=Uu?qt.for||qt:qt&&qt.withoutSetter||Nu,qe=function(s){return wa(Gs,s)||(Gs[s]=Fu&&wa(qt,s)?qt[s]:Vu("Symbol."+s)),Gs[s]},Hu=dt,_a=It,Pa=Jn,Gu=ms,Yu=Tu,qu=qe,ju=TypeError,zu=qu("toPrimitive"),Wu=function(s,e){if(!_a(s)||Pa(s))return s;var t=Gu(s,zu),i;if(t){if(e===void 0&&(e="default"),i=Hu(t,s,e),!_a(i)||Pa(i))return i;throw ju("Can't convert object to primitive value")}return e===void 0&&(e="number"),Yu(s,e)},Qu=Wu,Ku=Jn,Yr=function(s){var e=Qu(s,"string");return Ku(e)?e:e+""},Ju=xt,Xu=jn,Zu=zn,Ci=Lt,Da=Yr,el=TypeError,Ys=Object.defineProperty,tl=Object.getOwnPropertyDescriptor,qs="enumerable",js="configurable",zs="writable";ei.f=Ju?Zu?function(e,t,i){if(Ci(e),t=Da(t),Ci(i),typeof e=="function"&&t==="prototype"&&"value"in i&&zs in i&&!i[zs]){var r=tl(e,t);r&&r[zs]&&(e[t]=i.value,i={configurable:js in i?i[js]:r[js],enumerable:qs in i?i[qs]:r[qs],writable:!1})}return Ys(e,t,i)}:Ys:function(e,t,i){if(Ci(e),t=Da(t),Ci(i),Xu)try{return Ys(e,t,i)}catch(r){}if("get"in i||"set"in i)throw el("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var gs=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},il=xt,sl=ei,rl=gs,Ei=il?function(s,e,t){return sl.f(s,e,rl(1,t))}:function(s,e,t){return s[e]=t,s},al=eo,nl=to,Ra=al("keys"),qr=function(s){return Ra[s]||(Ra[s]=nl(s))},jr={},ol=Vd,io=Ye,dl=It,ul=Ei,Ws=ut,Qs=Zn,ll=qr,cl=jr,Ia="Object already initialized",kr=io.TypeError,hl=io.WeakMap,rs,Si,as,fl=function(s){return as(s)?Si(s):rs(s,{})},pl=function(s){return function(e){var t;if(!dl(e)||(t=Si(e)).type!==s)throw kr("Incompatible receiver, "+s+" required");return t}};if(ol||Qs.state){var ze=Qs.state||(Qs.state=new hl);ze.get=ze.get,ze.has=ze.has,ze.set=ze.set,rs=function(s,e){if(ze.has(s))throw kr(Ia);return e.facade=s,ze.set(s,e),e},Si=function(s){return ze.get(s)||{}},as=function(s){return ze.has(s)}}else{var Ut=ll("state");cl[Ut]=!0,rs=function(s,e){if(Ws(s,Ut))throw kr(Ia);return e.facade=s,ul(s,Ut,e),e},Si=function(s){return Ws(s,Ut)?s[Ut]:{}},as=function(s){return Ws(s,Ut)}}var ml={set:rs,get:Si,has:as,enforce:fl,getterFor:pl},vl=hs,so=Function.prototype,xa=so.apply,La=so.call,gl=typeof Reflect=="object"&&Reflect.apply||(vl?La.bind(xa):function(){return La.apply(xa,arguments)}),Sl=fs,bl=ot,ro=function(s){if(Sl(s)==="Function")return bl(s)},ao={},no={},oo={}.propertyIsEnumerable,uo=Object.getOwnPropertyDescriptor,yl=uo&&!oo.call({1:2},1);no.f=yl?function(e){var t=uo(this,e);return!!t&&t.enumerable}:oo;var Tl=xt,El=dt,$l=no,Al=gs,kl=Ti,wl=Yr,_l=ut,Pl=jn,Ca=Object.getOwnPropertyDescriptor;ao.f=Tl?Ca:function(e,t){if(e=kl(e),t=wl(t),Pl)try{return Ca(e,t)}catch(i){}if(_l(e,t))return Al(!El($l.f,e,t),e[t])};var Dl=nt,Rl=Ne,Il=/#|\.prototype\./,$i=function(s,e){var t=Ll[xl(s)];return t==Ol?!0:t==Cl?!1:Rl(e)?Dl(e):!!e},xl=$i.normalize=function(s){return String(s).replace(Il,".").toLowerCase()},Ll=$i.data={},Cl=$i.NATIVE="N",Ol=$i.POLYFILL="P",Bl=$i,Oa=ro,Ml=Gr,Nl=hs,Fl=Oa(Oa.bind),lo=function(s,e){return Ml(s),e===void 0?s:Nl?Fl(s,e):function(){return s.apply(e,arguments)}},Oi=Ye,Ul=gl,Vl=ro,Hl=Ne,Gl=ao.f,Yl=Bl,Vt=Fr,ql=lo,Ht=Ei,Ba=ut,jl=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return Ul(s,this,arguments)};return e.prototype=s.prototype,e},Ss=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?Oi:r?Oi[t]:(Oi[t]||{}).prototype,o=i?Vt:Vt[t]||Ht(Vt,t,{})[t],u=o.prototype,d,l,c,h,f,m,g,T,A;for(h in e)d=Yl(i?h:t+(r?".":"#")+h,s.forced),l=!d&&n&&Ba(n,h),m=o[h],l&&(s.dontCallGetSet?(A=Gl(n,h),g=A&&A.value):g=n[h]),f=l&&g?g:e[h],!(l&&typeof m==typeof f)&&(s.bind&&l?T=ql(f,Oi):s.wrap&&l?T=jl(f):a&&Hl(f)?T=Vl(f):T=f,(s.sham||f&&f.sham||m&&m.sham)&&Ht(T,"sham",!0),Ht(o,h,T),a&&(c=t+"Prototype",Ba(Vt,c)||Ht(Vt,c,{}),Ht(Vt[c],h,f),s.real&&u&&(d||!u[h])&&Ht(u,h,f)))},wr=xt,zl=ut,co=Function.prototype,Wl=wr&&Object.getOwnPropertyDescriptor,zr=zl(co,"name"),Ql=zr&&function(){}.name==="something",Kl=zr&&(!wr||wr&&Wl(co,"name").configurable),Jl={EXISTS:zr,PROPER:Ql,CONFIGURABLE:Kl},ho={},Xl=Math.ceil,Zl=Math.floor,ec=Math.trunc||function(e){var t=+e;return(t>0?Zl:Xl)(t)},tc=ec,Wr=function(s){var e=+s;return e!==e||e===0?0:tc(e)},ic=Wr,sc=Math.max,rc=Math.min,ac=function(s,e){var t=ic(s);return t<0?sc(t+e,0):rc(t,e)},nc=Wr,oc=Math.min,dc=function(s){return s>0?oc(nc(s),9007199254740991):0},uc=dc,Qr=function(s){return uc(s.length)},lc=Ti,cc=ac,hc=Qr,Ma=function(s){return function(e,t,i){var r=lc(e),a=hc(r),n=cc(i,a),o;if(s&&t!=t){for(;a>n;)if(o=r[n++],o!=o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}},fc={includes:Ma(!0),indexOf:Ma(!1)},pc=ot,Ks=ut,mc=Ti,vc=fc.indexOf,gc=jr,Na=pc([].push),Sc=function(s,e){var t=mc(s),i=0,r=[],a;for(a in t)!Ks(gc,a)&&Ks(t,a)&&Na(r,a);for(;e.length>i;)Ks(t,a=e[i++])&&(~vc(r,a)||Na(r,a));return r},fo=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],bc=Sc,yc=fo,Tc=Object.keys||function(e){return bc(e,yc)},Ec=xt,$c=zn,Ac=ei,kc=Lt,wc=Ti,_c=Tc;ho.f=Ec&&!$c?Object.defineProperties:function(e,t){kc(e);for(var i=wc(t),r=_c(t),a=r.length,n=0,o;a>n;)Ac.f(e,o=r[n++],i[o]);return e};var Pc=Ur,Dc=Pc("document","documentElement"),Rc=Lt,Ic=ho,Fa=fo,xc=jr,Lc=Dc,Cc=qn,Oc=qr,Ua=">",Va="<",_r="prototype",Pr="script",po=Oc("IE_PROTO"),Js=function(){},mo=function(s){return Va+Pr+Ua+s+Va+"/"+Pr+Ua},Ha=function(s){s.write(mo("")),s.close();var e=s.parentWindow.Object;return s=null,e},Bc=function(){var s=Cc("iframe"),e="java"+Pr+":",t;return s.style.display="none",Lc.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(mo("document.F=Object")),t.close(),t.F},Bi,Ji=function(){try{Bi=new ActiveXObject("htmlfile")}catch(e){}Ji=typeof document!="undefined"?document.domain&&Bi?Ha(Bi):Bc():Ha(Bi);for(var s=Fa.length;s--;)delete Ji[_r][Fa[s]];return Ji()};xc[po]=!0;var vo=Object.create||function(e,t){var i;return e!==null?(Js[_r]=Rc(e),i=new Js,Js[_r]=null,i[po]=e):i=Ji(),t===void 0?i:Ic.f(i,t)},Mc=nt,Nc=!Mc(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),Fc=ut,Uc=Ne,Vc=vs,Hc=qr,Gc=Nc,Ga=Hc("IE_PROTO"),Dr=Object,Yc=Dr.prototype,go=Gc?Dr.getPrototypeOf:function(s){var e=Vc(s);if(Fc(e,Ga))return e[Ga];var t=e.constructor;return Uc(t)&&e instanceof t?t.prototype:e instanceof Dr?Yc:null},qc=Ei,So=function(s,e,t,i){return i&&i.enumerable?s[e]=t:qc(s,e,t),s},jc=nt,zc=Ne,Wc=It,Qc=vo,Ya=go,Kc=So,Jc=qe,Rr=Jc("iterator"),bo=!1,st,Xs,Zs;[].keys&&(Zs=[].keys(),"next"in Zs?(Xs=Ya(Ya(Zs)),Xs!==Object.prototype&&(st=Xs)):bo=!0);var Xc=!Wc(st)||jc(function(){var s={};return st[Rr].call(s)!==s});Xc?st={}:st=Qc(st);zc(st[Rr])||Kc(st,Rr,function(){return this});var yo={IteratorPrototype:st,BUGGY_SAFARI_ITERATORS:bo},Zc=qe,eh=Zc("toStringTag"),To={};To[eh]="z";var Kr=String(To)==="[object z]",th=Kr,ih=Ne,Xi=fs,sh=qe,rh=sh("toStringTag"),ah=Object,nh=Xi(function(){return arguments}())=="Arguments",oh=function(s,e){try{return s[e]}catch(t){}},bs=th?Xi:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=oh(e=ah(s),rh))=="string"?t:nh?Xi(e):(i=Xi(e))=="Object"&&ih(e.callee)?"Arguments":i},dh=Kr,uh=bs,lh=dh?{}.toString:function(){return"[object "+uh(this)+"]"},ch=Kr,hh=ei.f,fh=Ei,ph=ut,mh=lh,vh=qe,qa=vh("toStringTag"),Eo=function(s,e,t,i){if(s){var r=t?s:s.prototype;ph(r,qa)||hh(r,qa,{configurable:!0,value:e}),i&&!ch&&fh(r,"toString",mh)}},gh=yo.IteratorPrototype,Sh=vo,bh=gs,yh=Eo,Th=Zt,Eh=function(){return this},$h=function(s,e,t,i){var r=e+" Iterator";return s.prototype=Sh(gh,{next:bh(+!i,t)}),yh(s,r,!1,!0),Th[r]=Eh,s},Ah=Ss,kh=dt,$o=Jl,wh=$h,_h=go,Ph=Eo,ja=So,Dh=qe,za=Zt,Ao=yo,Rh=$o.PROPER;$o.CONFIGURABLE;Ao.IteratorPrototype;var Mi=Ao.BUGGY_SAFARI_ITERATORS,er=Dh("iterator"),Wa="keys",Ni="values",Qa="entries",Ih=function(){return this},xh=function(s,e,t,i,r,a,n){wh(t,e,i);var o=function(A){if(A===r&&h)return h;if(!Mi&&A in l)return l[A];switch(A){case Wa:return function(){return new t(this,A)};case Ni:return function(){return new t(this,A)};case Qa:return function(){return new t(this,A)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,l=s.prototype,c=l[er]||l["@@iterator"]||r&&l[r],h=!Mi&&c||o(r),f=e=="Array"&&l.entries||c,m,g,T;if(f&&(m=_h(f.call(new s)),m!==Object.prototype&&m.next&&(Ph(m,u,!0,!0),za[u]=Ih)),Rh&&r==Ni&&c&&c.name!==Ni&&(d=!0,h=function(){return kh(c,this)}),r)if(g={values:o(Ni),keys:a?h:o(Wa),entries:o(Qa)},n)for(T in g)(Mi||d||!(T in l))&&ja(l,T,g[T]);else Ah({target:e,proto:!0,forced:Mi||d},g);return n&&l[er]!==h&&ja(l,er,h,{name:r}),za[e]=h,g},Lh=function(s,e){return{value:s,done:e}},Ch=Ti,Ka=Zt,ko=ml;ei.f;var Oh=xh,Fi=Lh,wo="Array Iterator",Bh=ko.set,Mh=ko.getterFor(wo);Oh(Array,"Array",function(s,e){Bh(this,{type:wo,target:Ch(s),index:0,kind:e})},function(){var s=Mh(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,Fi(void 0,!0)):t=="keys"?Fi(i,!1):t=="values"?Fi(e[i],!1):Fi([i,e[i]],!1)},"values");Ka.Arguments=Ka.Array;var Nh=qe,Fh=Zt,Uh=Nh("iterator"),Vh=Array.prototype,Hh=function(s){return s!==void 0&&(Fh.Array===s||Vh[Uh]===s)},Gh=bs,Ja=ms,Yh=ps,qh=Zt,jh=qe,zh=jh("iterator"),_o=function(s){if(!Yh(s))return Ja(s,zh)||Ja(s,"@@iterator")||qh[Gh(s)]},Wh=dt,Qh=Gr,Kh=Lt,Jh=Hr,Xh=_o,Zh=TypeError,ef=function(s,e){var t=arguments.length<2?Xh(s):e;if(Qh(t))return Kh(Wh(t,s));throw Zh(Jh(s)+" is not iterable")},tf=dt,Xa=Lt,sf=ms,rf=function(s,e,t){var i,r;Xa(s);try{if(i=sf(s,"return"),!i){if(e==="throw")throw t;return t}i=tf(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return Xa(i),t},af=lo,nf=dt,of=Lt,df=Hr,uf=Hh,lf=Qr,Za=Vr,cf=ef,hf=_o,en=rf,ff=TypeError,Zi=function(s,e){this.stopped=s,this.result=e},tn=Zi.prototype,pf=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=af(e,i),d,l,c,h,f,m,g,T=function(E){return d&&en(d,"normal",E),new Zi(!0,E)},A=function(E){return r?(of(E),o?u(E[0],E[1],T):u(E[0],E[1])):o?u(E,T):u(E)};if(a)d=s.iterator;else if(n)d=s;else{if(l=hf(s),!l)throw ff(df(s)+" is not iterable");if(uf(l)){for(c=0,h=lf(s);h>c;c++)if(f=A(s[c]),f&&Za(tn,f))return f;return new Zi(!1)}d=cf(s,l)}for(m=a?s.next:d.next;!(g=nf(m,d)).done;){try{f=A(g.value)}catch(E){en(d,"throw",E)}if(typeof f=="object"&&f&&Za(tn,f))return f}return new Zi(!1)},mf=Yr,vf=ei,gf=gs,Sf=function(s,e,t){var i=mf(e);i in s?vf.f(s,i,gf(0,t)):s[i]=t},bf=Ss,yf=pf,Tf=Sf;bf({target:"Object",stat:!0},{fromEntries:function(e){var t={};return yf(e,function(i,r){Tf(t,i,r)},{AS_ENTRIES:!0}),t}});var Ef=Fr,$f=Ef.Object.fromEntries,Af={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},kf=Af,wf=Ye,_f=bs,Pf=Ei,sn=Zt,Df=qe,rn=Df("toStringTag");for(var tr in kf){var an=wf[tr],ir=an&&an.prototype;ir&&_f(ir)!==rn&&Pf(ir,rn,tr),sn[tr]=sn.Array}var Rf=$f,If=Rf,xf=If,Lf=xf,Qt=Mr(Lf),be;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",s[s.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(be||(be={}));var He=(s,e=0,t=be.OFFSET_P)=>{switch(t){case be.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case be.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case be.DASH_CMAF_OFFSET_P:{if(e===0)return s;const i=new URL(s);return i.searchParams.set("offset_p",e.toFixed(0)),i.toString()}default:V(t)}return s};const nn=(s,e)=>{var t;switch(e){case be.OFFSET_P:return NaN;case be.PLAYBACK_SHIFT:{const i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case be.DASH_CMAF_OFFSET_P:{const i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:V(e)}};var R=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};class ue{constructor(e){this.transitionStarted$=new L,this.transitionEnded$=new L,this.transitionUpdated$=new L,this.forceChanged$=new L,this.stateChangeStarted$=U(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=U(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||_(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const Cf=s=>{switch(s){case y.MPEG:case y.DASH:case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.HLS:case y.HLS_ONDEMAND:return!1;case y.DASH_LIVE:case y.DASH_LIVE_CMAF:case y.HLS_LIVE:case y.HLS_LIVE_CMAF:case y.DASH_LIVE_WEBM:case y.WEB_RTC_LIVE:return!0;default:return V(s)}};var q;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(q||(q={}));const Of=5,Bf=5,Mf=500,on=7e3;class Nf{constructor(e){this.subscription=new re,this.loadMediaTimeoutSubscription=new re,this.videoState=new ue(q.STOPPED),this.syncPlayback=()=>{const i=this.videoState.getState(),r=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${a}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(o)};`}),a===p.STOPPED){i!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==p.PAUSED&&o.state===z.Requested&&i!==q.STOPPED){this.seek(o.position/1e3);return}switch(a){case p.READY:{switch(i){case q.PLAYING:case q.PAUSED:case q.READY:break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:V(i)}break}case p.PLAYING:{switch(i){case q.PLAYING:break;case q.PAUSED:this.videoState.startTransitionTo(q.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case q.READY:this.videoState.startTransitionTo(q.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:V(i)}break}case p.PAUSED:{switch(i){case q.PLAYING:this.videoState.startTransitionTo(q.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case q.PAUSED:break;case q.READY:this.videoState.startTransitionTo(q.PAUSED),this.videoState.setState(q.PAUSED);break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:V(i)}break}default:V(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Cf(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new re;this.subscription.add(e),this.subscription.add(U(this.videoState.stateChangeStarted$.pipe(w(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(w(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));const t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const r=new L;e.add(r.pipe(Me(Mf)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===z.Applying||Math.abs(o-a)>Of)&&r.next(o),a=o})),e.add(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<Bf&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),R(this.params.desiredState.playbackState,p.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:V(n)}}),t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const i=U(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Me(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(q.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED)):(this.videoState.setState(q.PLAYING),R(this.params.desiredState.playbackState,p.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:z.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===q.PAUSED||e===q.PLAYING)&&(this.videoState.setState(q.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===q.PLAYING||e===q.PAUSED)&&(this.videoState.setState(q.PLAYING),R(this.params.desiredState.playbackState,p.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===q.READY&&this.videoState.setState(q.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===p.READY&&R(this.params.desiredState.playbackState,p.READY)}handleRemoteStop(){this.videoState.getState()!==q.STOPPED&&this.videoState.setState(q.STOPPED)}handleRemoteVolumeChange(e){var t,i;const r=this.params.output.volume$.getValue(),a={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(i=e.muted)!==null&&i!==void 0?i:r.muted};(a.volume!==r.volume||a.muted!==a.muted)&&this.params.output.volume$.next(a)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const i=this.params.source;let r,a,n;switch(e){case y.MPEG:{const l=i[e];P(l);const c=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 y.HLS:case y.HLS_ONDEMAND:{const l=i[e];P(l),r=l.url,a="application/x-mpegurl",n=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.DASH_WEBM_AV1:{const l=i[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_LIVE_CMAF:{const l=i[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const l=i[e];P(l),r=He(l.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case y.DASH:case y.DASH_LIVE:case y.WEB_RTC_LIVE:{const l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:C.VIDEO_PIPELINE,message:l,thrown:c}),c}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return V(e)}const o=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,a);o.contentUrl=r,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return _(u)&&(o.metadata.title=u),_(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===z.Applying||i.state===z.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(fd(on).subscribe(()=>a(`timeout(${on})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===z.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{const a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:C.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}var Ff=s=>{let e,t=!1,i=!1;s.on("playbackTimeUpdated",({timeToEnd:r})=>{i=r<=3,t&&i&&(e==null||e())}),s.extend("MediaSourceController",function(){const{parent:r}=this,a=r.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>a(n),t&&i&&(e==null||e())}}},!0)},Uf=s=>{const e=new S(1/0),t=new L,i=new S(void 0),r=new S(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},u=l=>{var c,h,f,m,g;const T=Qt(l.getAllResponseHeaders().trim().split(/[\n\r]+/).map(v=>v.split(": ")));if("x-playback-duration"in T||"x-playback-duration-millis"in T){const v=parseInt((c=l.getResponseHeader("X-Playback-Duration"))!==null&&c!==void 0?c:"",10),b=parseInt((h=l.getResponseHeader("X-Playback-Duration-Millis"))!==null&&h!==void 0?h:"",10),$=(f=b!=null?b:v*1e3)!==null&&f!==void 0?f:NaN;_($)&&!isNaN($)&&e.next($)}const A=(m=T["x-delivery-type"])!==null&&m!==void 0?m:gi.HTTP1,E=(g={1:!0,0:!1}[T["x-reused"]])!==null&&g!==void 0?g:void 0;i.next(A),r.next(E)},d=l=>{l.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return s.extend("XHRLoader",function(){const{parent:l}=this,c=l.load.bind(l);return{load:function(h){if(h.request.type==="MPD"){const f=h.onload,m=h.progress;h.onload=function(...g){return u(this),f(...g)},h.progress=function(...g){return d(this),m(...g)},o()}return c(h)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:i}},Kt=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},Vf=s=>s.extend("RequestModifier",()=>({modifyRequestURL:Kt}),!0),Hf=s=>{s.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[r,a]=i.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(i.request.url,location.href);n.searchParams.append("bytes",`${r}-${a}`),i.request.url=n.toString(),i.request.range=void 0}t(i)}}},!0)};const Ge=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=s.getState(),o=e(),u=te(r),d=new re;return r&&d.add(r.subscribe(l=>{const c=s.getState();i(l,c)&&s.setState(l)},a)),i(o,n)||(t(n),u&&s.setState(n)),d.add(s.stateChangeStarted$.subscribe(l=>{t(l.to),u&&s.setState(l.to)},a)),d},Ct=(s,e,t)=>Ge(e,()=>s.loop,i=>{_(i)&&(s.loop=i)},{onError:t}),lt=(s,e,t,i)=>Ge(e,()=>({muted:s.muted,volume:s.volume}),r=>{_(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),Tt=(s,e,t,i)=>Ge(e,()=>s.playbackRate,r=>{_(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Gf=s=>["__",s.language,s.label].join("|"),Yf=(s,e)=>{if(s.id===e)return!0;const[t,i,r]=e.split("|");return s.language===i&&s.label===r};class Ze{constructor(){this.available$=new L,this.current$=new S(void 0),this.error$=new L,this.subscription=new re,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:C.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Ge(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{_(a)&&this.setInternal(a)},{equal:(a,n)=>_(a)&&_(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(w(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Ge(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{_(a)&&this.setExternal(a)},{equal:(a,n)=>_(a)&&_(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(w(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Ge(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(Ge(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){P(this.video);const{textTracks:e}=this.video;this.subscription.add(B(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(U(B(e,"addtrack"),B(e,"removetrack"),ke(["init"])).pipe(w(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),fe((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(U(B(e,"change"),ke(["init"])).pipe(w(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),w(i=>i&&this.htmlTextTrackToITextTrack(i).id),fe()).subscribe(this.current$));const t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(B(e,"addtrack").subscribe(i=>{var r,a;(r=i.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var u,d,l,c,h;const f=(d=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&d!==void 0?d:null;f&&f.length&&(this.applyCueSettings((c=(l=o.target)===null||l===void 0?void 0:l.cues)!==null&&c!==void 0?c:null),(h=o.target)===null||h===void 0||h.removeEventListener("cuechange",n))};(a=i.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(B(e,"removetrack").subscribe(i=>{var r;(r=i.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const r=i;_(t.align)&&(r.align=t.align),_(t.position)&&(r.position=t.position),_(t.size)&&(r.size=t.size),_(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){P(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Ze.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,i;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:(i=this.internalTracks.get(n))===null||i===void 0?void 0:i.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){P(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(te(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"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const Jr=s=>{s.removeAttribute("src"),s.load()},qf=s=>{try{s.pause(),s.playbackRate=0,Jr(s),s.remove()}catch(e){console.error(e)}};class jf{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 Ir=window.WeakMap?new WeakMap:new jf,ct=s=>{let e=s.querySelector("video");const t=!!e;return e?Jr(e):(e=document.createElement("video"),s.appendChild(e)),Ir.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},ht=s=>{const e=Ir.get(s);Ir.delete(s),e?Jr(s):qf(s)};class ys{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=s=>{var e;let t=s;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},dn=s=>{const e=Po(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},zf=s=>{const e=Po(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)},xr=3;class Wf{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let r=this._source.buffered.start(t);const a=this._source.buffered.end(t);r>e&&r-e<xr&&(r=e),this._buffer.push({from:r,to:a,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||xr))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:r,to:a})=>{const n=r>=e&&r<t,o=a>=e&&a<t;n&&o||(n?i(t,a):o?i(r,e):r<e&&a>t?(i(t,a),i(r,e)):i(r,a))})}destroy(){this._buffer=[]}}var Do=(s,e,t=xr)=>{let i=0,r=0;for(let a=0;a<s.length;a++){const n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};const ft=s=>{const e=v=>B(s,v).pipe(Wt(void 0)),i=U(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>B(s,v))).pipe(w(v=>v.type==="ended"?s.readyState<2:s.readyState<3),fe()),r=U(B(s,"progress"),B(s,"timeupdate")).pipe(w(()=>Do(s.buffered,s.currentTime))),n=Br().browser===Mn.Safari?Ie({play:e("play").pipe(me()),playing:e("playing")}).pipe(Wt(void 0)):e("playing"),o=B(s,"volumechange").pipe(w(()=>({muted:s.muted,volume:s.volume}))),u=B(s,"ratechange").pipe(w(()=>s.playbackRate)),d=B(s,"error").pipe(se(()=>!!(s.error||s.played.length)),w(()=>{var v;const b=s.error;return{id:b?`MediaError#${b.code}`:"HtmlVideoError",category:C.VIDEO_PIPELINE,message:b?b.message:"Error event from HTML video element",thrown:(v=s.error)!==null&&v!==void 0?v:void 0}})),l=B(s,"timeupdate").pipe(w(()=>s.currentTime)),c=new L,h=.3;let f;l.subscribe(v=>{s.loop&&_(f)&&_(v)&&f>=s.duration-h&&v<=h&&c.next(f),f=v});const m=B(s,"enterpictureinpicture"),g=B(s,"leavepictureinpicture"),T=new S(zf(s));m.subscribe(()=>T.next(!0)),g.subscribe(()=>T.next(!1));const A=new S(dn(s));return B(s,"fullscreenchange").pipe(w(()=>dn(s))).subscribe(A),{playing$:n,pause$:e("pause").pipe(se(()=>!s.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:B(s,"durationchange").pipe(w(()=>s.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:o,playbackRateState$:u,inPiP$:T,inFullscreen$:A}},Xr=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var Qf=Ss,Kf=vs,Jf=Qr,Xf=Wr;Qf({target:"Array",proto:!0},{at:function(e){var t=Kf(this),i=Jf(t),r=Xf(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});var Zf=Ur,Ro=Zf,ep=Ro,tp=ep("Array","at"),ip=tp,sp=ip,rp=sp,ap=rp,Qe=Mr(ap);let Zr=!1,it={};const np=s=>{Zr=s},op=()=>{it={}},dp=s=>{s(it)},Ui=(s,e)=>{var t;Zr&&(it.meta=(t=it.meta)!==null&&t!==void 0?t:{},it.meta[s]=e)};class Ke{constructor(e){this.name=e}next(e){var t,i;if(!Zr)return;it.series=(t=it.series)!==null&&t!==void 0?t:{};const r=(i=it.series[this.name])!==null&&i!==void 0?i:[];r.push([Date.now(),e]),it.series[this.name]=r}}var Pt;(function(s){s.FitsContainer="FitsContainer",s.FitsThroughput="FitsThroughput",s.Buffer="Buffer",s.DroppedFramesLimit="DroppedFramesLimit",s.FitsQualityLimits="FitsQualityLimits"})(Pt||(Pt={}));const up=new Ke("best_bitrate"),lp=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class cp{constructor(){this.history={}}recordSelection(e){this.history[e.id]=pe()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const ti=(s,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:d,droppedVideoMaxQualityLimit:l,abrLogger:c})=>{var h,f,m,g,T;const A=i.usePixelRatio&&(h=window.devicePixelRatio)!==null&&h!==void 0?h:1,E=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*A*i.containerSizeFactor,height:e.height*A*i.containerSizeFactor},v=E&&Rt(E),b=i.considerPlaybackRate&&_(o)?o:1,$=s.filter(F=>!vi(F.quality)).sort((F,I)=>pi(F.quality,I.quality)?-1:1),D=(f=Qe($,-1))===null||f===void 0?void 0:f.quality,Y=(m=Qe($,0))===null||m===void 0?void 0:m.quality,J=te(r)||_(r.min)&&_(r.max)&&Ki(r.max,r.min)||_(r.min)&&Y&&pi(r.min,Y)||_(r.max)&&D&&Ki(r.max,D),N=b*lp(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),G={},O=$.filter(F=>(v?Ki(F.quality,v):!0)?(_(t)&&isFinite(t)&&_(F.bitrate)?t-a>=F.bitrate*N:!0)?i.lazyQualitySwitch&&_(i.minBufferToSwitchUp)&&u&&!vi(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&pi(F.quality,u.quality)?(G[F.quality]=Pt.Buffer,!1):!!l&&Tr(F.quality,l)?(G[F.quality]=Pt.DroppedFramesLimit,!1):J||(te(r.max)||Nn(F.quality,r.max))&&(te(r.min)||Tr(F.quality,r.min))?!0:(G[F.quality]=Pt.FitsQualityLimits,!1):(G[F.quality]=Pt.FitsThroughput,!1):(G[F.quality]=Pt.FitsContainer,!1))[0];O&&O.bitrate&&up.next(O.bitrate);const H=(g=O!=null?O:$[Math.ceil(($.length-1)/2)])!==null&&g!==void 0?g:s[0];H.quality!==((T=d==null?void 0:d.last)===null||T===void 0?void 0:T.quality)&&c({message:`
|
|
7
7
|
[available tracks] ${s.map(F=>F.quality).join(", ")}
|
|
8
8
|
|
|
9
9
|
[limit params]
|
|
@@ -26,7 +26,7 @@ import{ValueSubject as S,Subject as L,Subscription as re,isNonNullable as _,Erro
|
|
|
26
26
|
[selected track] ${H.quality}
|
|
27
27
|
`});const ae=H&&d&&d.history[H.id]&&pe()-d.history[H.id]<=i.trackCooldown&&(!d.last||H.id!==d.last.id);if(H!=null&&H.id&&d&&!ae&&d.recordSelection(H),ae&&(d!=null&&d.last)){const F=d.last;return d==null||d.recordSwitch(F),c({message:`
|
|
28
28
|
[last selected] ${F.quality}
|
|
29
|
-
`}),F}return d==null||d.recordSwitch(H),H};var we=s=>new URL(s).hostname;const hp=300,ns=(s,e=hp)=>new cs(t=>{const{width:i,height:r}=s.getBoundingClientRect();if(t.next({width:i,height:r}),!window.ResizeObserver)return;const a=new ResizeObserver(bd(n=>{const o=n[0];if(!o)return;let u,d;o.contentBoxSize&&o.contentBoxSize[0]?(d=o.contentBoxSize[0].blockSize,u=o.contentBoxSize[0].inlineSize):o.contentRect&&(u=o.contentRect.width,d=o.contentRect.height),_(u)&&_(d)&&t.next({width:u,height:d})},e));return a.observe(s),()=>a.disconnect()});class Ts{constructor(){this.onDroopedVideoFramesLimit$=new L,this.subscription=new re,this.playing=!1,this.tracks=[],this.forceChecker$=new L,this.isForceCheckCounter=0,this.prevTotalVideoFrames=0,this.prevDroppedVideoFrames=0,this.limitCounts={},this.handleChangeVideoQuality=()=>{const e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!vi(e.quality)&&this.onChangeQuality(e.quality)},this.checkDroppedFrames=()=>{var e;const{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality(),r=t-this.prevTotalVideoFrames,a=i-this.prevDroppedVideoFrames,n=1-(r-a)/r;!isNaN(n)&&n>0&&this.log({message:`[dropped]. current dropped percent: ${n}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(n)&&n>=this.droppedFramesChecker.percentLimit&&pi(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((e=this.limitCounts[this.currentQuality])!==null&&e!==void 0?e:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(t,i)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(B(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=is(this.droppedFramesChecker.checkTime).pipe(se(()=>this.playing),se(()=>{const r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(Me(this.droppedFramesChecker.checkTime)),i=U(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var t,i;const r=(i=(t=Object.entries(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>Ki(a,n)?-1:1))===null||t===void 0?void 0:t[0])===null||i===void 0?void 0:i[0];return e!=null?e:r}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}}const ui={};var W;(function(s){s.DOWNLOADING_LIB="downloading_lib",s.STOPPED="stopped",s.STREAM_INITIALIZED="stream_initialized",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(W||(W={}));const Se=(s,e)=>new cs(t=>{const i=r=>t.next(r);return s.on(e,i),()=>s.off(e,i)});class un{constructor(e){this.subscription=new re,this.videoState=new ue(W.DOWNLOADING_LIB),this.textTracksManager=new Ze,this.droppedFramesManager=new Ts,this.videoTracks$=new S([]),this.frameRatesByFrameHeight={},this.isLive$=new S(void 0),this.maxSeekBackTime$=new S(1/0),this.availableFrom$=new S(void 0),this.elementSize$=new S(void 0),this.liveOffset=new ys,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState(),n=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===W.DOWNLOADING_LIB||t===W.STREAM_INITIALIZED))switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===z.Requested&&t!==W.STOPPED&&i!==p.STOPPED&&(n?this.seek(a.position-this.liveOffset.getTotalPausedTime()):this.seek(a.position)),i){case p.STOPPED:{switch(t){case W.STOPPED:break;case W.PLAYING:case W.PAUSED:case W.READY:this.stop();break;default:V(t)}break}case p.READY:{switch(t){case W.STOPPED:this.prepare();break;case W.PLAYING:case W.PAUSED:case W.READY:break;default:V(t)}break}case p.PLAYING:{switch(t){case W.PLAYING:break;case W.PAUSED:n&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case W.READY:this.play();break;case W.STOPPED:this.prepare();break;default:V(t)}break}case p.PAUSED:{switch(t){case W.PLAYING:this.pause(),this.liveOffset.pause();break;case W.PAUSED:break;case W.READY:this.videoState.setState(W.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED);break;case W.STOPPED:this.prepare();break;default:V(t)}break}default:V(i)}},this.video=ct(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=r=>{var a;e||this.params.output.error$.next({id:r==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:C.NETWORK,message:`Dash.js failed to load: ${(a=r==null?void 0:r.toString)===null||a===void 0?void 0:a.call(r)}`,thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(ui.MediaPlayer=r.MediaPlayer,ui.Debug=r.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){P(ui.MediaPlayer,"dashjs not loaded"),P(ui.Debug,"dashjs not loaded"),this.player=ui.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter(e=>(e.height&&(this.frameRatesByFrameHeight[e.height]=e.frameRate?Xr(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&Hf(this.player),Ff(this.player),this.params.tuning.requestQuick&&Vf(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(W.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=v=>{e.error$.next({id:"DashIFProvider",category:C.WTF,message:"DashIFProvider internal logic error",thrown:v})},r=(v,b)=>this.subscription.add(v.subscribe(b,i));r(ns(this.video),this.elementSize$),r(Se(this.player,"error").pipe(w(v=>{const b=typeof v.error=="object"?v.error.code:v.error,$=typeof v.error=="object"?v.error.message:void 0;return{id:`DashJS#${b}`,message:$}})),e.error$),r(Se(this.player,"playbackError").pipe(w(v=>({id:"DashJSPlayback",message:v.error}))),e.error$);const a=Se(this.player,"qualityChangeRendered").pipe(se(({mediaType:v})=>v==="video"),w(({newQuality:v})=>{var b;return(b=this.videoTracks$.getValue().find(({bitrateInfo:$})=>$.qualityIndex===v))===null||b===void 0?void 0:b.track}));a.pipe(se(_)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(se(({to:v})=>v===W.STREAM_INITIALIZED),me()).subscribe(()=>{this.subscription.add(Ge(t.videoTrack,()=>{var v,b;const $=this.player.getQualityFor("video");return(b=(v=this.videoTracks$.getValue().find(({bitrateInfo:D})=>D.qualityIndex===$))===null||v===void 0?void 0:v.track)===null||b===void 0?void 0:b.id},v=>{var b;if(te(v))return;const $=(b=this.videoTracks$.getValue().find(({track:D})=>D.id===v))===null||b===void 0?void 0:b.bitrateInfo;$&&this.player.setQualityFor("video",$.qualityIndex)},{changed$:a.pipe(w(v=>v==null?void 0:v.id)),onError:i}))},i)),this.subscription.add(Ge(t.autoVideoTrackSwitching,()=>{var v,b,$;return($=(b=(v=this.player.getSettings().streaming)===null||v===void 0?void 0:v.abr)===null||b===void 0?void 0:b.autoSwitchBitrate)===null||$===void 0?void 0:$.video},v=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:v}}}}),{onError:i})),r(Se(this.player,"bufferStateChanged").pipe(se(({mediaType:v})=>v==="video"),w(({state:v})=>v==="bufferStalled")),e.isBuffering$),r(Se(this.player,"fragmentLoadingStarted"),({mediaType:v,request:{url:b}})=>{var $,D;const Y=this.player.getDashMetrics(),J=Y.getLatestFragmentRequestHeaderValueByID(v,"X-Reused"),N=($=Y.getLatestFragmentRequestHeaderValueByID(v,"X-Delivery-Type"))!==null&&$!==void 0?$:gi.HTTP1,G=(D={1:!0,0:!1}[J])!==null&&D!==void 0?D:void 0;this.params.output.httpConnectionType$.next(N),this.params.output.httpConnectionReused$.next(G),e.hostname$.next(we(b))}),r(Se(this.player,"streamInitialized"),({streamInfo:{duration:v,manifestInfo:{isDynamic:b,availableFrom:$}}})=>{this.isLive$.next(b),this.availableFrom$.next($.getTime()),b||e.duration$.next(v);const D=[],Y=this.player.getQualityFor("video");let J;for(const N of this.player.getBitrateInfoListFor("video")){const G=N.qualityIndex.toString(10),Q=Rt(N),O=N.bitrate/1e3,H={width:N.width,height:N.height},ae=this.frameRatesByFrameHeight[N.height];if(Q){const F={id:G,quality:Q,bitrate:O,size:H,fps:ae};D.push({track:F,bitrateInfo:N}),N.qualityIndex===Y&&(J=F)}}this.videoTracks$.next(D),e.availableVideoTracks$.next(D.map(({track:N})=>N)),J&&e.currentVideoTrack$.next(J),this.videoState.setState(W.STREAM_INITIALIZED),this.videoState.startTransitionTo(W.READY)}),r(Se(this.player,"fragmentLoadingCompleted"),({request:v})=>{if(!v.requestEndDate||!v.firstByteDate||!v.bytesLoaded)return;const b=v.requestEndDate.getTime()-v.firstByteDate.getTime(),$=v.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed($,b)}),r(U(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeStarted$,this.droppedFramesManager.onDroopedVideoFramesLimit$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks$.getValue().length)return;const v=this.params.dependencies.throughputEstimator.throughput$.getValue(),b=ti(this.videoTracks$.getValue().map(({track:Y})=>Y),{container:this.elementSize$.getValue(),throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),$=t.autoVideoTrackLimits.getTransition();$&&e.autoVideoTrackLimits$.next($.to);const D=this.videoTracks$.getValue().find(({track:Y})=>Y===b);D!=null&&D.bitrateInfo&&this.player.setQualityFor("video",D==null?void 0:D.bitrateInfo.qualityIndex,!1)}),r(Ie({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(se(_))}).pipe(se(({isLive:v})=>v),w(({maxSeekBackTime:v})=>-v/1e3)),this.params.output.duration$);const n=Se(this.player,"playbackTimeUpdated").pipe(w(({time:v})=>v!=null?v:0));r(Ie({availableFrom:this.availableFrom$.pipe(se(_)),currentTime:n}),({availableFrom:v,currentTime:b})=>this.params.output.liveTime$.next(v+b*1e3)),r(n.pipe(se(()=>this.isLive$.getValue()===!1)),e.position$),r(Se(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),r(Se(this.player,"playbackEnded"),e.endedEvent$),r(Se(this.player,"playbackProgress").pipe(w(()=>Do(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(Se(this.player,"playbackPlaying"),()=>{this.videoState.setState(W.PLAYING),R(t.playbackState,p.PLAYING)}),r(Se(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(W.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(Se(this.player,"playbackPaused"),()=>{this.videoState.setState(W.PAUSED),R(t.playbackState,p.PAUSED)}),r(Se(this.player,"canPlay"),()=>{var v;((v=this.videoState.getTransition())===null||v===void 0?void 0:v.to)===W.READY&&this.videoState.setState(W.READY)}),r(this.isLive$,e.isLive$),r(ns(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=U(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Me(0));r(o,this.syncPlayback);const{playbackDuration$:u,ping$:d,connectionType$:l,connectionReused$:c}=Uf(this.player);r(l,this.params.output.httpConnectionType$),r(c,this.params.output.httpConnectionReused$),r(u,this.maxSeekBackTime$),r(d.pipe(me()),e.firstBytesEvent$),r(Se(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(Ie({isLive:this.isLive$,isShort:e.duration$.pipe(w(v=>v<60))}),({isLive:v,isShort:b})=>{const $=!v&&b;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:$}}})}),r(n.pipe(se(v=>v>this.params.tuning.insufficientBufferRuleMargin),me()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(Se(this.player,"manifestLoaded").pipe(me()).subscribe(()=>{this.subscription.add(Se(this.player,"playbackPlaying").pipe(me(),Wt(void 0)).subscribe(e.firstFrameEvent$,i))},i)),r(Se(this.player,"manifestLoaded"),v=>{var b,$,D,Y,J,N,G;if(!(($=(b=v.data)===null||b===void 0?void 0:b.Period)===null||$===void 0)&&$.AdaptationSet){const Q=[];for(const O of(Y=(D=v.data)===null||D===void 0?void 0:D.Period)===null||Y===void 0?void 0:Y.AdaptationSet)if(O.contentType==="text"){const H=(J=O.Representation)===null||J===void 0?void 0:J.id,ae=new URL((N=O.Representation)===null||N===void 0?void 0:N.BaseURL,(G=v.data)===null||G===void 0?void 0:G.baseUri).toString(),F="internal",I=O.lang;Q.push({id:H,url:ae,type:F,language:I})}t.internalTextTracks.startTransitionTo(Q)}}),this.subscription.add(Ct(this.video,t.isLooped,i));const{volumeState$:h,looped$:f,playbackRateState$:m,inPiP$:g,inFullscreen$:T,pause$:A,playing$:E}=ft(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:E,pause$:A,tracks$:this.videoTracks$.pipe(w(v=>v.map(({track:b})=>b)))}),this.subscription.add(lt(this.video,t.volume,h,i)),this.subscription.add(h.subscribe(e.volume$,i)),this.subscription.add(f.subscribe(e.loopedEvent$)),this.subscription.add(Tt(this.video,t.playbackRate,m,i)),this.subscription.add(g.subscribe(e.inPiP$)),this.subscription.add(T.subscribe(e.inFullscreen$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(W.STOPPED),R(this.params.desiredState.playbackState,p.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(W.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const r=He(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,be.PLAYBACK_SHIFT);this.player.attachSource(r)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(W.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(W.PAUSED),this.video.pause()}destroy(){var e;this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(t){}ht(this.video),this.params.output.element$.next(void 0)}}var Ai=s=>{switch(s){case"mobile":return Ce.Q_144P;case"lowest":return Ce.Q_240P;case"low":return Ce.Q_360P;case"sd":case"medium":return Ce.Q_480P;case"hd":case"high":return Ce.Q_720P;case"fullhd":case"full":return Ce.Q_1080P;case"quadhd":case"quad":return Ce.Q_1440P;case"ultrahd":case"ultra":return Ce.Q_2160P}};const ln=s=>{if(s instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(s.message))throw s;return!(s instanceof DOMException&&(s.code===20||s.name==="AbortError"))};var Et=async s=>{const e=s.muted;try{await s.play()}catch(t){if(!ln(t))return!1;if(e)return console.warn(t),!1;s.muted=!0;try{await s.play()}catch(i){return ln(i)&&(s.muted=!1,console.warn(i)),!1}}return!0};function $e(){return pe()}function Io(s){return $e()-s}function cn(s){const e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let d=n.indexOf("?")>-1?"&":"?";return u&&(n+=d+"lowLat=1",d="&"),o&&(n+=d+"_rnd="+Math.floor(999999999*Math.random())),n}}}function fp(s,e,t){const i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function es(s,e,t,i){const r=window.XMLHttpRequest;let a,n,o,u=!1,d=0,l,c,h=!1,f="arraybuffer",m=7e3,g=2e3,T=()=>{if(u)return;P(l);const O=Io(l);let H;if(O<g){H=g-O,setTimeout(T,H);return}g*=2,g>m&&(g=m),n&&n.abort(),n=new r,D()};const A=O=>(a=O,Q),E=O=>(c=O,Q),v=()=>(f="json",Q),b=()=>{if(!u){if(--d>=0){T(),i&&i();return}u=!0,c&&c(),t&&t()}},$=O=>(h=O,Q),D=()=>{l=$e(),n=new r,n.open("get",s);let O=0,H,ae=0;const F=()=>(P(l),Math.max(l,Math.max(H||0,ae||0)));if(a&&n.addEventListener("progress",I=>{const M=$e();a.updateChunk&&I.loaded>O&&(a.updateChunk(F(),I.loaded-O),O=I.loaded,H=M)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>b())),n.addEventListener("load",()=>{if(u)return;P(n);const I=n.status;if(I>=200&&I<300){if(n.response.byteLength&&a){const M=n.response.byteLength-O;M&&a.updateChunk&&a.updateChunk(F(),M)}c&&c(),n&&e(n.response)}else b()}),n.addEventListener("error",()=>{b()}),h){const I=()=>{P(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ae=$e(),n.removeEventListener("readystatechange",I))};n.addEventListener("readystatechange",I)}return n.responseType=f,n.send(),Q},Q={withBitrateReporting:A,withParallel:$,withJSONResponse:v,withRetryCount:O=>(d=O,Q),withRetryInterval:(O,H)=>(_(O)&&(g=O),_(H)&&(m=H),Q),withTimeout:O=>(o=O,Q),withFinally:E,send:D,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return Q}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,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-vp;if(t-e>mp){let i=0,r=0;for(;this.intervals.length>0;){const a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{const n=t-a.start,o=a.end-a.start;i+=n;const u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){const a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>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,i,r,a){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const i=$e(),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=$e()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=es(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=$e()}_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=$e();if(Object.keys(this.activeRequests).length>=e)return!1;const i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){const a={};return a.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Vi=1e4,Hi=3,bp=300,yp=2e3,Tp=6e4,Ep=10,$p=1,Ap=500;class kp{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=cn(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=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 i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)===null||i===void 0?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,i=t.buffered.length;let r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let i,r,a;const n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a));return r||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||_(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const n=()=>{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(Hi,Vi,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,playerCallback:r}=this.params;let a=!1,n=null,o=null,u=null,d=null,l=!1;const c=()=>{const b=a&&(!l||l===this.rep);return b||t("Not running!"),b},h=(b,$,D)=>{u&&u.abort(),u=es(this.urlResolver.resolve(b,!1),$,D,()=>this._retryCallback()).withTimeout(Vi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Hi).withFinally(()=>{u=null}).send()},f=(b,$,D)=>{P(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(b,!1),$,D,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=b=>{const $=i.playbackRate;i.playbackRate!==b&&(t(`Playback rate switch: ${$}=>${b}`),i.playbackRate=b)},g=b=>{this.lowLatency=b,t(`lowLatency changed to ${b}`),T()},T=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let b=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}const D=$e()-1e4;let Y=0;for(let N=0;N<this.bufferStates.length;N++){const G=this.bufferStates[N];b=Math.min(b,G.buf),G.ts<D&&Y++}this.bufferStates.splice(0,Y),t(`update playback rate; minBuffer=${b} drop=${Y} jitter=${this.sourceJitter}`);let J=b-$p;this.sourceJitter>=0?J-=this.sourceJitter/2:this.sourceJitter-=1,J>3?m(1.15):J>1?m(1.1):J>.3?m(1.05):m(1)}},A=b=>{let $;const D=()=>$&&$.start?$.start.length:0,Y=I=>$.start[I]/1e3,J=I=>$.dur[I]/1e3,N=I=>$.fragIndex+I,G=(I,M)=>({chunkIdx:N(I),startTS:Y(I),dur:J(I),discontinuity:M}),Q=()=>{let I=0;if($&&$.dur){let M=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,X=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,he=M;this.sourceJitter>1&&(he+=this.sourceJitter-1);let ve=$.dur.length-1;for(;ve>=0&&(he-=$.dur[ve],!(he<=0));--ve);I=Math.min(ve,$.dur.length-1-X),I=Math.max(I,0)}return G(I,!0)},O=I=>{const M=D();if(!(M<=0)){if(_(I)){for(let X=0;X<M;X++)if(Y(X)>I)return G(X)}return Q()}},H=I=>{const M=D(),X=I?I.chunkIdx+1:0,he=X-$.fragIndex;if(!(M<=0)){if(!I||he<0||he-M>Ep)return t(`Resync: offset=${he} bChunks=${M} chunk=`+JSON.stringify(I)),Q();if(!(he>=M))return G(X-$.fragIndex,!1)}},ae=(I,M,X)=>{d&&d.abort(),d=es(this.urlResolver.resolve(I,!0,this.lowLatency),M,X,()=>this._retryCallback()).withTimeout(Vi).withRetryCount(Hi).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(I,M)=>{ae(b,X=>{if(!c())return;$=X;const he=!!$.lowLatency;he!==this.lowLatency&&g(he);let ve=0;for(let _e=0;_e<$.dur.length;++_e)ve+=$.dur[_e];ve>0&&(P(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ve/$.dur.length)),r({name:"index",zeroTime:$.zeroTime,shiftDuration:$.shiftDuration}),this.sourceJitter=$.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,$.jitter/1e3)):1,I(O(M))},()=>this._handleNetworkError())},nextChunk:H}},E=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),P(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:b=>{const{videoElement:$,logger:D}=this.params;let Y=A(e.jidxUrl),J,N,G,Q,O=0,H,ae,F;const I=()=>{H&&(clearTimeout(H),H=void 0);const Z=Math.max(Ap,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ae=O+Z,xe=$e(),Pe=Math.min(1e4,Ae-xe);O=xe;const Le=()=>{d||c()&&Y.seek(()=>{c()&&(O=$e(),M(),I())})};Pe>0?H=window.setTimeout(()=>{this.paused?I():Le()},Pe):Le()},M=()=>{let Z;for(;Z=Y.nextChunk(Q);)Q=Z,je(Z);const Ae=Y.nextChunk(G);if(Ae){if(G&&Ae.discontinuity){D("Detected discontinuity; restarting playback"),this.paused?I():(E(),this._initPlayerWith(e));return}_e(Ae)}else I()},X=(Z,Ae)=>{if(!c()||!this.sourceBuffer)return;let xe,Pe,Le;const Ot=$t=>{window.setTimeout(()=>{c()&&X(Z,Ae)},$t)};if(this.sourceBuffer.updating)D("Source buffer is updating; delaying appendBuffer"),Ot(100);else{const $t=$e(),Bt=$.currentTime;!this.paused&&$.buffered.length>1&&ae===Bt&&$t-F>500&&(D("Stall suspected; trying to fix"),this._fixupStall()),ae!==Bt&&(ae=Bt,F=$t);const Mt=this._getBufferSizeSec();if(Mt>30)D(`Buffered ${Mt} seconds; delaying appendBuffer`),Ot(2e3);else try{this.sourceBuffer.appendBuffer(Z),this.videoPlayStarted?(this.bufferStates.push({ts:$t,buf:Mt}),T(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ae&&Ae()}catch(wi){if(wi.name==="QuotaExceededError")D("QuotaExceededError; delaying appendBuffer"),Le=this.sourceBuffer.buffered.length,Le!==0&&(xe=this.sourceBuffer.buffered.start(0),Pe=Bt,Pe-xe>4&&this.sourceBuffer.remove(xe,Pe-3)),Ot(1e3);else throw wi}}},he=()=>{N&&J&&(D([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(G)]),X(N,function(){N=null,M()}))},ve=Z=>e.fragUrlTemplate.replace("%%id%%",Z.chunkIdx),_e=Z=>{c()&&f(ve(Z),(Ae,xe)=>{if(c()){if(xe/=1e3,N=Ae,G=Z,n=Z.startTS,xe){const Pe=Math.min(10,Z.dur/xe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Pe:Pe}he()}},()=>this._handleNetworkError())},je=Z=>{c()&&(P(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ve(Z),!1)))},pt=Z=>{c()&&(e.cachedHeader=Z,X(Z,()=>{J=!0,he()}))};a=!0,Y.seek(Z=>{if(c()){if(O=$e(),!Z){I();return}Q=Z,!te(b)||Z.startTS>b?_e(Z):(G=Z,M())}},b),e.cachedHeader?pt(e.cachedHeader):h(e.headerUrl,pt,()=>this._handleNetworkError())},stop:E,getTimestampSec:()=>n},l}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),_(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,P(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return _(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let h,f,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(f=this._getBufferSizeSec(),m=c/this.bitrate,f>10&&m>.8||f>15&&m>.5||f>20&&m>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},a=(()=>({updateChunk:(h,f)=>{const m=$e();if(this.chunkRateEstimator.addInterval(h,m,f)){const T=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:m-h,speed:T}),!0}},get:()=>{const h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}}))();let n=-1/0,o,u=!0;const d=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Io(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,h)=>{const f=a.updateChunk(c,h);return f&&d(),f},notifySwitch:c=>{const h=$e();c<o&&(n=h),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=es(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Vi).withRetryCount(Hi).withRetryInterval(bp,yp).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;Et(t).then(i=>{i||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:r}=this.params,a=n=>{const o=[];return n!=null&&n.length?(n.forEach((u,d)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=d,o.push(u))}),o.sort(function(u,d){return u.video&&d.video?d.video.height-u.video.height:d.bitrate-u.bitrate}),o):(this.params.playerCallback({name:"error",type:"partial_metadata"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Tp))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var j;(function(s){s.STOPPED="stopped",s.MANIFEST_READY="manifest_ready",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(j||(j={}));const wp=[j.PAUSED,j.PLAYING,j.READY],_p=[j.PAUSED,j.PLAYING,j.READY];class Pp{constructor(e){this.subscription=new re,this.videoState=new ue(j.STOPPED),this.representations$=new S([]),this.textTracksManager=new Ze,this.droppedFramesManager=new Ts,this.maxSeekBackTime$=new S(1/0),this.zeroTime$=new S(void 0),this.liveOffset=new ys,this._dashCb=r=>{var a,n,o,u;switch(r.name){case"buffering":{const d=r.isBuffering;this.params.output.isBuffering$.next(d);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:C.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const d=r.manifest,l=[];for(const c of d){const h=(a=c.name)!==null&&a!==void 0?a:c.index.toString(10),f=(n=Ai(c.name))!==null&&n!==void 0?n:Rt(c.video),m=c.bitrate/1e3,g={...c.video};if(!f)continue;const T={id:h,quality:f,bitrate:m,size:g};l.push({track:T,representation:c})}this.representations$.next(l),this.params.output.availableVideoTracks$.next(l.map(({track:c})=>c)),((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===j.MANIFEST_READY&&this.videoState.setState(j.MANIFEST_READY);break}case"qualitySwitch":{const d=r.quality,l=(u=this.representations$.getValue().find(({representation:c})=>c===d))===null||u===void 0?void 0:u.track;this.params.output.hostname$.next(new URL(d.headerUrl,this.params.source.url).hostname),_(l)&&this.params.output.currentVideoTrack$.next(l);break}case"bandwidth":{const{size:d,duration:l}=r;this.params.dependencies.throughputEstimator.addRawSpeed(d,l);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{const r=this.videoState.getState(),a=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${r}; videoTransition: ${JSON.stringify(a)}; desiredPlaybackState: ${n}; seekState: ${JSON.stringify(u)};`}),n===p.STOPPED){r!==j.STOPPED&&(this.videoState.startTransitionTo(j.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(j.STOPPED));return}if(a)return;const d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(_p.includes(r)&&(d||l)){this.prepare();return}if((o==null?void 0:o.to)!==p.PAUSED&&u.state===z.Requested&&wp.includes(r)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(r){case j.STOPPED:this.videoState.startTransitionTo(j.MANIFEST_READY),this.dash.attachSource(He(this.params.source.url));return;case j.MANIFEST_READY:this.videoState.startTransitionTo(j.READY),this.prepare();break;case j.READY:if(n===p.PAUSED)this.videoState.setState(j.PAUSED);else if(n===p.PLAYING){this.videoState.startTransitionTo(j.PLAYING);const c=o==null?void 0:o.from;c&&c===p.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(j.PAUSED)})}return;case j.PLAYING:n===p.PAUSED&&(this.videoState.startTransitionTo(j.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case j.PAUSED:if(n===p.PLAYING)if(this.videoState.startTransitionTo(j.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(j.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.dash.reinit(He(this.params.source.url,c))}return;default:return V(r)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:C.WTF,message:"DashLiveProvider internal logic error",thrown:r})};U(this.videoState.stateChangeStarted$.pipe(w(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(w(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=ct(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(we(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=ft(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.representations$.pipe(w(r=>r.map(({track:a})=>a)))}),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===j.READY&&this.videoState.setState(j.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(j.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===z.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(j.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(fe(),w(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Ie({zeroTime:this.zeroTime$.pipe(se(_)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Ct(this.video,this.params.desiredState.isLooped,t)).add(lt(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Tt(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{const a=r&&pd(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case j.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(p.STOPPED);break;case j.MANIFEST_READY:case j.READY:((a=this.params.desiredState.playbackState.getTransition())===null||a===void 0?void 0:a.to)===p.READY&&this.params.desiredState.playbackState.setState(p.READY);break;case j.PAUSED:this.params.desiredState.playbackState.setState(p.PAUSED);break;case j.PLAYING:this.params.desiredState.playbackState.setState(p.PLAYING);break;default:return V(r.to)}},t)).add(U(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,ke(["init"])).pipe(Me(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),ht(this.video)}createLiveDashPlayer(){const e=new kp({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,i,r,a,n;const o=this.representations$.getValue(),u=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),d=(r=(i=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||i===void 0?void 0:i.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),l=!d&&_(u)?u:(a=ti(o.map(({track:m})=>m),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}))===null||a===void 0?void 0:a.id,c=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.videoTrack.getState(),f=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((c&&l||l!==h)&&this.setVideoTrack(l),f&&this.setAutoQuality(d),c||f||l!==h){const m=(n=o.find(({track:g})=>g.id===l))===null||n===void 0?void 0:n.representation;P(m,"Representations missing"),this.dash.startPlay(m,d)}}setVideoTrack(e){var t;const i=(t=this.representations$.getValue().find(({track:r})=>r.id===e))===null||t===void 0?void 0:t.representation;P(i,`No such representation ${e}`),this.dash.switchByName(i.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t===p.PAUSED&&i===j.PAUSED,a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(He(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}}var xo=s=>{var e,t;const i=s.get("X-Delivery-Type"),r=s.get("X-Reused"),a=i===null?gi.HTTP1:(e=i)!==null&&e!==void 0?e:void 0,n=r===null?void 0:(t={1:!0,0:!1}[r])!==null&&t!==void 0?t:void 0;return{type:a,reused:n}},bt=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){const r=s.start(i)*1e3,a=s.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};const Dp=s=>{const e=document.createElement("a");return e.href=s,e.origin},Rp=s=>{const e=document.createElement("a");return e.href=s,e.host};class Lo{constructor(e,t=[],i,r,a,n){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=i,this._progressCb=r,this._headersCb=a,this._errorCb=n,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{var t,i,r,a,n,o,u,d;if(this._xhr){if(((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(i=this._errorCb)===null||i===void 0||i.call(this,`Http${(r=this._xhr)===null||r===void 0?void 0:r.status}`,`XHR response code ${(a=this._xhr)===null||a===void 0?void 0:a.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const l=Qt(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(c=>c.split(":").map(h=>h.trim())));(n=this._headersCb)===null||n===void 0||n.call(this,new Headers(l))}else this._xhr.readyState===4?(o=this._completeCb)===null||o===void 0||o.call(this,this._xhr.response):this._xhr.readyState===3&&((u=this._progressCb)===null||u===void 0||u.call(this,this._xhr.response))}catch(l){throw(d=this._errorCb)===null||d===void 0||d.call(this,"XHR2CallbackError",`xhr2 callback threw ${String(l)}`,l),l}}},this._xhr.onerror=()=>{var t;(t=this._xhr)===null||t===void 0||t.abort(),this._retryTimeout=window.setTimeout(()=>{var i;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(i=this._errorCb)===null||i===void 0||i.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let r;this._failoverIndex>=this._failoverHosts.length?(r=this._url,this._failoverIndex=0):(r=this._url.replace(Rp(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",r,!0),this._xhr.send(null)}},500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class os{constructor(e){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t==null||t()}catch(i){if(i.name==="QuotaExceededError"){this._isFull=!0;const r=this._sourceBuffer.buffered;let a=0;for(let n=0,o=r.length;n<o;n++)a+=r.end(n)-r.start(n);a&&(this._maxBufferDuration=Math.round(a))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",i),i}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,i,r,a,n,o){this.abort(()=>{let u=0;const d=Date.now();let l=0,c=0,h=0;const f=g=>{r(os._str2ua(g.substr(u))),u=g.length};let m=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(m=Kt(m)),this._lastXhr=new Lo(m,e.failoverHosts,g=>{this._lastXhr=void 0,f(g);const T=Date.now()-d;this._params.onBandwidthChange({size:g.length,duration:T,speed:8*g.length/(T/1e3)}),this._onDashCallback("loading",{size:g.length,done:!0}),a==null||a()},g=>{if(g.length-u>o&&f(g),c===0){c=Date.now();return}h=g.length-l;const T=Date.now()-c;h>=100*1024&&T>=1e3&&(this._params.onBandwidthChange({size:h,duration:T,speed:8*h/(T/1e3)}),h=0,l=g.length,c=Date.now()),this._onDashCallback("loading",{size:g.length,done:!1})},n,(g,T,A)=>this._params.onError(g,T,A))})}abort(e){var t;(t=this._lastXhr)===null||t===void 0||t.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e==null||e()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(i){throw this._params.onError("SourceBuffer","Source Buffer update error",i),i}};return this._sourceBuffer.addEventListener("updateend",t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener("updateend",e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=os._concatUint8(this._appendPromiseUint8Array,e):(this._appendPromiseUint8Array=e,this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,()=>{this._appendPromiseUint8Array=void 0,t&&this._sbUpdatingWatch(t)})}))}endOfStream(){this._mediaSource.readyState==="open"&&this._sbUpdatingWatch(()=>this._mediaSource.endOfStream())}static _concatUint8(e,t){const i=new Uint8Array(e.byteLength+t.byteLength);return i.set(e,0),i.set(t,e.byteLength),i}static _str2ua(e){const t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}remove(e,t){this._sbUpdatingWatch(()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(e,t),this._maxBufferDuration=Number.POSITIVE_INFINITY})}destroy(){var e;(e=this._lastXhr)===null||e===void 0||e.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._mediaSource.readyState==="open"&&this._sourceBuffer.abort()}}class Ip{constructor(e){var t;this._representations=[],this._appendVector={},this._cachingPaused=!1,this._duration=0,this.STREAM_END_THRESHOLD=1,this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=(t=e.onDashCallback)!==null&&t!==void 0?t:()=>{},this._config=e.config}_parseDurationFromISO8601(e){const t=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/,i=(o,u)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*u},r=t.exec(e),a=(r==null?void 0:r[1])==="-"?-1:1,n={years:i(r==null?void 0:r[2],a),months:i(r==null?void 0:r[3],a),weeks:i(r==null?void 0:r[4],a),days:i(r==null?void 0:r[5],a),hours:i(r==null?void 0:r[6],a),minutes:i(r==null?void 0:r[7],a),seconds:i(r==null?void 0:r[8],a)};return n.hours*3600+n.minutes*60+n.seconds}getRepresentations(){return this._representations}attachSource(e,t){let i=e;this._config.REQUEST_QUIC&&(i=Kt(i)),new Lo(i,t,r=>{this.attachManifest(r,t,Dp(i))},void 0,r=>{this._params.onResponseHeaders(r)},(r,a,n)=>this._params.onError(r,a,n))}attachManifest(e,t,i){const a=new DOMParser().parseFromString(e,"text/xml").documentElement,n=(d,l)=>{const c=d.attributes.getNamedItem(l);return c?c.value:null};this._duration=this._parseDurationFromISO8601(String(n(a,"mediaPresentationDuration")));const o=[],u=[];if(Array.prototype.forEach.call(a.getElementsByTagName("Representation"),d=>{var l,c,h,f,m,g,T,A,E,v,b,$,D,Y,J,N,G,Q,O;const H=d.getElementsByTagName("SegmentBase")[0],ae=H&&n(H,"indexRange").split("-"),F=H&&H.getElementsByTagName("Initialization")[0],I=F&&n(F,"range").split("-");if(!I||!ae){const je=d.parentElement;if((je==null?void 0:je.getAttribute("contentType"))==="text"){const pt=(l=d.getAttribute("id"))!==null&&l!==void 0?l:void 0,Z=(i?i+"/":"")+((m=(f=(h=(c=d.getElementsByTagName("BaseURL"))===null||c===void 0?void 0:c[0])===null||h===void 0?void 0:h.childNodes)===null||f===void 0?void 0:f[0])===null||m===void 0?void 0:m.data),Ae=(g=je.getAttribute("lang"))!==null&&g!==void 0?g:void 0;Z&&u.push({id:pt,url:Z,language:Ae})}return}const M=.1,X=Number((T=d.attributes.getNamedItem("bandwidth"))===null||T===void 0?void 0:T.value),he=(i?i+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ve;const _e=(E=(A=d.attributes.getNamedItem("frameRate"))===null||A===void 0?void 0:A.value)!==null&&E!==void 0?E:void 0;ve=_e?Xr(_e):void 0,o.push({width:Number((v=d.attributes.getNamedItem("width"))===null||v===void 0?void 0:v.value),height:Number((b=d.attributes.getNamedItem("height"))===null||b===void 0?void 0:b.value),bandwidth:X,baseURL:he,failoverHosts:t,indexFrom:Number(ae[0]),indexTo:Number(ae[1]),initFrom:Number(I[0]),initTo:Number(I[1]),codecs:(D=($=d.attributes.getNamedItem("codecs"))===null||$===void 0?void 0:$.value)!==null&&D!==void 0?D:void 0,mimeType:(J=(Y=d.attributes.getNamedItem("mimeType"))===null||Y===void 0?void 0:Y.value)!==null&&J!==void 0?J:void 0,fps:ve,bufferSize:M*X/8,bufferLength:M,name:(G=(N=d.attributes.getNamedItem("okQuality"))===null||N===void 0?void 0:N.value)!==null&&G!==void 0?G:void 0,id:(O=(Q=d.attributes.getNamedItem("id"))===null||Q===void 0?void 0:Q.value)!==null&&O!==void 0?O:void 0})}),o.length)this._representations=o;else{this._onDashCallback("error");return}u.forEach(({id:d,language:l,url:c})=>{const h=document.createElement("track");c&&h.setAttribute("src",c),d&&h.setAttribute("id",d),l&&h.setAttribute("srclang",l),this._video.appendChild(h)}),this._representations.sort((d,l)=>l.bandwidth-d.bandwidth),this._params.onManifestReady({representations:this._representations,textRepresentations:u})}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const i=Date.now();this._stream.load(e,e.initFrom,e.indexTo,r=>{let a=e.initTo-e.initFrom+1;if(!r.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(r.buffer,0,a);const n=new DataView(r.buffer);a+=12;const o=n.getUint32(a+4,!1);a+=8;let u=n.getUint32(a,!1),d=n.getUint32(a+4,!1)+(e.indexTo+1);a+=8;const l=n.getUint16(a+2,!1);a+=4,e.refs=[];for(let h=0;h<l;h+=1){const f=d+(n.getUint32(a,!1)&2147483647),m=u+n.getUint32(a+4,!1);a+=12,e.refs.push({fromTime:u/o,toTime:m/o,fromOffset:d,toOffset:f-1}),d=f,u=m}const c=e.refs[e.refs.length-1];c.toTime-c.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,r=>{this._params.onResponseHeaders(r),this._params.onIdxRequestPing(Date.now()-i)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const i=new t;let r,a;const n=()=>{const d=this._findRef(this._video.currentTime);if(!d||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const f=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),f)}const l=this._appendVector[String(d.fromTime)];l!==r&&(r=l,this._params.onRepresentationPlay(l));let c;if(this._findRef(d.toTime)){const f=this._buffer.getByTime(this._video.currentTime);if(!f){this._onDashCallback("buffering");return}c=f.to-this._video.currentTime,c<e.bufferLength&&(this._onDashCallback("buffering"),a!==f.to&&(a=f.to,window.setTimeout(()=>{try{const m=this._buffer.getNextWithGap(f);m&&(this._video.currentTime=m.from)}catch(m){throw this._params.onError("GapSyncError",`Seek Error ${String(m)}`,m),m}},c*1e3)))}},o=()=>{this._loopTimeout=window.setTimeout(()=>{try{n()}catch(d){throw this._params.onError("LoopError",`Dash Loop exception ${String(d)}`,d),d}o()},250)},u=()=>{if(!this._stream)try{const d=i.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new os({mediaSource:i,sourceBuffer:d,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(d){throw this._params.onError("DashSourceOpen",`Source open exception ${String(d)}`,d),d}this._loadInitAndSidx(e),i.duration||(i.duration=this._duration),this._loopTimeout||o(),i.removeEventListener("sourceopen",u),i.removeEventListener("webkitsourceopen",u)};i.addEventListener("sourceopen",u,!1),i.addEventListener("webkitsourceopen",u,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener("waiting",()=>{const d=this._video&&this._video.played.length;d&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(d-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,i=!1,r=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const a=this._findRef(t);if(a){if(i){this._isLastRef(a)&&t>=a.toTime&&(t=a.fromTime);const n=this._findRef(this._video.currentTime),o=Math.abs(this._video.currentTime-t),u=r||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||a===n||o<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=u?t:a.fromTime}this._appendVector[String(a.fromTime)]=e,this._stream.load(e,a.fromOffset,a.toOffset,(n,o)=>this._stream.append(n,o),()=>{this._lastLoadOffset=a.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},n=>this._params.onResponseHeaders(n),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const i=this._buffer.getByTime(this._video.currentTime),r=this._findRef(this._video.currentTime);if(!i||!r){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const a=.1;if(r.toTime<i.to+a){const n=this._findRef(r.toTime);n&&n.toTime<i.to+a?(this._buffer.smartRemove(r.fromTime-a,n.toTime+a,(o,u)=>this._stream.remove(o,u)),this._loadRef(e,n.toTime)):(this._buffer.smartRemove(r.fromTime-a,r.toTime+a,(o,u)=>this._stream.remove(o,u)),this._loadRef(e,r.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t){this._stream&&this._buffer.getByTime(e)?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0,t)}updateRefsForCurrentTime(){const e=this._video.currentTime;(!this._stream||te(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return;if(Array.isArray(i)&&i.length===0){this._params.onError("emptyrefs","Empty refs");return}let r;for(let a=0;a<i.length;a++){const n=i[a];if(n.fromTime<=e&&n.toTime>e)return n;n.fromTime>e&&(!r||n.fromTime<r.fromTime)&&(r=n)}if(!r){const a=i[i.length-1];if(e>a.toTime)return a}return r}_isLastRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return!1;const r=i[i.length-1];return e.fromTime===r.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const i=this._video.buffered.start(t),r=this._video.buffered.end(t);if(e>i&&e<r)return Math.round(r*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var K;(function(s){s.STOPPED="stopped",s.MANIFEST_LOADED="manifest-loaded",s.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",s.METADATA_LOADED="metadata-loaded",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(K||(K={}));const xp=[K.PAUSED,K.PLAYING];class Lp{constructor(e){this.videoState=new ue(K.STOPPED),this.subscription=new re,this.representations$=new S([]),this.currentRepresentation$=new S(void 0),this.textTracksManager=new Ze,this.droppedFramesManager=new Ts,this.elementSize$=new S(void 0),this.dashLiteEvents={idxRequestPing$:new L,responseHeaders$:new L,manifestReady$:new L,representationPlay$:new L,error$:new L},this.handleManifestReady=({representations:t,textRepresentations:i})=>{var r,a,n;const o=[];for(const u of t){const d=(a=(r=u.name)!==null&&r!==void 0?r:u.id)!==null&&a!==void 0?a:u.height.toString(10),l=(n=u.name&&Ai(u.name))!==null&&n!==void 0?n:Rt(u),c=u.bandwidth/1e3,h={width:u.width,height:u.height},f=u.fps;if(!l)continue;const m={id:d,quality:l,bitrate:c,size:h,fps:f};o.push({track:m,representation:u})}if(this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),(i==null?void 0:i.length)>0){const u=[];for(const d of i){const l=d.id||`${d.language}_${Date.now()}`;u.push({id:l,type:"internal",url:d.url||"",language:d.language,isAuto:d.isAuto})}this.params.desiredState.internalTextTracks.startTransitionTo(u)}this.videoState.setState(K.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var i;const r=(i=this.representations$.getValue().find(({representation:a})=>a===t))===null||i===void 0?void 0:i.track;r&&(this.params.output.currentVideoTrack$.next(r),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(r.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return P(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(n)};`}),r===p.STOPPED){t!==K.STOPPED&&(this.videoState.startTransitionTo(K.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(K.STOPPED),R(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(!i)switch((a==null?void 0:a.to)!==p.PAUSED&&n.state===z.Requested&&xp.includes(t)&&this.seek(n.position,n.forcePrecise),t){case K.STOPPED:this.videoState.startTransitionTo(K.MANIFEST_LOADED),this.prepare();return;case K.MANIFEST_LOADED:this.videoState.startTransitionTo(K.INITIAL_REPRESENTATION_SELECTED);return;case K.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(K.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case K.METADATA_LOADED:this.videoState.startTransitionTo(K.READY),this.dash.updateRefsForCurrentTime();return;case K.READY:r===p.READY?R(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(K.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed());return;case K.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(K.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&R(this.params.desiredState.playbackState,p.PLAYING);return;case K.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&R(this.params.desiredState.playbackState,p.PAUSED);return;default:return V(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),U(this.videoState.stateChangeStarted$.pipe(w(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(w(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=ct(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Wf(this.video),this.dash=new Ip({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:({representations:t,textRepresentations:i})=>this.dashLiteEvents.manifestReady$.next({representations:t,textRepresentations:i}),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,i,r)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:i,thrown:r,category:C.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"DashProvider",category:C.WTF,message:"DashProvider internal logic error",thrown:o})},r=()=>{const o=this.params.desiredState.autoVideoTrackSwitching.getState(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();return u?u.to:o},a=ft(this.video),n=(o,u)=>this.subscription.add(o.subscribe(u,i));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(a.seeking$.subscribe(()=>{te(this.params.desiredState.seekState.getState().state!==z.Applying)&&(this.videoState.getState()===K.PLAYING||this.videoState.getState()===K.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(Ct(this.video,t.isLooped,i)),this.subscription.add(lt(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Tt(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:a.playing$,pause$:a.pause$,tracks$:this.representations$.pipe(w(o=>o.map(({track:u})=>u)))}),n(ns(this.video),this.elementSize$),this.subscription.add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===K.READY&&this.videoState.setState(K.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(K.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED)})).add(a.playing$.subscribe(()=>{this.videoState.setState(K.PLAYING),R(this.params.desiredState.playbackState,p.PLAYING)},i)).add(a.loadedMetadata$.subscribe(()=>{this.videoState.setState(K.METADATA_LOADED)},i)).add(a.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},i)).add(this.dashLiteEvents.error$.pipe(w(({id:o,message:u,thrown:d})=>({id:`DashLite_${o}`,category:C.WTF,message:u,thrown:d}))).subscribe(this.params.output.error$)).add(U(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$,this.params.output.element$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,B(this.video,"progress")).pipe(w(()=>{var o,u,d;const l=this.currentRepresentation$.getValue(),c=this.representations$.getValue(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition(),f=this.params.desiredState.videoTrack.getState(),m=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),g=this.elementSize$.getValue(),T=r();h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to);let A;if(!T&&_(f))A=f;else{const E=bt(this.video.buffered,this.video.currentTime*1e3),v=T?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,b=Math.min(E/v,1);A=(u=ti(c.map(({track:D})=>D),{container:g,throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:b,playbackRate:this.video.playbackRate,current:(o=c.find(({representation:D})=>D===l))===null||o===void 0?void 0:o.track,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}))===null||u===void 0?void 0:u.id;const $=t.autoVideoTrackLimits.getTransition();$&&e.autoVideoTrackLimits$.next($.to)}return _(A)?(d=c.find(({track:E})=>E.id===A))===null||d===void 0?void 0:d.representation:void 0}),fe()).subscribe(this.currentRepresentation$,i)).add(Ie({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(se(o=>o.to===K.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(se(_))}).pipe(me()).subscribe(()=>this.videoState.setState(K.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(se(_),fe((o,u)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?o.height<=u.height:o===u)).subscribe(o=>{const u=bt(this.video.buffered,this.video.currentTime*1e3),d=Math.min(u/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||d<=.5||!r())&&(this.dash.setQualityByRepresentation(o,!0),this.params.output.hostname$.next(we(o.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:u,reused:d}=xo(o);this.params.output.httpConnectionType$.next(u),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(me(),Wt(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(o=>this.params.dependencies.throughputEstimator.addRawRtt(o))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,i)).add(this.dashLiteEvents.representationPlay$.pipe(se(_)).subscribe(this.handleRepresentationPlay,i)).add(U(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Me(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),ht(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return V(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){Et(this.video).then(e=>{e||(this.videoState.setState(K.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.DOM,thrown:e}))}}var Te;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(Te||(Te={}));var ds;(function(s){s.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",s.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(ds||(ds={}));var Be;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(Be||(Be={}));var ee;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(ee||(ee={}));var Jt;(function(s){s.MP4="mp4",s.WEBM="webm"})(Jt||(Jt={}));var us;(function(s){s[s.RECTANGULAR=0]="RECTANGULAR",s[s.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",s[s.CUBEMAP=2]="CUBEMAP",s[s.MESH=3]="MESH"})(us||(us={}));var le;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(le||(le={}));class hn{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;const i=this.listeners[e];for(let r=0,a=i.length;r<a;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const i=this.listeners[e.type].slice();for(let r=0,a=i.length;r<a;r++){const n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}}class Co 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 Oo=class{constructor(){Object.defineProperty(this,"signal",{value:new Co,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Oo.prototype[Symbol.toStringTag]="AbortController",Co.prototype[Symbol.toStringTag]="AbortSignal");function Bo(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function Cp(s){typeof s=="function"&&(s={fetch:s});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!Bo({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(d,l){let c;l&&l.signal&&(c=l.signal,delete l.signal);const h=new t(d,l);return c&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),h},a.prototype=t.prototype);const n=e;return{fetch:(u,d)=>{const l=a&&a.prototype.isPrototypeOf(u)?u.signal:d?d.signal:void 0;if(l){let c;try{c=new DOMException("Aborted","AbortError")}catch(f){c=new Error("Aborted"),c.name="AbortError"}if(l.aborted)return Promise.reject(c);const h=new Promise((f,m)=>{l.addEventListener("abort",()=>m(c),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([h,n(u,d)])}return n(u,d)},Request:a}}const Es=Bo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Mo=Es?Cp({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,bi=Es?Mo.fetch:window.fetch;Es?Mo.Request:window.Request;const zt=Es?Oo:window.AbortController;var Lr=(s,e)=>{for(let t=0;t<s.length;t++)if(s.start(t)*1e3<=e&&s.end(t)*1e3>e)return!0;return!1};const Op=(s,e={})=>{const i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},Bp=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",fn=Bp?Op:window.requestIdleCallback;var sr,rr;let No=!1;try{No=Br().browser===Mn.Safari&&parseInt((rr=(sr=navigator.userAgent.match(/Version\/(\d+)/))===null||sr===void 0?void 0:sr[1])!==null&&rr!==void 0?rr:"",10)<16}catch(s){console.error(s)}class Mp{constructor(e){this.bufferFull$=new L,this.error$=new L,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const i=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!i),this.currentTask=null}this.queue.length&&this.pull()}catch(i){this.error$.next({id:"BufferTaskQueueUnknown",category:C.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i;No&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:i}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&i==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${i}`,category:C.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:V(t)}}}var pn=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};class et{get id(){return this.type}get size(){return this.size32}constructor(e){this.cursor=0,this.source=e,this.children=[];const t=this.readUint32();this.size32=t<=e.buffer.byteLength?t:NaN,this.type=this.readString(4),this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,e.byteOffset+this.cursor,this.size32?this.size32-8:void 0),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}readString(e,t="ascii"){const r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){const e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){const e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){const e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){const e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}}class Fo extends et{}class Np extends et{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const i=this.readString(4);this.compatibleBrands.push(i),t-=4}}}class Fp extends et{parseChildrenBoxes(){return ii(this.content)}}class Up extends et{constructor(e){super(e),this.data=this.content}}class ki extends et{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class Vp extends ki{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let i=this.readUint32();const r=i>>>31,a=i<<1>>>1,n=this.readUint32();i=this.readUint32();const o=i>>>28,u=i<<3>>>3;this.segments.push({referenceType:r,referencedSize:a,subsegmentDuration:n,SAPType:o,SAPDeltaTime:u})}}}class Hp extends et{parseChildrenBoxes(){return ii(this.content)}}class Gp extends et{parseChildrenBoxes(){return ii(this.content)}}var Dt;(function(s){s[s.MONOSCOPIC=0]="MONOSCOPIC",s[s.TOP_BOTTOM=1]="TOP_BOTTOM",s[s.LEFT_RIGHT=2]="LEFT_RIGHT",s[s.STEREO_CUSTOM=3]="STEREO_CUSTOM",s[s.RIGHT_LEFT=4]="RIGHT_LEFT"})(Dt||(Dt={}));class Yp extends ki{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=Dt.MONOSCOPIC;break;case 1:this.stereoMode=Dt.TOP_BOTTOM;break;case 2:this.stereoMode=Dt.LEFT_RIGHT;break;case 3:this.stereoMode=Dt.STEREO_CUSTOM;break;case 4:this.stereoMode=Dt.RIGHT_LEFT;break}this.cursor+=1}}class qp extends ki{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class jp extends ki{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class zp extends et{parseChildrenBoxes(){return ii(this.content)}}class Wp extends ki{constructor(e){super(e),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}}class Qp extends et{parseChildrenBoxes(){return ii(this.content)}}class Kp extends et{parseChildrenBoxes(){return ii(this.content)}}const Jp={ftyp:Np,moov:Fp,mdat:Up,sidx:Vp,trak:Hp,mdia:zp,tkhd:Wp,minf:Qp,sv3d:Gp,st3d:Yp,prhd:qp,proj:Kp,equi:jp,unknown:Fo};class Xp{createBox(e,t){const i=Jp[e];return i?new i(t):new Fo(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return $s.createBox(i,new DataView(e.buffer,e.byteOffset))}}const $s=new Xp;function fi(s,e){const t=new TextDecoder("ascii");let i=s.byteOffset,r=[];for(;i<s.byteLength;){const a=t.decode(new DataView(s.buffer,i,1));if(a===e[r.length]?r.push(a):r=[],r.length===4&&r.join("")===e){const o=new DataView(s.buffer,i-7,4).getUint32(0);return i-7+o>s.byteLength?null:$s.createBox(e,new DataView(s.buffer,i-7))}i++}return null}function Zp(s,e){const t=[];let i=0;for(;i<s.byteLength;){const r=fi(new DataView(s.buffer,s.byteOffset+i,s.byteLength-i),e);if(r)t.push(r),i+=r.size+r.source.byteOffset;else break}return t}function ii(s){const e=[];let t=0;for(;t<s.byteLength;){const i=$s.createFromView(new DataView(s.buffer,s.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const em=new TextDecoder("ascii"),tm=s=>em.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",im=s=>{const e=$s.createFromView(s);let t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=a.subsegmentDuration/e.timescale*1e3,o={status:ee.NONE,time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},sm=s=>{const e=Zp(s,"mdat");if(e.length){const t=e.reduce((i,r)=>i+r.size,0);return new DataView(s.buffer,s.byteOffset,t)}return null},rm=s=>{const e={is3dVideo:!1,stereoMode:0,projectionType:us.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(fi(s,"sv3d")){e.is3dVideo=!0;const i=fi(s,"st3d");i&&(e.stereoMode=i.stereoMode);const r=fi(s,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const a=fi(s,"equi");a&&(e.projectionData.bounds.top=a.projectionBoundsTop,e.projectionData.bounds.right=a.projectionBoundsRight,e.projectionData.bounds.bottom=a.projectionBoundsBottom,e.projectionData.bounds.left=a.projectionBoundsLeft)}return e},am={validateData:tm,parseInit:rm,getIndexRange:()=>{},parseSegments:im,parseFeedableSegmentChunk:sm};var k;(function(s){s[s.EBML=440786851]="EBML",s[s.EBMLVersion=17030]="EBMLVersion",s[s.EBMLReadVersion=17143]="EBMLReadVersion",s[s.EBMLMaxIDLength=17138]="EBMLMaxIDLength",s[s.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",s[s.DocType=17026]="DocType",s[s.DocTypeVersion=17031]="DocTypeVersion",s[s.DocTypeReadVersion=17029]="DocTypeReadVersion",s[s.Void=236]="Void",s[s.Segment=408125543]="Segment",s[s.SeekHead=290298740]="SeekHead",s[s.Seek=19899]="Seek",s[s.SeekID=21419]="SeekID",s[s.SeekPosition=21420]="SeekPosition",s[s.Info=357149030]="Info",s[s.TimestampScale=2807729]="TimestampScale",s[s.Duration=17545]="Duration",s[s.Tracks=374648427]="Tracks",s[s.TrackEntry=174]="TrackEntry",s[s.Video=224]="Video",s[s.Projection=30320]="Projection",s[s.ProjectionType=30321]="ProjectionType",s[s.ProjectionPrivate=30322]="ProjectionPrivate",s[s.Chapters=272869232]="Chapters",s[s.Cluster=524531317]="Cluster",s[s.Timestamp=231]="Timestamp",s[s.SilentTracks=22612]="SilentTracks",s[s.SilentTrackNumber=22743]="SilentTrackNumber",s[s.Position=167]="Position",s[s.PrevSize=171]="PrevSize",s[s.SimpleBlock=163]="SimpleBlock",s[s.BlockGroup=160]="BlockGroup",s[s.EncryptedBlock=175]="EncryptedBlock",s[s.Attachments=423732329]="Attachments",s[s.Tags=307544935]="Tags",s[s.Cues=475249515]="Cues",s[s.CuePoint=187]="CuePoint",s[s.CueTime=179]="CueTime",s[s.CueTrackPositions=183]="CueTrackPositions",s[s.CueTrack=247]="CueTrack",s[s.CueClusterPosition=241]="CueClusterPosition",s[s.CueRelativePosition=240]="CueRelativePosition",s[s.CueDuration=178]="CueDuration",s[s.CueBlockNumber=21368]="CueBlockNumber",s[s.CueCodecState=234]="CueCodecState",s[s.CueReference=219]="CueReference",s[s.CueRefTime=150]="CueRefTime"})(k||(k={}));var x;(function(s){s.SignedInteger="int",s.UnsignedInteger="uint",s.Float="float",s.String="string",s.UTF8="utf8",s.Date="date",s.Master="master",s.Binary="binary"})(x||(x={}));const mn={[k.EBML]:{type:x.Master},[k.EBMLVersion]:{type:x.UnsignedInteger},[k.EBMLReadVersion]:{type:x.UnsignedInteger},[k.EBMLMaxIDLength]:{type:x.UnsignedInteger},[k.EBMLMaxSizeLength]:{type:x.UnsignedInteger},[k.DocType]:{type:x.String},[k.DocTypeVersion]:{type:x.UnsignedInteger},[k.DocTypeReadVersion]:{type:x.UnsignedInteger},[k.Void]:{type:x.Binary},[k.Segment]:{type:x.Master},[k.SeekHead]:{type:x.Master},[k.Seek]:{type:x.Master},[k.SeekID]:{type:x.Binary},[k.SeekPosition]:{type:x.UnsignedInteger},[k.Info]:{type:x.Master},[k.TimestampScale]:{type:x.UnsignedInteger},[k.Duration]:{type:x.Float},[k.Tracks]:{type:x.Master},[k.TrackEntry]:{type:x.Master},[k.Video]:{type:x.Master},[k.Projection]:{type:x.Master},[k.ProjectionType]:{type:x.UnsignedInteger},[k.ProjectionPrivate]:{type:x.Master},[k.Chapters]:{type:x.Master},[k.Cluster]:{type:x.Master},[k.Timestamp]:{type:x.UnsignedInteger},[k.SilentTracks]:{type:x.Master},[k.SilentTrackNumber]:{type:x.UnsignedInteger},[k.Position]:{type:x.UnsignedInteger},[k.PrevSize]:{type:x.UnsignedInteger},[k.SimpleBlock]:{type:x.Binary},[k.BlockGroup]:{type:x.Master},[k.EncryptedBlock]:{type:x.Binary},[k.Attachments]:{type:x.Master},[k.Tags]:{type:x.Master},[k.Cues]:{type:x.Master},[k.CuePoint]:{type:x.Master},[k.CueTime]:{type:x.UnsignedInteger},[k.CueTrackPositions]:{type:x.Master},[k.CueTrack]:{type:x.UnsignedInteger},[k.CueClusterPosition]:{type:x.UnsignedInteger},[k.CueRelativePosition]:{type:x.UnsignedInteger},[k.CueDuration]:{type:x.UnsignedInteger},[k.CueBlockNumber]:{type:x.UnsignedInteger},[k.CueCodecState]:{type:x.UnsignedInteger},[k.CueReference]:{type:x.Master},[k.CueRefTime]:{type:x.UnsignedInteger}},Uo=s=>{const e=s.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=ls(s,t),r=i in mn,a=r?mn[i].type:x.Binary,n=s.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const u=new DataView(s.buffer,s.byteOffset+t+1,o-1),d=n&255>>o,l=ls(u),c=d*2**((o-1)*8)+l,h=t+o;let f;return h+c>s.byteLength?f=new DataView(s.buffer,s.byteOffset+h):f=new DataView(s.buffer,s.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:f,valueSize:c}},ls=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{const t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Je=(s,e)=>{switch(e){case x.SignedInteger:return s.getInt8(0);case x.UnsignedInteger:return ls(s);case x.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case x.String:return new TextDecoder("ascii").decode(s);case x.UTF8:return new TextDecoder("utf-8").decode(s);case x.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case x.Master:return s;case x.Binary:return s;default:V(e)}},Xt=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=Uo(i);if(!e(r))return;r.type===x.Master&&Xt(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},nm=s=>{if(s.getUint32(0)!==k.EBML)return!1;let e,t,i;const r=Uo(s);return Xt(r.value,({tag:a,type:n,value:o})=>(a===k.EBMLReadVersion?e=Je(o,n):a===k.DocType?t=Je(o,n):a===k.DocTypeReadVersion&&(i=Je(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Vo=[k.Info,k.SeekHead,k.Tracks,k.TrackEntry,k.Video,k.Projection,k.ProjectionType,k.ProjectionPrivate,k.Chapters,k.Cluster,k.Cues,k.Attachments,k.Tags],om=[k.Timestamp,k.SilentTracks,k.SilentTrackNumber,k.Position,k.PrevSize,k.SimpleBlock,k.BlockGroup,k.EncryptedBlock],dm=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,d,l=!1;const c=0;return Xt(s,({tag:h,type:f,value:m,valueSize:g})=>{if(h===k.SeekID){const T=Je(m,f);d=ls(T)}else h!==k.SeekPosition&&(d=void 0);return h===k.Segment?(e=m.byteOffset,t=m.byteOffset+g):h===k.Info?a=!0:h===k.SeekHead?n=!0:h===k.TimestampScale?i=Je(m,f):h===k.Duration?r=Je(m,f):h===k.SeekPosition&&d===k.Cues?u=Je(m,f):h===k.Tracks?Xt(m,({tag:T,type:A,value:E})=>T===k.ProjectionType?(l=Je(E,A)===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"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:l,stereoMode:c,projectionType:us.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},um=s=>{if(te(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},lm=(s,e)=>{let t=!1,i=!1;const r=o=>_(o.time)&&_(o.position),a=[];let n;return Xt(s,({tag:o,type:u,value:d})=>{switch(o){case k.Cues:t=!0;break;case k.CuePoint:n&&r(n)&&a.push(n),n={};break;case k.CueTime:n&&(n.time=Je(d,u));break;case k.CueTrackPositions:break;case k.CueClusterPosition:n&&(n.position=Je(d,u));break;default:t&&Vo.includes(o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{const{time:d,position:l}=o,c=a[u+1];return{status:ee.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}}})},cm=s=>{let e=0,t=!1;try{Xt(s,i=>i.tag===k.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):om.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[k.SimpleBlock,k.BlockGroup,k.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},hm={validateData:nm,parseInit:dm,getIndexRange:um,parseSegments:lm,parseFeedableSegmentChunk:cm},Ho=1e4,fm=3e4,pm=5e3,mm=Ho,vm=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a})=>{var n;const o=(n=a?Ai(a):void 0)!==null&&n!==void 0?n:Rt({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r}},gm=({id:s,bitrate:e})=>({id:s,bitrate:e}),Sm=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=Qe(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:Qe(s,-1)},bm=({id:s,lang:e,url:t,isAuto:i})=>({id:s,url:t,isAuto:i,type:"internal",language:e}),Gi=s=>{const e=[];let t=0,i=s.length-1;for(;t<Ho&&i>=0;)e.unshift(s[i]),t+=s[i].time.to-s[i].time.from,i--;return e};class vn{constructor(e,t,i,r,{fetcher:a,tuning:n,getCurrentPosition:o,compatibilityMode:u=!1,manifest:d}){switch(this.onLastSegment$=new S(!1),this.fullyBuffered$=new S(!1),this.playingRepresentation$=new S(void 0),this.playingRepresentationInit$=new S(void 0),this.error$=new L,this.gaps=[],this.isSeekingLive=!1,this.subscription=new re,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.startWith=Re(this.destroyAbortController.signal,async function*(l){const c=this.representations.get(l);P(c,`Cannot find representation ${l}`),this.playingRepresentationId=l,this.downloadingRepresentationId=l,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${c.mime}; codecs="${c.codecs}"`),this.sourceBufferTaskQueue=new Mp(this.sourceBuffer),this.subscription.add(B(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},g=>this.error$.next({id:"SegmentEjection",category:C.WTF,message:"Error when trying to clear segments ejected by browser",thrown:g}))),this.subscription.add(B(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:C.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(g=>{if(!this.sourceBuffer)return;const T=Math.min(this.bufferLimit,pn(this.sourceBuffer.buffered)*.8);this.bufferLimit=T,this.pruneBuffer(this.getCurrentPosition(),g)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(g=>this.error$.next(g))),yield this.loadInit(c,"high",!0);const h=this.initData.get(c.id),f=this.segments.get(c.id),m=this.parsedInitData.get(c.id);P(h,"No init buffer for starting representation"),P(f,"No segments for starting representation"),h instanceof ArrayBuffer&&(this.searchGaps(f,c),yield this.sourceBufferTaskQueue.append(h,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(m))}.bind(this)),this.switchTo=Re(this.destroyAbortController.signal,async function*(l){if(l===this.downloadingRepresentationId||l===this.switchingToRepresentationId)return;this.switchingToRepresentationId=l;const c=this.representations.get(l);P(c,`No such representation ${l}`);let h=this.segments.get(l),f=this.initData.get(l);if(te(f)||te(h)?yield this.loadInit(c,"high",!1):f instanceof Promise&&(yield f),h=this.segments.get(l),P(h,"No segments for starting representation"),f=this.initData.get(l),!f||!(f instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=l,this.abort(),yield this.sourceBufferTaskQueue.append(f,this.downloadAbortController.signal);const m=this.getCurrentPosition();_(m)&&(this.searchGaps(h,c),this.maintain(m))}.bind(this)),this.seekLive=Re(this.destroyAbortController.signal,async function*(l){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!l)return;for(const T of this.representations.keys()){const A=l.find(b=>b.id===T);A&&this.representations.set(T,A);const E=this.representations.get(T);if(!E)return;const v=Gi(E.segmentReference.segments);this.segments.set(E.id,v)}const c=this.switchingToRepresentationId?this.switchingToRepresentationId:this.downloadingRepresentationId,h=this.representations.get(c);P(h);const f=Gi(h.segmentReference.segments),m=this.initData.get(h.id);if(P(m,"No init buffer for starting representation"),P(f,"No segments for starting representation"),!(m instanceof ArrayBuffer))return;const g=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),g&&(yield this.sourceBufferTaskQueue.remove(g.from*1e3,g.to*1e3,this.destroyAbortController.signal)),this.searchGaps(f,h),yield this.sourceBufferTaskQueue.append(m,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this)),this.fetcher=a,this.tuning=n,this.compatibilityMode=u,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isLive=!!(d!=null&&d.dynamic),this.container=i,i){case Jt.MP4:this.containerParser=am;break;case Jt.WEBM:this.containerParser=hm;break;default:V(i)}this.initData=new Map(r.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new zt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(te(e)||te(this.downloadingRepresentationId)||te(this.playingRepresentationId)||te(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(P(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const r=i.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const l=bt(this.sourceBuffer.buffered,e),c=r?r.time.to+100:-1/0;r&&l>=r.time.to-e+100&&(a=c)}if(isFinite(this.bufferLimit)&&pn(this.sourceBuffer.buffered)>=this.bufferLimit){const d=bt(this.sourceBuffer.buffered,e),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<l);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{const l=Qe(o,0);l&&l.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}!this.isLive&&!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===ee.FED&&!o.length&&bt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const u=Qe(i,-1);u&&u.status===ee.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===u))}searchGaps(e,t){this.gaps=[];let i=0;for(const r of e)r.time.from-i>0&&this.gaps.push({representation:t.id,from:i,to:r.time.from}),i=r.time.to;_(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(r=>r.id===this.downloadingRepresentationId);if(!t)return;const i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var t,i,r,a;for(const n of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!n)return;const o=n.segmentReference.segments.map(c=>({...c,status:ee.NONE,size:void 0})),u=(i=this.segments.get(n.id))!==null&&i!==void 0?i:[],d=(a=(r=Qe(u,-1))===null||r===void 0?void 0:r.time.to)!==null&&a!==void 0?a:0,l=o==null?void 0:o.findIndex(c=>Math.round(d)>=Math.round(c.time.from)&&Math.round(d)<=Math.round(c.time.to));if(l===-1){this.liveUpdateSegmentIndex=0;const c=Gi(o);this.segments.set(n.id,[...c])}else{const c=o.slice(l+1);this.segments.set(n.id,[...u,...c])}}}findSegmentStartTime(e){var t,i,r;const a=(i=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&i!==void 0?i:this.playingRepresentationId;if(!a)return;const n=this.segments.get(a);if(!n)return;const o=n.find(u=>u.time.from<=e&&u.time.to>=e);return(r=o==null?void 0:o.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){const i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const r=e.findIndex(({status:c,time:{from:h,to:f}},m)=>{const g=h<=i&&f>=i,T=h>i||g||m===0&&i===0,A=Math.min(this.forwardBufferTarget,this.bufferLimit),E=this.preloadOnly&&h<=i+A||f<=i+A;return(c===ee.NONE||c===ee.PARTIALLY_EJECTED&&T&&E&&this.sourceBuffer&&!Lr(this.sourceBuffer.buffered,i))&&T&&E});if(r===-1)return[];if(t!==Be.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===ee.NONE||h.status===ee.PARTIALLY_EJECTED)u.push(h);else break}return u}async loadSegments(e,t,i="auto"){if(!e.length)return;let r,a,n=e;const{type:o}=t.segmentReference;switch(o){case Be.BYTE_RANGE:{r=t.segmentReference.url,a={from:Qe(e,0).byte.from,to:Qe(e,-1).byte.to};break}case Be.TEMPLATE:{const d=Qe(e,0);r=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:V(o)}for(const d of n)d.status=ee.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:u}=this.downloadAbortController;if(this.failedDownloads&&(await Re(u,async function*(){const d=fa(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,d))}.bind(this))(),u.aborted))for(const d of this.activeSegments)e.includes(d.segment)&&this.abortSegment(d.segment);return void this.fetcher.fetch(r,{range:a,onProgress:(d,l)=>{if(!u.aborted)try{this.onSomeDataLoaded(d,t.id,a?a.from:0,l,u)}catch(c){this.error$.next({id:"SegmentFeeding",category:C.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}},signal:u,priority:i}).then(()=>this.failedDownloads=0,d=>{if(d.name!=="AbortError"){for(const l of this.activeSegments)e.includes(l.segment)&&this.abortSegment(l.segment);this.onSegmentDownloadError(d)}})}onSegmentDownloadError(e){var t;let i=!1;const r=this.getCurrentPosition();this.sourceBuffer&&_(r)&&(i=bt((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,i||this.error$.next({id:"SegmentDownload",category:C.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,i,r,a){if(!this.activeSegments.size)return;const n=()=>{this.abort()},o=c=>{var h;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),c.segment.status=ee.FED,"size"in c.segment&&(c.segment.size=c.fedBytes);for(const f of this.representations.values())if(f.id!==t)for(const m of(h=this.segments.get(f.id))!==null&&h!==void 0?h:[])m.status===ee.FED&&m.time.from===c.segment.time.from&&m.time.to===c.segment.time.to&&(m.status=ee.NONE);this.activeSegments.delete(c),this.detectGapsWhenIdle(t,[c.segment])},u=this.representations.get(t);if(!u)return;const d=u.segmentReference.type,l=e.byteLength;for(const c of this.activeSegments){const{segment:h}=c,f=d===Be.BYTE_RANGE,m=f?h.byte.to-h.byte.from+1:l;if(c.representationId!==t||!(!f||h.byte.from>=i&&h.byte.to<i+e.byteLength))continue;if(a.aborted){n();continue}const T=f?h.byte.from-i:0,A=f?h.byte.to-i:e.byteLength,E=T<r,v=A<=r;if(h.status===ee.DOWNLOADING&&E&&v){h.status=ee.DOWNLOADED,this.activeSegments.delete(c);const b=new DataView(e.buffer,e.byteOffset+T,m);this.sourceBufferTaskQueue.append(b,a).then($=>$&&!a.aborted?o(c):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&E&&(c.loadedBytes=Math.min(m,r-T),c.loadedBytes>c.feedingBytes)){const b=new DataView(e.buffer,e.byteOffset+T+c.feedingBytes,c.loadedBytes-c.feedingBytes),$=c.loadedBytes===m?b:this.containerParser.parseFeedableSegmentChunk(b);$!=null&&$.byteLength&&(h.status=ee.PARTIALLY_FED,c.feedingBytes+=$.byteLength,this.sourceBufferTaskQueue.append($,a).then(D=>{if(a.aborted)n();else if(D)c.fedBytes+=$.byteLength,c.fedBytes===m&&o(c);else{if(c.feedingBytes<m)return;n()}}))}}}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===ee.PARTIALLY_FED||e.status===ee.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=ee.NONE),e.status=ee.PARTIALLY_EJECTED):e.status=ee.NONE;for(const i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,a]of this.initData.entries()){const n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=fn(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Re(this.destroyAbortController.signal,async function*(){const o=fa(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),this.segments.set(e.id,this.isLive?Gi(l):l),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:C.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||te(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,n=-1/0,o=!1;const u=d=>{var l;a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const c="size"in d?(l=d.size)!==null&&l!==void 0?l:0:d.byte.to-d.byte.from;r+=c};for(const d of this.segments.values())for(const l of d){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;l.status===ee.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===ee.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===ee.NONE&&Math.round(f.time.from)<=Math.round(l)&&Math.round(f.time.to)>=Math.round(c)){a=l,n=c;break}}if(o=isFinite(a)&&isFinite(n),!o&&i){r=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const l of this.segments.values())for(const c of l)c.time.from>e+d&&c.status===ee.FED&&u(c)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=fn(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:C.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(te(this.sourceBuffer)||te(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}const t=1;for(const i of this.segments.values())for(const r of i){const{status:a}=r;if(a!==ee.FED&&a!==ee.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(l=>l.from-t<=n&&l.to+t>=o),d=e.filter(l=>n>=l.from-t&&n<=l.to+t||o>=l.from-t&&o<=l.to+t);u||(d.length===1?r.status=ee.PARTIALLY_EJECTED:r.status=ee.NONE)}}}var jt;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(jt||(jt={}));class ym{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new S(void 0),this.lastConnectionReused$=new S(void 0),this.lastRequestFirstBytes$=new S(void 0),this.abortAllController=new zt,this.subscription=new re,this.fetchManifest=Re(this.abortAllController.signal,async function*(r){let a=r;this.requestQuic&&(a=Kt(a));const n=yield bi(a,{signal:this.abortAllController.signal}).catch(li);return n?(this.onHeadersReceived(n.headers),n.text()):null}.bind(this)),this.fetch=Re(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}={}){var c,h,f,m;let g=r;const T=new Headers;if(n)switch(a){case jt.HEADER:{T.append("Range",`bytes=${n.from}-${n.to}`);break}case jt.PARAM:{const M=new URL(g,location.href);M.searchParams.append("bytes",`${n.from}-${n.to}`),g=M.toString();break}default:V(a)}this.requestQuic&&(g=Kt(g));let A=this.abortAllController.signal,E;if(d){const M=new zt;if(E=U(B(this.abortAllController.signal,"abort"),B(d,"abort")).subscribe(()=>{try{M.abort()}catch(X){li(X)}}),this.abortAllController.signal.aborted||d.aborted)try{M.abort()}catch(X){li(X)}A=M.signal}const v=pe(),b=yield bi(g,{priority:u,headers:T,signal:A}).catch(li),$=pe();if((c=this.throughputEstimator)===null||c===void 0||c.addRawRtt($-v),!b)return E==null||E.unsubscribe(),null;if(!b.ok||!b.body)return E==null||E.unsubscribe(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`));this.onHeadersReceived(b.headers);const D=parseInt((h=b.headers.get("Content-Length"))!==null&&h!==void 0?h:"",10)||n&&n.to-n.from+1||NaN;if(!D){const M=yield b.arrayBuffer();return(f=this.throughputEstimator)===null||f===void 0||f.addRawSpeed(M.byteLength,pe()-$),o==null||o(new DataView(M),M.byteLength),E==null||E.unsubscribe(),M}if(!o&&!l)return E==null||E.unsubscribe(),b.arrayBuffer();const[Y,J]=b.body.tee(),N=Y.getReader();l&&((m=this.throughputEstimator)===null||m===void 0||m.trackStream(J));let G=0;const Q=new ArrayBuffer(D),O=new Uint8Array(Q),H=new DataView(Q);let ae=!1;const F=M=>{E==null||E.unsubscribe(),ae=!0,li(M)},I=Re(A,async function*({done:M,value:X}){if(G===0&&this.lastRequestFirstBytes$.next(pe()-v),A.aborted){E==null||E.unsubscribe();return}!M&&X&&(O.set(X,G),G+=X.byteLength,o==null||o(H,G),yield N==null?void 0:N.read().then(I,F))}.bind(this));return yield N==null?void 0:N.read().then(I,F),E==null||E.unsubscribe(),ae?null:Q}.bind(this)),this.fetchByteRangeRepresentation=Re(this.abortAllController.signal,async function*(r,a,n){var o;if(r.type!==Be.BYTE_RANGE)return null;const{from:u,to:d}=r.initRange;let l=u,c=d,h=!1,f,m;r.indexRange&&(f=r.indexRange.from,m=r.indexRange.to,h=d+1===f,h&&(l=Math.min(f,u),c=Math.max(m,d))),l=Math.min(l,0);const g=yield this.fetch(r.url,{range:{from:l,to:c},priority:n,measureThroughput:!1});if(!g)return null;const T=new DataView(g,u-l,d-l+1);if(!a.validateData(T))throw new Error("Invalid media file");const A=a.parseInit(T),E=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(A);if(!E)throw new ReferenceError("No way to load representation index");let v;if(h)v=new DataView(g,E.from-l,E.to-E.from+1);else{const $=yield this.fetch(r.url,{range:E,priority:n,measureThroughput:!1});if(!$)return null;v=new DataView($)}const b=a.parseSegments(v,A,E);return{init:A,dataView:new DataView(g),segments:b}}.bind(this)),this.fetchTemplateRepresentation=Re(this.abortAllController.signal,async function*(r,a){if(r.type!==Be.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:ee.NONE,size:void 0})),dataView:new DataView(o)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=xo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var r,a;const{type:n}=e;switch(n){case Be.BYTE_RANGE:return(r=await this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case Be.TEMPLATE:return(a=await this.fetchTemplateRepresentation(e,i))!==null&&a!==void 0?a:null;default:V(n)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const li=s=>{if(!(s instanceof DOMException)||!(s.name==="AbortError"||s.code===20))throw s};var Tm=It,Em=fs,$m=qe,Am=$m("match"),km=function(s){var e;return Tm(s)&&((e=s[Am])!==void 0?!!e:Em(s)=="RegExp")},wm=bs,_m=String,Pm=function(s){if(wm(s)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return _m(s)},Dm=Lt,Rm=function(){var s=Dm(this),e="";return s.hasIndices&&(e+="d"),s.global&&(e+="g"),s.ignoreCase&&(e+="i"),s.multiline&&(e+="m"),s.dotAll&&(e+="s"),s.unicode&&(e+="u"),s.unicodeSets&&(e+="v"),s.sticky&&(e+="y"),e},Im=dt,xm=ut,Lm=Vr,Cm=Rm,gn=RegExp.prototype,Om=function(s){var e=s.flags;return e===void 0&&!("flags"in gn)&&!xm(s,"flags")&&Lm(gn,s)?Im(Cm,s):e},ea=ot,Bm=vs,Mm=Math.floor,ar=ea("".charAt),Nm=ea("".replace),nr=ea("".slice),Fm=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Um=/\$([$&'`]|\d{1,2})/g,Vm=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=Um;return r!==void 0&&(r=Bm(r),u=Fm),Nm(a,u,function(d,l){var c;switch(ar(l,0)){case"$":return"$";case"&":return s;case"`":return nr(e,0,t);case"'":return nr(e,n);case"<":c=r[nr(l,1,-1)];break;default:var h=+l;if(h===0)return d;if(h>o){var f=Mm(h/10);return f===0?d:f<=o?i[f-1]===void 0?ar(l,1):i[f-1]+ar(l,1):d}c=i[h-1]}return c===void 0?"":c})},Hm=Ss,Gm=dt,ta=ot,Sn=Nr,Ym=Ne,qm=ps,jm=km,Gt=Pm,zm=ms,Wm=Om,Qm=Vm,Km=qe,Jm=Km("replace"),Xm=TypeError,Go=ta("".indexOf),Zm=ta("".replace),bn=ta("".slice),ev=Math.max,yn=function(s,e,t){return t>s.length?-1:e===""?t:Go(s,e,t)};Hm({target:"String",proto:!0},{replaceAll:function(e,t){var i=Sn(this),r,a,n,o,u,d,l,c,h,f=0,m=0,g="";if(!qm(e)){if(r=jm(e),r&&(a=Gt(Sn(Wm(e))),!~Go(a,"g")))throw Xm("`.replaceAll` does not allow non-global regexes");if(n=zm(e,Jm),n)return Gm(n,e,i,t);if(r)return Zm(Gt(i),e,t)}for(o=Gt(i),u=Gt(e),d=Ym(t),d||(t=Gt(t)),l=u.length,c=ev(1,l),f=yn(o,u,0);f!==-1;)h=d?Gt(t(u,f,o)):Qm(u,o,f,[],void 0,t),g+=bn(o,m,f)+h,m=f+l,f=yn(o,u,f+c);return m<o.length&&(g+=bn(o,m)),g}});var tv=Ro,iv=tv("String","replaceAll"),sv=iv,rv=sv,av=rv,nv=av,Tn=Mr(nv);const En=s=>{if(!s.startsWith("P"))return;const e=(n,o)=>{const u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},or=(s,e)=>{let t=s;t=Tn(t,"$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,a]of Object.entries(i)){const n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=Tn(t,n,(o,u)=>te(a)?o:te(u)?a:a.padStart(parseInt(u,10),"0"))}return t},ov=(s,e)=>{var t,i,r,a,n,o,u,d,l,c,h,f,m,g,T,A,E,v,b,$,D,Y,J,N,G,Q,O,H,ae,F,I,M,X,he,ve,_e,je,pt,Z;const xe=new DOMParser().parseFromString(s,"application/xml"),Pe={video:[],audio:[],text:[]},Le=xe.children[0],Ot=Le.getElementsByTagName("Period")[0],$t=Ot.children,Bt=Le.getAttribute("type")==="dynamic",Mt=Le.getAttribute("availabilityStartTime"),wi=Mt?new Date(Mt).getTime():void 0;let At;const ia=Le.getAttribute("mediaPresentationDuration"),sa=Ot.getAttribute("duration"),As=Le.getElementsByTagName("vk:Attrs")[0],ra=As==null?void 0:As.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(ia)At=En(ia);else if(sa){const Fe=En(sa);_(Fe)&&(At=Fe)}else ra&&(At=parseInt(ra,10));let Jo=0;const ks=(i=(t=Le.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],Xo=ks.includes(ds.WEBM_AS_IN_FFMPEG)||ks.includes(ds.WEBM_AS_IN_SPEC)?Jt.WEBM:Jt.MP4;for(const Fe of $t){const _i=Fe.getAttribute("mimeType"),Zo=Fe.getAttribute("codecs"),aa=(r=Fe.getAttribute("contentType"))!==null&&r!==void 0?r:_i==null?void 0:_i.split("/")[0],ed=(n=(a=Fe.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],na=Fe.querySelectorAll("Representation"),td=Fe.querySelector("SegmentTemplate");if(aa===Te.TEXT){for(const ge of na){const mt=ge.getAttribute("id")||"",Pi=Fe.getAttribute("lang"),Nt=(d=(u=(o=ge.querySelector("BaseURL"))===null||o===void 0?void 0:o.textContent)===null||u===void 0?void 0:u.trim())!==null&&d!==void 0?d:"",ws=new URL(Nt,e).toString(),_s=mt.includes("_auto");Pe[Te.TEXT].push({id:mt,lang:Pi,isAuto:_s,kind:Te.TEXT,url:ws})}continue}for(const ge of na){const mt=(l=ge.getAttribute("mimeType"))!==null&&l!==void 0?l:_i,Pi=(h=(c=ge.getAttribute("codecs"))!==null&&c!==void 0?c:Zo)!==null&&h!==void 0?h:"",Nt=(m=(f=ge.getAttribute("contentType"))!==null&&f!==void 0?f:mt==null?void 0:mt.split("/")[0])!==null&&m!==void 0?m:aa,ws=(T=(g=Fe.getAttribute("profiles"))===null||g===void 0?void 0:g.split(","))!==null&&T!==void 0?T:[],_s=parseInt((A=ge.getAttribute("width"))!==null&&A!==void 0?A:"",10),oa=parseInt((E=ge.getAttribute("height"))!==null&&E!==void 0?E:"",10),da=parseInt((v=ge.getAttribute("bandwidth"))!==null&&v!==void 0?v:"",10)/1e3,ua=(b=ge.getAttribute("frameRate"))!==null&&b!==void 0?b:"",id=($=ge.getAttribute("quality"))!==null&&$!==void 0?$:void 0,sd=ua?Xr(ua):void 0,rd=(D=ge.getAttribute("id"))!==null&&D!==void 0?D:(Jo++).toString(10),ad=Nt==="video"?`${oa}p`:Nt==="audio"?`${da}Kbps`:Pi,nd=`${rd}@${ad}`,od=(N=(J=(Y=ge.querySelector("BaseURL"))===null||Y===void 0?void 0:Y.textContent)===null||J===void 0?void 0:J.trim())!==null&&N!==void 0?N:"",la=new URL(od,e).toString(),dd=[...ks,...ed,...ws];let Ps;const ud=ge.querySelector("SegmentBase"),kt=(G=ge.querySelector("SegmentTemplate"))!==null&&G!==void 0?G:td;if(ud){const si=(O=(Q=ge.querySelector("SegmentBase Initialization"))===null||Q===void 0?void 0:Q.getAttribute("range"))!==null&&O!==void 0?O:"",[ri,Rs]=si.split("-").map(Ft=>parseInt(Ft,10)),ai={from:ri,to:Rs},ni=(H=ge.querySelector("SegmentBase"))===null||H===void 0?void 0:H.getAttribute("indexRange"),[Is,Di]=ni?ni.split("-").map(Ft=>parseInt(Ft,10)):[],oi=ni?{from:Is,to:Di}:void 0;Ps={type:Be.BYTE_RANGE,url:la,initRange:ai,indexRange:oi}}else if(kt){const si={representationId:(ae=ge.getAttribute("id"))!==null&&ae!==void 0?ae:void 0,bandwidth:(F=ge.getAttribute("bandwidth"))!==null&&F!==void 0?F:void 0},ri=parseInt((I=kt.getAttribute("timescale"))!==null&&I!==void 0?I:"",10),Rs=(M=kt.getAttribute("initialization"))!==null&&M!==void 0?M:"",ai=kt.getAttribute("media"),ni=(he=parseInt((X=kt.getAttribute("startNumber"))!==null&&X!==void 0?X:"",10))!==null&&he!==void 0?he:1,Is=or(Rs,si);if(!ai)throw new ReferenceError("No media attribute in SegmentTemplate");const Di=(ve=kt.querySelectorAll("SegmentTimeline S"))!==null&&ve!==void 0?ve:[],oi=[];let Ft=0;if(Di.length){let xs=ni,tt=0;for(const di of Di){const vt=parseInt((_e=di.getAttribute("d"))!==null&&_e!==void 0?_e:"",10),wt=parseInt((je=di.getAttribute("r"))!==null&&je!==void 0?je:"",10)||0,Ri=parseInt((pt=di.getAttribute("t"))!==null&&pt!==void 0?pt:"",10);tt=Number.isFinite(Ri)?Ri:tt;const Ls=vt/ri*1e3,ca=tt/ri*1e3;for(let Ii=0;Ii<wt+1;Ii++){const ld=or(ai,{...si,segmentNumber:xs.toString(10),segmentTime:(tt+Ii*vt).toString(10)}),ha=(ca||0)+Ii*Ls,cd=ha+Ls;xs++,oi.push({time:{from:ha,to:cd},url:ld})}tt+=(wt+1)*vt,Ft+=(wt+1)*Ls}}else if(_(At)){const tt=parseInt((Z=kt.getAttribute("duration"))!==null&&Z!==void 0?Z:"",10)/ri*1e3,di=Math.ceil(At/tt);let vt=0;for(let wt=1;wt<di;wt++){const Ri=or(ai,{...si,segmentNumber:wt.toString(10),segmentTime:vt.toString(10)});oi.push({time:{from:vt,to:vt+tt},url:Ri}),vt+=tt}}Ps={type:Be.TEMPLATE,baseUrl:la,initUrl:Is,totalSegmentsDurationMs:Ft,segments:oi}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Nt||!mt)continue;const Ds={video:Te.VIDEO,audio:Te.AUDIO,text:Te.TEXT}[Nt];Ds&&Pe[Ds].push({id:nd,kind:Ds,segmentReference:Ps,profiles:dd,duration:At,bitrate:da,mime:mt,codecs:Pi,width:_s,height:oa,fps:sd,quality:id})}}return{dynamic:Bt,liveAvailabilityStartTime:wi,duration:At,container:Xo,representations:Pe}},Cr=1e3,$n=["timeupdate","progress","play","seeked","stalled","waiting"];var Oe;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(Oe||(Oe={}));let dv=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new re,this.representationSubscription=new re,this.state$=new ue(Oe.NONE),this.currentVideoRepresentation$=new S(void 0),this.currentVideoRepresentationInit$=new S(void 0),this.error$=new L,this.lastConnectionType$=new S(void 0),this.lastConnectionReused$=new S(void 0),this.lastRequestFirstBytes$=new S(void 0),this.isLive$=new S(!1),this.liveDuration$=new S(0),this.liveAvailabilityStartTime$=new S(void 0),this.bufferLength$=new S(0),this.liveLoadBufferLength$=new S(0),this.forceEnded$=new L,this.gapWatchdogStarted=!1,this.destroyController=new zt,this.initManifest=Re(this.destroyController.signal,async function*(t,i,r){var a;this.element=t,this.manifestUrlString=He(i,r,be.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Oe.MANIFEST_READY),this.manifest=yield this.updateManifest(),!((a=this.manifest)===null||a===void 0)&&a.representations.video.length?this.state$.setState(Oe.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:C.PARSER,message:"No playable video representations"})}.bind(this)),this.updateManifest=Re(this.destroyController.signal,async function*(){var t;const i=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:C.NETWORK,message:"Failed to load manifest",thrown:n})});if(!i)return this.manifest;let r;try{r=ov(i!=null?i:"",this.manifestUrlString)}catch(n){this.error$.next({id:"ManifestParsing",category:C.PARSER,message:"Failed to parse MPD manifest",thrown:n})}if(!r)return null;const a=({kind:n,mime:o,codecs:u})=>{var d,l,c,h;return!!(!((l=(d=this.element)===null||d===void 0?void 0:d.canPlayType)===null||l===void 0)&&l.call(d,o)&&(!((h=(c=window.MediaSource)===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0)&&h.call(c,`${o}; codecs="${u}"`))||n===Te.TEXT)};return this.isLive$.getValue()!==r.dynamic&&(this.isLive$.next(r.dynamic),this.liveDuration$.getValue()!==r.duration&&this.liveDuration$.next(-1*((t=r.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==r.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(r.liveAvailabilityStartTime)),{...r,representations:Qt(Object.entries(r.representations).map(([n,o])=>[n,o.filter(a)]))}}.bind(this)),this.initRepresentations=Re(this.destroyController.signal,async function*(t,i){P(this.manifest),P(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Oe.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,manifest:this.manifest};if(this.videoBufferManager=new vn(Te.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],_(i)&&(this.audioBufferManager=new vn(Te.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,r),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(is(Cr).subscribe(o=>{var u;if(!((u=this.element)===null||u===void 0)&&u.paused){const d=nn(this.manifestUrlString,be.DASH_CMAF_OFFSET_P);this.manifestUrlString=He(this.manifestUrlString,d+1e3,be.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(U(...$n.map(o=>B(this.element,o))).pipe(md(Cr),w(o=>this.element?bt(this.element.buffered,this.element.currentTime*1e3):0)).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.subscribe(u=>{var d,l;let c=0;if(u){const h=((l=(d=this.element)===null||d===void 0?void 0:d.currentTime)!==null&&l!==void 0?l:0)*1e3;c=Math.min(...this.bufferManagers.map(m=>{var g,T;return(T=(g=m.getLiveSegmentsToLoadState(this.manifest))===null||g===void 0?void 0:g.to)!==null&&T!==void 0?T:0}))-h}this.liveLoadBufferLength$.next(c)}));let o=0;this.representationSubscription.add(this.liveLoadBufferLength$.subscribe(async u=>{P(this.element);const d=this.element.playbackRate,l=nn(this.manifestUrlString,be.DASH_CMAF_OFFSET_P),c=fm*d,h=mm*d,f=pm*d;o=u>o?u:o;const m=l===0&&u<f,g=l!==0&&u<c+f&&u>=c,T=l!==0&&u<c;if(T||g){const A=o-(c+h),E=Math.trunc(l+A/d);let v;u?E>0?v=E:v=0:v=l,this.manifestUrlString=He(this.manifestUrlString,v,be.DASH_CMAF_OFFSET_P)}(m||T||g)&&(await this.updateLive(),o=0)}))}const a=U(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(w(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=U(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(w(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.representationSubscription.add(U(this.forceEnded$,Ie({allBuffersFull:a,someBufferEnded:n}).pipe(se(({allBuffersFull:o,someBufferEnded:u})=>o&&u))).subscribe(()=>{var o;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(u=>!u.updating))try{(o=this.source)===null||o===void 0||o.endOfStream()}catch(u){this.error$.next({id:"EndOfStream",category:C.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:u})}})),this.representationSubscription.add(U(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield new Promise(o=>{var u;return(u=this.source)===null||u===void 0?void 0:u.addEventListener("sourceopen",o)})),_(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&_(i)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)]):yield this.videoBufferManager.startWith(t),this.state$.setState(Oe.REPRESENTATIOS_READY)}.bind(this)),this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((i=this.audioBufferManager)===null||i===void 0)&&i.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=is(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:C.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new ym({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}async seekLive(e){var t,i,r,a;P(this.element),this.manifestUrlString=He(this.manifestUrlString,e,be.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),await((t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((i=this.manifest)===null||i===void 0?void 0:i.representations.video)),await((r=this.audioBufferManager)===null||r===void 0?void 0:r.seekLive((a=this.manifest)===null||a===void 0?void 0:a.representations.audio))}initBuffer(){P(this.element),this.state$.setState(Oe.RUNNING),this.subscription.add(U(...$n.map(e=>B(this.element,e)),B(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:C.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(B(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(B(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Lr(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){const i={[Te.VIDEO]:this.videoBufferManager,[Te.AUDIO]:this.audioBufferManager,[Te.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)}seek(e,t){var i,r,a,n,o;P(this.element),P(this.videoBufferManager);let u;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?u=e:u=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!==null&&i!==void 0?i:e,(a=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&a!==void 0?a:e),Lr(this.element.buffered,u)||(this.videoBufferManager.abort(),(n=this.audioBufferManager)===null||n===void 0||n.abort()),this.videoBufferManager.maintain(u),(o=this.audioBufferManager)===null||o===void 0||o.maintain(u),this.element.currentTime=u/1e3}stop(){var e,t;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(e=this.videoBufferManager)===null||e===void 0||e.destroy(),this.videoBufferManager=null,(t=this.audioBufferManager)===null||t===void 0||t.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Oe.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}async updateLive(){var e;this.manifest=await this.updateManifest(),(e=this.bufferManagers)===null||e===void 0||e.forEach(t=>t.updateLive(this.manifest))}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isLive$.getValue()&&this.element.currentTime>e.to&&(this.element.currentTime=0);const t=this.element.currentTime*1e3,i=[];for(const r of this.bufferManagers)for(const a of r.gaps)r.playingRepresentation$.getValue()===a.representation&&a.from<=t&&a.to>t&&(this.element.duration*1e3-a.to<this.tuning.endGapTolerance?i.push(1/0):i.push(a.to));if(i.length){const r=Math.max(...i);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=r/1e3}}};class uv{constructor(e,t){this.fov=e,this.orientation=t}}class lv{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,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);const r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:a,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){const e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){const t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}const t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){const r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var cv=`#define GLSLIFY 1
|
|
29
|
+
`}),F}return d==null||d.recordSwitch(H),H};var we=s=>new URL(s).hostname;const hp=300,ns=(s,e=hp)=>new cs(t=>{const{width:i,height:r}=s.getBoundingClientRect();if(t.next({width:i,height:r}),!window.ResizeObserver)return;const a=new ResizeObserver(bd(n=>{const o=n[0];if(!o)return;let u,d;o.contentBoxSize&&o.contentBoxSize[0]?(d=o.contentBoxSize[0].blockSize,u=o.contentBoxSize[0].inlineSize):o.contentRect&&(u=o.contentRect.width,d=o.contentRect.height),_(u)&&_(d)&&t.next({width:u,height:d})},e));return a.observe(s),()=>a.disconnect()});class Ts{constructor(){this.onDroopedVideoFramesLimit$=new L,this.subscription=new re,this.playing=!1,this.tracks=[],this.forceChecker$=new L,this.isForceCheckCounter=0,this.prevTotalVideoFrames=0,this.prevDroppedVideoFrames=0,this.limitCounts={},this.handleChangeVideoQuality=()=>{const e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!vi(e.quality)&&this.onChangeQuality(e.quality)},this.checkDroppedFrames=()=>{var e;const{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality(),r=t-this.prevTotalVideoFrames,a=i-this.prevDroppedVideoFrames,n=1-(r-a)/r;!isNaN(n)&&n>0&&this.log({message:`[dropped]. current dropped percent: ${n}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(n)&&n>=this.droppedFramesChecker.percentLimit&&pi(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((e=this.limitCounts[this.currentQuality])!==null&&e!==void 0?e:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(t,i)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(B(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=is(this.droppedFramesChecker.checkTime).pipe(se(()=>this.playing),se(()=>{const r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(Me(this.droppedFramesChecker.checkTime)),i=U(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var t,i;const r=(i=(t=Object.entries(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>Ki(a,n)?-1:1))===null||t===void 0?void 0:t[0])===null||i===void 0?void 0:i[0];return e!=null?e:r}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}}const ui={};var W;(function(s){s.DOWNLOADING_LIB="downloading_lib",s.STOPPED="stopped",s.STREAM_INITIALIZED="stream_initialized",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(W||(W={}));const Se=(s,e)=>new cs(t=>{const i=r=>t.next(r);return s.on(e,i),()=>s.off(e,i)});class un{constructor(e){this.subscription=new re,this.videoState=new ue(W.DOWNLOADING_LIB),this.textTracksManager=new Ze,this.droppedFramesManager=new Ts,this.videoTracks$=new S([]),this.frameRatesByFrameHeight={},this.isLive$=new S(void 0),this.maxSeekBackTime$=new S(1/0),this.availableFrom$=new S(void 0),this.elementSize$=new S(void 0),this.liveOffset=new ys,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState(),n=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===W.DOWNLOADING_LIB||t===W.STREAM_INITIALIZED))switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===z.Requested&&t!==W.STOPPED&&i!==p.STOPPED&&(n?this.seek(a.position-this.liveOffset.getTotalPausedTime()):this.seek(a.position)),i){case p.STOPPED:{switch(t){case W.STOPPED:break;case W.PLAYING:case W.PAUSED:case W.READY:this.stop();break;default:V(t)}break}case p.READY:{switch(t){case W.STOPPED:this.prepare();break;case W.PLAYING:case W.PAUSED:case W.READY:break;default:V(t)}break}case p.PLAYING:{switch(t){case W.PLAYING:break;case W.PAUSED:n&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case W.READY:this.play();break;case W.STOPPED:this.prepare();break;default:V(t)}break}case p.PAUSED:{switch(t){case W.PLAYING:this.pause(),this.liveOffset.pause();break;case W.PAUSED:break;case W.READY:this.videoState.setState(W.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED);break;case W.STOPPED:this.prepare();break;default:V(t)}break}default:V(i)}},this.video=ct(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=r=>{var a;e||this.params.output.error$.next({id:r==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:C.NETWORK,message:`Dash.js failed to load: ${(a=r==null?void 0:r.toString)===null||a===void 0?void 0:a.call(r)}`,thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(ui.MediaPlayer=r.MediaPlayer,ui.Debug=r.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){P(ui.MediaPlayer,"dashjs not loaded"),P(ui.Debug,"dashjs not loaded"),this.player=ui.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter(e=>(e.height&&(this.frameRatesByFrameHeight[e.height]=e.frameRate?Xr(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&Hf(this.player),Ff(this.player),this.params.tuning.requestQuick&&Vf(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(W.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=v=>{e.error$.next({id:"DashIFProvider",category:C.WTF,message:"DashIFProvider internal logic error",thrown:v})},r=(v,b)=>this.subscription.add(v.subscribe(b,i));r(ns(this.video),this.elementSize$),r(Se(this.player,"error").pipe(w(v=>{const b=typeof v.error=="object"?v.error.code:v.error,$=typeof v.error=="object"?v.error.message:void 0;return{id:`DashJS#${b}`,message:$}})),e.error$),r(Se(this.player,"playbackError").pipe(w(v=>({id:"DashJSPlayback",message:v.error}))),e.error$);const a=Se(this.player,"qualityChangeRendered").pipe(se(({mediaType:v})=>v==="video"),w(({newQuality:v})=>{var b;return(b=this.videoTracks$.getValue().find(({bitrateInfo:$})=>$.qualityIndex===v))===null||b===void 0?void 0:b.track}));a.pipe(se(_)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(se(({to:v})=>v===W.STREAM_INITIALIZED),me()).subscribe(()=>{this.subscription.add(Ge(t.videoTrack,()=>{var v,b;const $=this.player.getQualityFor("video");return(b=(v=this.videoTracks$.getValue().find(({bitrateInfo:D})=>D.qualityIndex===$))===null||v===void 0?void 0:v.track)===null||b===void 0?void 0:b.id},v=>{var b;if(te(v))return;const $=(b=this.videoTracks$.getValue().find(({track:D})=>D.id===v))===null||b===void 0?void 0:b.bitrateInfo;$&&this.player.setQualityFor("video",$.qualityIndex)},{changed$:a.pipe(w(v=>v==null?void 0:v.id)),onError:i}))},i)),this.subscription.add(Ge(t.autoVideoTrackSwitching,()=>{var v,b,$;return($=(b=(v=this.player.getSettings().streaming)===null||v===void 0?void 0:v.abr)===null||b===void 0?void 0:b.autoSwitchBitrate)===null||$===void 0?void 0:$.video},v=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:v}}}}),{onError:i})),r(Se(this.player,"bufferStateChanged").pipe(se(({mediaType:v})=>v==="video"),w(({state:v})=>v==="bufferStalled")),e.isBuffering$),r(Se(this.player,"fragmentLoadingStarted"),({mediaType:v,request:{url:b}})=>{var $,D;const Y=this.player.getDashMetrics(),J=Y.getLatestFragmentRequestHeaderValueByID(v,"X-Reused"),N=($=Y.getLatestFragmentRequestHeaderValueByID(v,"X-Delivery-Type"))!==null&&$!==void 0?$:gi.HTTP1,G=(D={1:!0,0:!1}[J])!==null&&D!==void 0?D:void 0;this.params.output.httpConnectionType$.next(N),this.params.output.httpConnectionReused$.next(G),e.hostname$.next(we(b))}),r(Se(this.player,"streamInitialized"),({streamInfo:{duration:v,manifestInfo:{isDynamic:b,availableFrom:$}}})=>{this.isLive$.next(b),this.availableFrom$.next($.getTime()),b||e.duration$.next(v);const D=[],Y=this.player.getQualityFor("video");let J;for(const N of this.player.getBitrateInfoListFor("video")){const G=N.qualityIndex.toString(10),Q=Rt(N),O=N.bitrate/1e3,H={width:N.width,height:N.height},ae=this.frameRatesByFrameHeight[N.height];if(Q){const F={id:G,quality:Q,bitrate:O,size:H,fps:ae};D.push({track:F,bitrateInfo:N}),N.qualityIndex===Y&&(J=F)}}this.videoTracks$.next(D),e.availableVideoTracks$.next(D.map(({track:N})=>N)),J&&e.currentVideoTrack$.next(J),this.videoState.setState(W.STREAM_INITIALIZED),this.videoState.startTransitionTo(W.READY)}),r(Se(this.player,"fragmentLoadingCompleted"),({request:v})=>{if(!v.requestEndDate||!v.firstByteDate||!v.bytesLoaded)return;const b=v.requestEndDate.getTime()-v.firstByteDate.getTime(),$=v.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed($,b)}),r(U(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeStarted$,this.droppedFramesManager.onDroopedVideoFramesLimit$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks$.getValue().length)return;const v=this.params.dependencies.throughputEstimator.throughput$.getValue(),b=ti(this.videoTracks$.getValue().map(({track:Y})=>Y),{container:this.elementSize$.getValue(),throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),$=t.autoVideoTrackLimits.getTransition();$&&e.autoVideoTrackLimits$.next($.to);const D=this.videoTracks$.getValue().find(({track:Y})=>Y===b);D!=null&&D.bitrateInfo&&this.player.setQualityFor("video",D==null?void 0:D.bitrateInfo.qualityIndex,!1)}),r(Ie({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(se(_))}).pipe(se(({isLive:v})=>v),w(({maxSeekBackTime:v})=>-v/1e3)),this.params.output.duration$);const n=Se(this.player,"playbackTimeUpdated").pipe(w(({time:v})=>v!=null?v:0));r(Ie({availableFrom:this.availableFrom$.pipe(se(_)),currentTime:n}),({availableFrom:v,currentTime:b})=>this.params.output.liveTime$.next(v+b*1e3)),r(n.pipe(se(()=>this.isLive$.getValue()===!1)),e.position$),r(Se(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),r(Se(this.player,"playbackEnded"),e.endedEvent$),r(Se(this.player,"playbackProgress").pipe(w(()=>Do(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(Se(this.player,"playbackPlaying"),()=>{this.videoState.setState(W.PLAYING),R(t.playbackState,p.PLAYING)}),r(Se(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(W.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(Se(this.player,"playbackPaused"),()=>{this.videoState.setState(W.PAUSED),R(t.playbackState,p.PAUSED)}),r(Se(this.player,"canPlay"),()=>{var v;((v=this.videoState.getTransition())===null||v===void 0?void 0:v.to)===W.READY&&this.videoState.setState(W.READY)}),r(this.isLive$,e.isLive$),r(ns(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=U(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Me(0));r(o,this.syncPlayback);const{playbackDuration$:u,ping$:d,connectionType$:l,connectionReused$:c}=Uf(this.player);r(l,this.params.output.httpConnectionType$),r(c,this.params.output.httpConnectionReused$),r(u,this.maxSeekBackTime$),r(d.pipe(me()),e.firstBytesEvent$),r(Se(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(Ie({isLive:this.isLive$,isShort:e.duration$.pipe(w(v=>v<60))}),({isLive:v,isShort:b})=>{const $=!v&&b;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:$}}})}),r(n.pipe(se(v=>v>this.params.tuning.insufficientBufferRuleMargin),me()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(Se(this.player,"manifestLoaded").pipe(me()).subscribe(()=>{this.subscription.add(Se(this.player,"playbackPlaying").pipe(me(),Wt(void 0)).subscribe(e.firstFrameEvent$,i))},i)),r(Se(this.player,"manifestLoaded"),v=>{var b,$,D,Y,J,N,G;if(!(($=(b=v.data)===null||b===void 0?void 0:b.Period)===null||$===void 0)&&$.AdaptationSet){const Q=[];for(const O of(Y=(D=v.data)===null||D===void 0?void 0:D.Period)===null||Y===void 0?void 0:Y.AdaptationSet)if(O.contentType==="text"){const H=(J=O.Representation)===null||J===void 0?void 0:J.id,ae=new URL((N=O.Representation)===null||N===void 0?void 0:N.BaseURL,(G=v.data)===null||G===void 0?void 0:G.baseUri).toString(),F="internal",I=O.lang;Q.push({id:H,url:ae,type:F,language:I})}t.internalTextTracks.startTransitionTo(Q)}}),this.subscription.add(Ct(this.video,t.isLooped,i));const{volumeState$:h,looped$:f,playbackRateState$:m,inPiP$:g,inFullscreen$:T,pause$:A,playing$:E}=ft(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:E,pause$:A,tracks$:this.videoTracks$.pipe(w(v=>v.map(({track:b})=>b)))}),this.subscription.add(lt(this.video,t.volume,h,i)),this.subscription.add(h.subscribe(e.volume$,i)),this.subscription.add(f.subscribe(e.loopedEvent$)),this.subscription.add(Tt(this.video,t.playbackRate,m,i)),this.subscription.add(g.subscribe(e.inPiP$)),this.subscription.add(T.subscribe(e.inFullscreen$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(W.STOPPED),R(this.params.desiredState.playbackState,p.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(W.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const r=He(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,be.PLAYBACK_SHIFT);this.player.attachSource(r)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(W.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(W.PAUSED),this.video.pause()}destroy(){var e;this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(t){}ht(this.video),this.params.output.element$.next(void 0)}}var Ai=s=>{switch(s){case"mobile":return Ce.Q_144P;case"lowest":return Ce.Q_240P;case"low":return Ce.Q_360P;case"sd":case"medium":return Ce.Q_480P;case"hd":case"high":return Ce.Q_720P;case"fullhd":case"full":return Ce.Q_1080P;case"quadhd":case"quad":return Ce.Q_1440P;case"ultrahd":case"ultra":return Ce.Q_2160P}};const ln=s=>{if(s instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(s.message))throw s;return!(s instanceof DOMException&&(s.code===20||s.name==="AbortError"))};var Et=async s=>{const e=s.muted;try{await s.play()}catch(t){if(!ln(t))return!1;if(e)return console.warn(t),!1;s.muted=!0;try{await s.play()}catch(i){return ln(i)&&(s.muted=!1,console.warn(i)),!1}}return!0};function $e(){return pe()}function Io(s){return $e()-s}function cn(s){const e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=n=>i.test(n);return{resolve:(n,o,u=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let d=n.indexOf("?")>-1?"&":"?";return u&&(n+=d+"lowLat=1",d="&"),o&&(n+=d+"_rnd="+Math.floor(999999999*Math.random())),n}}}function fp(s,e,t){const i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function es(s,e,t,i){const r=window.XMLHttpRequest;let a,n,o,u=!1,d=0,l,c,h=!1,f="arraybuffer",m=7e3,g=2e3,T=()=>{if(u)return;P(l);const O=Io(l);let H;if(O<g){H=g-O,setTimeout(T,H);return}g*=2,g>m&&(g=m),n&&n.abort(),n=new r,D()};const A=O=>(a=O,Q),E=O=>(c=O,Q),v=()=>(f="json",Q),b=()=>{if(!u){if(--d>=0){T(),i&&i();return}u=!0,c&&c(),t&&t()}},$=O=>(h=O,Q),D=()=>{l=$e(),n=new r,n.open("get",s);let O=0,H,ae=0;const F=()=>(P(l),Math.max(l,Math.max(H||0,ae||0)));if(a&&n.addEventListener("progress",I=>{const M=$e();a.updateChunk&&I.loaded>O&&(a.updateChunk(F(),I.loaded-O),O=I.loaded,H=M)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>b())),n.addEventListener("load",()=>{if(u)return;P(n);const I=n.status;if(I>=200&&I<300){if(n.response.byteLength&&a){const M=n.response.byteLength-O;M&&a.updateChunk&&a.updateChunk(F(),M)}c&&c(),n&&e(n.response)}else b()}),n.addEventListener("error",()=>{b()}),h){const I=()=>{P(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ae=$e(),n.removeEventListener("readystatechange",I))};n.addEventListener("readystatechange",I)}return n.responseType=f,n.send(),Q},Q={withBitrateReporting:A,withParallel:$,withJSONResponse:v,withRetryCount:O=>(d=O,Q),withRetryInterval:(O,H)=>(_(O)&&(g=O),_(H)&&(m=H),Q),withTimeout:O=>(o=O,Q),withFinally:E,send:D,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return Q}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,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-vp;if(t-e>mp){let i=0,r=0;for(;this.intervals.length>0;){const a=this.intervals[0];if(a.end<=t)i+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{const n=t-a.start,o=a.end-a.start;i+=n;const u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&i>0){const a=r*8/(i/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>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,i,r,a){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const i=$e(),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=$e()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=es(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=$e()}_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=$e();if(Object.keys(this.activeRequests).length>=e)return!1;const i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){const a={};return a.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Vi=1e4,Hi=3,bp=300,yp=2e3,Tp=6e4,Ep=10,$p=1,Ap=500;class kp{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=cn(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=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 i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)===null||i===void 0?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,i=t.buffered.length;let r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let i,r,a;const n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a));return r||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||_(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const n=()=>{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(Hi,Vi,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,playerCallback:r}=this.params;let a=!1,n=null,o=null,u=null,d=null,l=!1;const c=()=>{const b=a&&(!l||l===this.rep);return b||t("Not running!"),b},h=(b,$,D)=>{u&&u.abort(),u=es(this.urlResolver.resolve(b,!1),$,D,()=>this._retryCallback()).withTimeout(Vi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Hi).withFinally(()=>{u=null}).send()},f=(b,$,D)=>{P(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(b,!1),$,D,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=b=>{const $=i.playbackRate;i.playbackRate!==b&&(t(`Playback rate switch: ${$}=>${b}`),i.playbackRate=b)},g=b=>{this.lowLatency=b,t(`lowLatency changed to ${b}`),T()},T=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let b=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}const D=$e()-1e4;let Y=0;for(let N=0;N<this.bufferStates.length;N++){const G=this.bufferStates[N];b=Math.min(b,G.buf),G.ts<D&&Y++}this.bufferStates.splice(0,Y),t(`update playback rate; minBuffer=${b} drop=${Y} jitter=${this.sourceJitter}`);let J=b-$p;this.sourceJitter>=0?J-=this.sourceJitter/2:this.sourceJitter-=1,J>3?m(1.15):J>1?m(1.1):J>.3?m(1.05):m(1)}},A=b=>{let $;const D=()=>$&&$.start?$.start.length:0,Y=I=>$.start[I]/1e3,J=I=>$.dur[I]/1e3,N=I=>$.fragIndex+I,G=(I,M)=>({chunkIdx:N(I),startTS:Y(I),dur:J(I),discontinuity:M}),Q=()=>{let I=0;if($&&$.dur){let M=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,X=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,he=M;this.sourceJitter>1&&(he+=this.sourceJitter-1);let ve=$.dur.length-1;for(;ve>=0&&(he-=$.dur[ve],!(he<=0));--ve);I=Math.min(ve,$.dur.length-1-X),I=Math.max(I,0)}return G(I,!0)},O=I=>{const M=D();if(!(M<=0)){if(_(I)){for(let X=0;X<M;X++)if(Y(X)>I)return G(X)}return Q()}},H=I=>{const M=D(),X=I?I.chunkIdx+1:0,he=X-$.fragIndex;if(!(M<=0)){if(!I||he<0||he-M>Ep)return t(`Resync: offset=${he} bChunks=${M} chunk=`+JSON.stringify(I)),Q();if(!(he>=M))return G(X-$.fragIndex,!1)}},ae=(I,M,X)=>{d&&d.abort(),d=es(this.urlResolver.resolve(I,!0,this.lowLatency),M,X,()=>this._retryCallback()).withTimeout(Vi).withRetryCount(Hi).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(I,M)=>{ae(b,X=>{if(!c())return;$=X;const he=!!$.lowLatency;he!==this.lowLatency&&g(he);let ve=0;for(let _e=0;_e<$.dur.length;++_e)ve+=$.dur[_e];ve>0&&(P(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ve/$.dur.length)),r({name:"index",zeroTime:$.zeroTime,shiftDuration:$.shiftDuration}),this.sourceJitter=$.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,$.jitter/1e3)):1,I(O(M))},()=>this._handleNetworkError())},nextChunk:H}},E=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),P(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:b=>{const{videoElement:$,logger:D}=this.params;let Y=A(e.jidxUrl),J,N,G,Q,O=0,H,ae,F;const I=()=>{H&&(clearTimeout(H),H=void 0);const Z=Math.max(Ap,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ae=O+Z,xe=$e(),Pe=Math.min(1e4,Ae-xe);O=xe;const Le=()=>{d||c()&&Y.seek(()=>{c()&&(O=$e(),M(),I())})};Pe>0?H=window.setTimeout(()=>{this.paused?I():Le()},Pe):Le()},M=()=>{let Z;for(;Z=Y.nextChunk(Q);)Q=Z,je(Z);const Ae=Y.nextChunk(G);if(Ae){if(G&&Ae.discontinuity){D("Detected discontinuity; restarting playback"),this.paused?I():(E(),this._initPlayerWith(e));return}_e(Ae)}else I()},X=(Z,Ae)=>{if(!c()||!this.sourceBuffer)return;let xe,Pe,Le;const Ot=$t=>{window.setTimeout(()=>{c()&&X(Z,Ae)},$t)};if(this.sourceBuffer.updating)D("Source buffer is updating; delaying appendBuffer"),Ot(100);else{const $t=$e(),Bt=$.currentTime;!this.paused&&$.buffered.length>1&&ae===Bt&&$t-F>500&&(D("Stall suspected; trying to fix"),this._fixupStall()),ae!==Bt&&(ae=Bt,F=$t);const Mt=this._getBufferSizeSec();if(Mt>30)D(`Buffered ${Mt} seconds; delaying appendBuffer`),Ot(2e3);else try{this.sourceBuffer.appendBuffer(Z),this.videoPlayStarted?(this.bufferStates.push({ts:$t,buf:Mt}),T(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ae&&Ae()}catch(wi){if(wi.name==="QuotaExceededError")D("QuotaExceededError; delaying appendBuffer"),Le=this.sourceBuffer.buffered.length,Le!==0&&(xe=this.sourceBuffer.buffered.start(0),Pe=Bt,Pe-xe>4&&this.sourceBuffer.remove(xe,Pe-3)),Ot(1e3);else throw wi}}},he=()=>{N&&J&&(D([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(G)]),X(N,function(){N=null,M()}))},ve=Z=>e.fragUrlTemplate.replace("%%id%%",Z.chunkIdx),_e=Z=>{c()&&f(ve(Z),(Ae,xe)=>{if(c()){if(xe/=1e3,N=Ae,G=Z,n=Z.startTS,xe){const Pe=Math.min(10,Z.dur/xe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Pe:Pe}he()}},()=>this._handleNetworkError())},je=Z=>{c()&&(P(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ve(Z),!1)))},pt=Z=>{c()&&(e.cachedHeader=Z,X(Z,()=>{J=!0,he()}))};a=!0,Y.seek(Z=>{if(c()){if(O=$e(),!Z){I();return}Q=Z,!te(b)||Z.startTS>b?_e(Z):(G=Z,M())}},b),e.cachedHeader?pt(e.cachedHeader):h(e.headerUrl,pt,()=>this._handleNetworkError())},stop:E,getTimestampSec:()=>n},l}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),_(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,P(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return _(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let h,f,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(f=this._getBufferSizeSec(),m=c/this.bitrate,f>10&&m>.8||f>15&&m>.5||f>20&&m>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},a=(()=>({updateChunk:(h,f)=>{const m=$e();if(this.chunkRateEstimator.addInterval(h,m,f)){const T=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:m-h,speed:T}),!0}},get:()=>{const h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}}))();let n=-1/0,o,u=!0;const d=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&Io(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,h)=>{const f=a.updateChunk(c,h);return f&&d(),f},notifySwitch:c=>{const h=$e();c<o&&(n=h),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=es(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Vi).withRetryCount(Hi).withRetryInterval(bp,yp).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;Et(t).then(i=>{i||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:r}=this.params,a=n=>{const o=[];return n!=null&&n.length?(n.forEach((u,d)=>{u.video&&r.canPlayType(u.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(u.codecs)&&(u.index=d,o.push(u))}),o.sort(function(u,d){return u.video&&d.video?d.video.height-u.video.height:d.bitrate-u.bitrate}),o):(this.params.playerCallback({name:"error",type:"partial_metadata"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Tp))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var j;(function(s){s.STOPPED="stopped",s.MANIFEST_READY="manifest_ready",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(j||(j={}));const wp=[j.PAUSED,j.PLAYING,j.READY],_p=[j.PAUSED,j.PLAYING,j.READY];class Pp{constructor(e){this.subscription=new re,this.videoState=new ue(j.STOPPED),this.representations$=new S([]),this.textTracksManager=new Ze,this.droppedFramesManager=new Ts,this.maxSeekBackTime$=new S(1/0),this.zeroTime$=new S(void 0),this.liveOffset=new ys,this._dashCb=r=>{var a,n,o,u;switch(r.name){case"buffering":{const d=r.isBuffering;this.params.output.isBuffering$.next(d);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:C.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const d=r.manifest,l=[];for(const c of d){const h=(a=c.name)!==null&&a!==void 0?a:c.index.toString(10),f=(n=Ai(c.name))!==null&&n!==void 0?n:Rt(c.video),m=c.bitrate/1e3,g={...c.video};if(!f)continue;const T={id:h,quality:f,bitrate:m,size:g};l.push({track:T,representation:c})}this.representations$.next(l),this.params.output.availableVideoTracks$.next(l.map(({track:c})=>c)),((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===j.MANIFEST_READY&&this.videoState.setState(j.MANIFEST_READY);break}case"qualitySwitch":{const d=r.quality,l=(u=this.representations$.getValue().find(({representation:c})=>c===d))===null||u===void 0?void 0:u.track;this.params.output.hostname$.next(new URL(d.headerUrl,this.params.source.url).hostname),_(l)&&this.params.output.currentVideoTrack$.next(l);break}case"bandwidth":{const{size:d,duration:l}=r;this.params.dependencies.throughputEstimator.addRawSpeed(d,l);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration||0),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{const r=this.videoState.getState(),a=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${r}; videoTransition: ${JSON.stringify(a)}; desiredPlaybackState: ${n}; seekState: ${JSON.stringify(u)};`}),n===p.STOPPED){r!==j.STOPPED&&(this.videoState.startTransitionTo(j.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(j.STOPPED));return}if(a)return;const d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(_p.includes(r)&&(d||l)){this.prepare();return}if((o==null?void 0:o.to)!==p.PAUSED&&u.state===z.Requested&&wp.includes(r)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(r){case j.STOPPED:this.videoState.startTransitionTo(j.MANIFEST_READY),this.dash.attachSource(He(this.params.source.url));return;case j.MANIFEST_READY:this.videoState.startTransitionTo(j.READY),this.prepare();break;case j.READY:if(n===p.PAUSED)this.videoState.setState(j.PAUSED);else if(n===p.PLAYING){this.videoState.startTransitionTo(j.PLAYING);const c=o==null?void 0:o.from;c&&c===p.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(j.PAUSED)})}return;case j.PLAYING:n===p.PAUSED&&(this.videoState.startTransitionTo(j.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case j.PAUSED:if(n===p.PLAYING)if(this.videoState.startTransitionTo(j.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(j.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.dash.reinit(He(this.params.source.url,c))}return;default:return V(r)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:C.WTF,message:"DashLiveProvider internal logic error",thrown:r})};U(this.videoState.stateChangeStarted$.pipe(w(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(w(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=ct(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(we(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=ft(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.representations$.pipe(w(r=>r.map(({track:a})=>a)))}),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===j.READY&&this.videoState.setState(j.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(j.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===z.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(j.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(fe(),w(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Ie({zeroTime:this.zeroTime$.pipe(se(_)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Ct(this.video,this.params.desiredState.isLooped,t)).add(lt(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Tt(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{const a=r&&pd(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case j.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(p.STOPPED);break;case j.MANIFEST_READY:case j.READY:((a=this.params.desiredState.playbackState.getTransition())===null||a===void 0?void 0:a.to)===p.READY&&this.params.desiredState.playbackState.setState(p.READY);break;case j.PAUSED:this.params.desiredState.playbackState.setState(p.PAUSED);break;case j.PLAYING:this.params.desiredState.playbackState.setState(p.PLAYING);break;default:return V(r.to)}},t)).add(U(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,ke(["init"])).pipe(Me(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),ht(this.video)}createLiveDashPlayer(){const e=new kp({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,i,r,a,n;const o=this.representations$.getValue(),u=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),d=(r=(i=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||i===void 0?void 0:i.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),l=!d&&_(u)?u:(a=ti(o.map(({track:m})=>m),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}))===null||a===void 0?void 0:a.id,c=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.videoTrack.getState(),f=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((c&&l||l!==h)&&this.setVideoTrack(l),f&&this.setAutoQuality(d),c||f||l!==h){const m=(n=o.find(({track:g})=>g.id===l))===null||n===void 0?void 0:n.representation;P(m,"Representations missing"),this.dash.startPlay(m,d)}}setVideoTrack(e){var t;const i=(t=this.representations$.getValue().find(({track:r})=>r.id===e))===null||t===void 0?void 0:t.representation;P(i,`No such representation ${e}`),this.dash.switchByName(i.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t===p.PAUSED&&i===j.PAUSED,a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(He(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}}var xo=s=>{var e,t;const i=s.get("X-Delivery-Type"),r=s.get("X-Reused"),a=i===null?gi.HTTP1:(e=i)!==null&&e!==void 0?e:void 0,n=r===null?void 0:(t={1:!0,0:!1}[r])!==null&&t!==void 0?t:void 0;return{type:a,reused:n}},bt=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){const r=s.start(i)*1e3,a=s.end(i)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};const Dp=s=>{const e=document.createElement("a");return e.href=s,e.origin},Rp=s=>{const e=document.createElement("a");return e.href=s,e.host};class Lo{constructor(e,t=[],i,r,a,n){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=i,this._progressCb=r,this._headersCb=a,this._errorCb=n,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{var t,i,r,a,n,o,u,d;if(this._xhr){if(((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(i=this._errorCb)===null||i===void 0||i.call(this,`Http${(r=this._xhr)===null||r===void 0?void 0:r.status}`,`XHR response code ${(a=this._xhr)===null||a===void 0?void 0:a.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const l=Qt(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(c=>c.split(":").map(h=>h.trim())));(n=this._headersCb)===null||n===void 0||n.call(this,new Headers(l))}else this._xhr.readyState===4?(o=this._completeCb)===null||o===void 0||o.call(this,this._xhr.response):this._xhr.readyState===3&&((u=this._progressCb)===null||u===void 0||u.call(this,this._xhr.response))}catch(l){throw(d=this._errorCb)===null||d===void 0||d.call(this,"XHR2CallbackError",`xhr2 callback threw ${String(l)}`,l),l}}},this._xhr.onerror=()=>{var t;(t=this._xhr)===null||t===void 0||t.abort(),this._retryTimeout=window.setTimeout(()=>{var i;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(i=this._errorCb)===null||i===void 0||i.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let r;this._failoverIndex>=this._failoverHosts.length?(r=this._url,this._failoverIndex=0):(r=this._url.replace(Rp(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",r,!0),this._xhr.send(null)}},500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class os{constructor(e){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t==null||t()}catch(i){if(i.name==="QuotaExceededError"){this._isFull=!0;const r=this._sourceBuffer.buffered;let a=0;for(let n=0,o=r.length;n<o;n++)a+=r.end(n)-r.start(n);a&&(this._maxBufferDuration=Math.round(a))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",i),i}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,i,r,a,n,o){this.abort(()=>{let u=0;const d=Date.now();let l=0,c=0,h=0;const f=g=>{r(os._str2ua(g.substr(u))),u=g.length};let m=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(m=Kt(m)),this._lastXhr=new Lo(m,e.failoverHosts,g=>{this._lastXhr=void 0,f(g);const T=Date.now()-d;this._params.onBandwidthChange({size:g.length,duration:T,speed:8*g.length/(T/1e3)}),this._onDashCallback("loading",{size:g.length,done:!0}),a==null||a()},g=>{if(g.length-u>o&&f(g),c===0){c=Date.now();return}h=g.length-l;const T=Date.now()-c;h>=100*1024&&T>=1e3&&(this._params.onBandwidthChange({size:h,duration:T,speed:8*h/(T/1e3)}),h=0,l=g.length,c=Date.now()),this._onDashCallback("loading",{size:g.length,done:!1})},n,(g,T,A)=>this._params.onError(g,T,A))})}abort(e){var t;(t=this._lastXhr)===null||t===void 0||t.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e==null||e()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(i){throw this._params.onError("SourceBuffer","Source Buffer update error",i),i}};return this._sourceBuffer.addEventListener("updateend",t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener("updateend",e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=os._concatUint8(this._appendPromiseUint8Array,e):(this._appendPromiseUint8Array=e,this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,()=>{this._appendPromiseUint8Array=void 0,t&&this._sbUpdatingWatch(t)})}))}endOfStream(){this._mediaSource.readyState==="open"&&this._sbUpdatingWatch(()=>this._mediaSource.endOfStream())}static _concatUint8(e,t){const i=new Uint8Array(e.byteLength+t.byteLength);return i.set(e,0),i.set(t,e.byteLength),i}static _str2ua(e){const t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}remove(e,t){this._sbUpdatingWatch(()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(e,t),this._maxBufferDuration=Number.POSITIVE_INFINITY})}destroy(){var e;(e=this._lastXhr)===null||e===void 0||e.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._mediaSource.readyState==="open"&&this._sourceBuffer.abort()}}class Ip{constructor(e){var t;this._representations=[],this._appendVector={},this._cachingPaused=!1,this._duration=0,this.STREAM_END_THRESHOLD=1,this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=(t=e.onDashCallback)!==null&&t!==void 0?t:()=>{},this._config=e.config}_parseDurationFromISO8601(e){const t=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/,i=(o,u)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*u},r=t.exec(e),a=(r==null?void 0:r[1])==="-"?-1:1,n={years:i(r==null?void 0:r[2],a),months:i(r==null?void 0:r[3],a),weeks:i(r==null?void 0:r[4],a),days:i(r==null?void 0:r[5],a),hours:i(r==null?void 0:r[6],a),minutes:i(r==null?void 0:r[7],a),seconds:i(r==null?void 0:r[8],a)};return n.hours*3600+n.minutes*60+n.seconds}getRepresentations(){return this._representations}attachSource(e,t){let i=e;this._config.REQUEST_QUIC&&(i=Kt(i)),new Lo(i,t,r=>{this.attachManifest(r,t,Dp(i))},void 0,r=>{this._params.onResponseHeaders(r)},(r,a,n)=>this._params.onError(r,a,n))}attachManifest(e,t,i){const a=new DOMParser().parseFromString(e,"text/xml").documentElement,n=(d,l)=>{const c=d.attributes.getNamedItem(l);return c?c.value:null};this._duration=this._parseDurationFromISO8601(String(n(a,"mediaPresentationDuration")));const o=[],u=[];if(Array.prototype.forEach.call(a.getElementsByTagName("Representation"),d=>{var l,c,h,f,m,g,T,A,E,v,b,$,D,Y,J,N,G,Q,O;const H=d.getElementsByTagName("SegmentBase")[0],ae=H&&n(H,"indexRange").split("-"),F=H&&H.getElementsByTagName("Initialization")[0],I=F&&n(F,"range").split("-");if(!I||!ae){const je=d.parentElement;if((je==null?void 0:je.getAttribute("contentType"))==="text"){const pt=(l=d.getAttribute("id"))!==null&&l!==void 0?l:void 0,Z=(i?i+"/":"")+((m=(f=(h=(c=d.getElementsByTagName("BaseURL"))===null||c===void 0?void 0:c[0])===null||h===void 0?void 0:h.childNodes)===null||f===void 0?void 0:f[0])===null||m===void 0?void 0:m.data),Ae=(g=je.getAttribute("lang"))!==null&&g!==void 0?g:void 0;Z&&u.push({id:pt,url:Z,language:Ae})}return}const M=.1,X=Number((T=d.attributes.getNamedItem("bandwidth"))===null||T===void 0?void 0:T.value),he=(i?i+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ve;const _e=(E=(A=d.attributes.getNamedItem("frameRate"))===null||A===void 0?void 0:A.value)!==null&&E!==void 0?E:void 0;ve=_e?Xr(_e):void 0,o.push({width:Number((v=d.attributes.getNamedItem("width"))===null||v===void 0?void 0:v.value),height:Number((b=d.attributes.getNamedItem("height"))===null||b===void 0?void 0:b.value),bandwidth:X,baseURL:he,failoverHosts:t,indexFrom:Number(ae[0]),indexTo:Number(ae[1]),initFrom:Number(I[0]),initTo:Number(I[1]),codecs:(D=($=d.attributes.getNamedItem("codecs"))===null||$===void 0?void 0:$.value)!==null&&D!==void 0?D:void 0,mimeType:(J=(Y=d.attributes.getNamedItem("mimeType"))===null||Y===void 0?void 0:Y.value)!==null&&J!==void 0?J:void 0,fps:ve,bufferSize:M*X/8,bufferLength:M,name:(G=(N=d.attributes.getNamedItem("okQuality"))===null||N===void 0?void 0:N.value)!==null&&G!==void 0?G:void 0,id:(O=(Q=d.attributes.getNamedItem("id"))===null||Q===void 0?void 0:Q.value)!==null&&O!==void 0?O:void 0})}),o.length)this._representations=o;else{this._onDashCallback("error");return}u.forEach(({id:d,language:l,url:c})=>{const h=document.createElement("track");c&&h.setAttribute("src",c),d&&h.setAttribute("id",d),l&&h.setAttribute("srclang",l),this._video.appendChild(h)}),this._representations.sort((d,l)=>l.bandwidth-d.bandwidth),this._params.onManifestReady({representations:this._representations,textRepresentations:u})}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const i=Date.now();this._stream.load(e,e.initFrom,e.indexTo,r=>{let a=e.initTo-e.initFrom+1;if(!r.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(r.buffer,0,a);const n=new DataView(r.buffer);a+=12;const o=n.getUint32(a+4,!1);a+=8;let u=n.getUint32(a,!1),d=n.getUint32(a+4,!1)+(e.indexTo+1);a+=8;const l=n.getUint16(a+2,!1);a+=4,e.refs=[];for(let h=0;h<l;h+=1){const f=d+(n.getUint32(a,!1)&2147483647),m=u+n.getUint32(a+4,!1);a+=12,e.refs.push({fromTime:u/o,toTime:m/o,fromOffset:d,toOffset:f-1}),d=f,u=m}const c=e.refs[e.refs.length-1];c.toTime-c.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,r=>{this._params.onResponseHeaders(r),this._params.onIdxRequestPing(Date.now()-i)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const i=new t;let r,a;const n=()=>{const d=this._findRef(this._video.currentTime);if(!d||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const f=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),f)}const l=this._appendVector[String(d.fromTime)];l!==r&&(r=l,this._params.onRepresentationPlay(l));let c;if(this._findRef(d.toTime)){const f=this._buffer.getByTime(this._video.currentTime);if(!f){this._onDashCallback("buffering");return}c=f.to-this._video.currentTime,c<e.bufferLength&&(this._onDashCallback("buffering"),a!==f.to&&(a=f.to,window.setTimeout(()=>{try{const m=this._buffer.getNextWithGap(f);m&&(this._video.currentTime=m.from)}catch(m){throw this._params.onError("GapSyncError",`Seek Error ${String(m)}`,m),m}},c*1e3)))}},o=()=>{this._loopTimeout=window.setTimeout(()=>{try{n()}catch(d){throw this._params.onError("LoopError",`Dash Loop exception ${String(d)}`,d),d}o()},250)},u=()=>{if(!this._stream)try{const d=i.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new os({mediaSource:i,sourceBuffer:d,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(d){throw this._params.onError("DashSourceOpen",`Source open exception ${String(d)}`,d),d}this._loadInitAndSidx(e),i.duration||(i.duration=this._duration),this._loopTimeout||o(),i.removeEventListener("sourceopen",u),i.removeEventListener("webkitsourceopen",u)};i.addEventListener("sourceopen",u,!1),i.addEventListener("webkitsourceopen",u,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener("waiting",()=>{const d=this._video&&this._video.played.length;d&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(d-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,i=!1,r=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const a=this._findRef(t);if(a){if(i){this._isLastRef(a)&&t>=a.toTime&&(t=a.fromTime);const n=this._findRef(this._video.currentTime),o=Math.abs(this._video.currentTime-t),u=r||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||a===n||o<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=u?t:a.fromTime}this._appendVector[String(a.fromTime)]=e,this._stream.load(e,a.fromOffset,a.toOffset,(n,o)=>this._stream.append(n,o),()=>{this._lastLoadOffset=a.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},n=>this._params.onResponseHeaders(n),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const i=this._buffer.getByTime(this._video.currentTime),r=this._findRef(this._video.currentTime);if(!i||!r){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const a=.1;if(r.toTime<i.to+a){const n=this._findRef(r.toTime);n&&n.toTime<i.to+a?(this._buffer.smartRemove(r.fromTime-a,n.toTime+a,(o,u)=>this._stream.remove(o,u)),this._loadRef(e,n.toTime)):(this._buffer.smartRemove(r.fromTime-a,r.toTime+a,(o,u)=>this._stream.remove(o,u)),this._loadRef(e,r.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t){this._stream&&this._buffer.getByTime(e)?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0,t)}updateRefsForCurrentTime(){const e=this._video.currentTime;(!this._stream||te(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return;if(Array.isArray(i)&&i.length===0){this._params.onError("emptyrefs","Empty refs");return}let r;for(let a=0;a<i.length;a++){const n=i[a];if(n.fromTime<=e&&n.toTime>e)return n;n.fromTime>e&&(!r||n.fromTime<r.fromTime)&&(r=n)}if(!r){const a=i[i.length-1];if(e>a.toTime)return a}return r}_isLastRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return!1;const r=i[i.length-1];return e.fromTime===r.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const i=this._video.buffered.start(t),r=this._video.buffered.end(t);if(e>i&&e<r)return Math.round(r*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var K;(function(s){s.STOPPED="stopped",s.MANIFEST_LOADED="manifest-loaded",s.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",s.METADATA_LOADED="metadata-loaded",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(K||(K={}));const xp=[K.PAUSED,K.PLAYING];class Lp{constructor(e){this.videoState=new ue(K.STOPPED),this.subscription=new re,this.representations$=new S([]),this.currentRepresentation$=new S(void 0),this.textTracksManager=new Ze,this.droppedFramesManager=new Ts,this.elementSize$=new S(void 0),this.dashLiteEvents={idxRequestPing$:new L,responseHeaders$:new L,manifestReady$:new L,representationPlay$:new L,error$:new L},this.handleManifestReady=({representations:t,textRepresentations:i})=>{var r,a,n;const o=[];for(const u of t){const d=(a=(r=u.name)!==null&&r!==void 0?r:u.id)!==null&&a!==void 0?a:u.height.toString(10),l=(n=u.name&&Ai(u.name))!==null&&n!==void 0?n:Rt(u),c=u.bandwidth/1e3,h={width:u.width,height:u.height},f=u.fps;if(!l)continue;const m={id:d,quality:l,bitrate:c,size:h,fps:f};o.push({track:m,representation:u})}if(this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),(i==null?void 0:i.length)>0){const u=[];for(const d of i){const l=d.id||`${d.language}_${Date.now()}`;u.push({id:l,type:"internal",url:d.url||"",language:d.language,isAuto:d.isAuto})}this.params.desiredState.internalTextTracks.startTransitionTo(u)}this.videoState.setState(K.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var i;const r=(i=this.representations$.getValue().find(({representation:a})=>a===t))===null||i===void 0?void 0:i.track;r&&(this.params.output.currentVideoTrack$.next(r),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(r.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return P(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(n)};`}),r===p.STOPPED){t!==K.STOPPED&&(this.videoState.startTransitionTo(K.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(K.STOPPED),R(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(!i)switch((a==null?void 0:a.to)!==p.PAUSED&&n.state===z.Requested&&xp.includes(t)&&this.seek(n.position,n.forcePrecise),t){case K.STOPPED:this.videoState.startTransitionTo(K.MANIFEST_LOADED),this.prepare();return;case K.MANIFEST_LOADED:this.videoState.startTransitionTo(K.INITIAL_REPRESENTATION_SELECTED);return;case K.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(K.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case K.METADATA_LOADED:this.videoState.startTransitionTo(K.READY),this.dash.updateRefsForCurrentTime();return;case K.READY:r===p.READY?R(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(K.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed());return;case K.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(K.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&R(this.params.desiredState.playbackState,p.PLAYING);return;case K.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&R(this.params.desiredState.playbackState,p.PAUSED);return;default:return V(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),U(this.videoState.stateChangeStarted$.pipe(w(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(w(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=ct(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Wf(this.video),this.dash=new Ip({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:({representations:t,textRepresentations:i})=>this.dashLiteEvents.manifestReady$.next({representations:t,textRepresentations:i}),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,i,r)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:i,thrown:r,category:C.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"DashProvider",category:C.WTF,message:"DashProvider internal logic error",thrown:o})},r=()=>{const o=this.params.desiredState.autoVideoTrackSwitching.getState(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();return u?u.to:o},a=ft(this.video),n=(o,u)=>this.subscription.add(o.subscribe(u,i));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(a.seeking$.subscribe(()=>{te(this.params.desiredState.seekState.getState().state!==z.Applying)&&(this.videoState.getState()===K.PLAYING||this.videoState.getState()===K.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(Ct(this.video,t.isLooped,i)),this.subscription.add(lt(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Tt(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:a.playing$,pause$:a.pause$,tracks$:this.representations$.pipe(w(o=>o.map(({track:u})=>u)))}),n(ns(this.video),this.elementSize$),this.subscription.add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===K.READY&&this.videoState.setState(K.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(K.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED)})).add(a.playing$.subscribe(()=>{this.videoState.setState(K.PLAYING),R(this.params.desiredState.playbackState,p.PLAYING)},i)).add(a.loadedMetadata$.subscribe(()=>{this.videoState.setState(K.METADATA_LOADED)},i)).add(a.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},i)).add(this.dashLiteEvents.error$.pipe(w(({id:o,message:u,thrown:d})=>({id:`DashLite_${o}`,category:C.WTF,message:u,thrown:d}))).subscribe(this.params.output.error$)).add(U(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$,this.params.output.element$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,B(this.video,"progress")).pipe(w(()=>{var o,u,d;const l=this.currentRepresentation$.getValue(),c=this.representations$.getValue(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition(),f=this.params.desiredState.videoTrack.getState(),m=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),g=this.elementSize$.getValue(),T=r();h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to);let A;if(!T&&_(f))A=f;else{const E=bt(this.video.buffered,this.video.currentTime*1e3),v=T?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,b=Math.min(E/v,1);A=(u=ti(c.map(({track:D})=>D),{container:g,throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:b,playbackRate:this.video.playbackRate,current:(o=c.find(({representation:D})=>D===l))===null||o===void 0?void 0:o.track,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}))===null||u===void 0?void 0:u.id;const $=t.autoVideoTrackLimits.getTransition();$&&e.autoVideoTrackLimits$.next($.to)}return _(A)?(d=c.find(({track:E})=>E.id===A))===null||d===void 0?void 0:d.representation:void 0}),fe()).subscribe(this.currentRepresentation$,i)).add(Ie({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(se(o=>o.to===K.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(se(_))}).pipe(me()).subscribe(()=>this.videoState.setState(K.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(se(_),fe((o,u)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?o.height<=u.height:o===u)).subscribe(o=>{const u=bt(this.video.buffered,this.video.currentTime*1e3),d=Math.min(u/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||d<=.5||!r())&&(this.dash.setQualityByRepresentation(o,!0),this.params.output.hostname$.next(we(o.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:u,reused:d}=xo(o);this.params.output.httpConnectionType$.next(u),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(me(),Wt(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(o=>this.params.dependencies.throughputEstimator.addRawRtt(o))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,i)).add(this.dashLiteEvents.representationPlay$.pipe(se(_)).subscribe(this.handleRepresentationPlay,i)).add(U(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Me(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),ht(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return V(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){Et(this.video).then(e=>{e||(this.videoState.setState(K.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.DOM,thrown:e}))}}var Te;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(Te||(Te={}));var ds;(function(s){s.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",s.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(ds||(ds={}));var Be;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(Be||(Be={}));var ee;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(ee||(ee={}));var Jt;(function(s){s.MP4="mp4",s.WEBM="webm"})(Jt||(Jt={}));var us;(function(s){s[s.RECTANGULAR=0]="RECTANGULAR",s[s.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",s[s.CUBEMAP=2]="CUBEMAP",s[s.MESH=3]="MESH"})(us||(us={}));var le;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(le||(le={}));class hn{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;const i=this.listeners[e];for(let r=0,a=i.length;r<a;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const i=this.listeners[e.type].slice();for(let r=0,a=i.length;r<a;r++){const n=i[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}}class Co 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 Oo=class{constructor(){Object.defineProperty(this,"signal",{value:new Co,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Oo.prototype[Symbol.toStringTag]="AbortController",Co.prototype[Symbol.toStringTag]="AbortSignal");function Bo(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function Cp(s){typeof s=="function"&&(s={fetch:s});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!Bo({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(d,l){let c;l&&l.signal&&(c=l.signal,delete l.signal);const h=new t(d,l);return c&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),h},a.prototype=t.prototype);const n=e;return{fetch:(u,d)=>{const l=a&&a.prototype.isPrototypeOf(u)?u.signal:d?d.signal:void 0;if(l){let c;try{c=new DOMException("Aborted","AbortError")}catch(f){c=new Error("Aborted"),c.name="AbortError"}if(l.aborted)return Promise.reject(c);const h=new Promise((f,m)=>{l.addEventListener("abort",()=>m(c),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([h,n(u,d)])}return n(u,d)},Request:a}}const Es=Bo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Mo=Es?Cp({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,bi=Es?Mo.fetch:window.fetch;Es?Mo.Request:window.Request;const zt=Es?Oo:window.AbortController;var Lr=(s,e)=>{for(let t=0;t<s.length;t++)if(s.start(t)*1e3<=e&&s.end(t)*1e3>e)return!0;return!1};const Op=(s,e={})=>{const i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},Bp=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",fn=Bp?Op:window.requestIdleCallback;var sr,rr;let No=!1;try{No=Br().browser===Mn.Safari&&parseInt((rr=(sr=navigator.userAgent.match(/Version\/(\d+)/))===null||sr===void 0?void 0:sr[1])!==null&&rr!==void 0?rr:"",10)<16}catch(s){console.error(s)}class Mp{constructor(e){this.bufferFull$=new L,this.error$=new L,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const i=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!i),this.currentTask=null}this.queue.length&&this.pull()}catch(i){this.error$.next({id:"BufferTaskQueueUnknown",category:C.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i;No&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:i}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&i==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${i}`,category:C.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:V(t)}}}var pn=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};class et{get id(){return this.type}get size(){return this.size32}constructor(e){this.cursor=0,this.source=e,this.children=[];const t=this.readUint32();this.size32=t<=e.buffer.byteLength?t:NaN,this.type=this.readString(4),this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,e.byteOffset+this.cursor,this.size32?this.size32-8:void 0),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}readString(e,t="ascii"){const r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){const e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){const e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){const e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){const e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}}class Fo extends et{}class Np extends et{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const i=this.readString(4);this.compatibleBrands.push(i),t-=4}}}class Fp extends et{parseChildrenBoxes(){return ii(this.content)}}class Up extends et{constructor(e){super(e),this.data=this.content}}class ki extends et{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class Vp extends ki{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let i=this.readUint32();const r=i>>>31,a=i<<1>>>1,n=this.readUint32();i=this.readUint32();const o=i>>>28,u=i<<3>>>3;this.segments.push({referenceType:r,referencedSize:a,subsegmentDuration:n,SAPType:o,SAPDeltaTime:u})}}}class Hp extends et{parseChildrenBoxes(){return ii(this.content)}}class Gp extends et{parseChildrenBoxes(){return ii(this.content)}}var Dt;(function(s){s[s.MONOSCOPIC=0]="MONOSCOPIC",s[s.TOP_BOTTOM=1]="TOP_BOTTOM",s[s.LEFT_RIGHT=2]="LEFT_RIGHT",s[s.STEREO_CUSTOM=3]="STEREO_CUSTOM",s[s.RIGHT_LEFT=4]="RIGHT_LEFT"})(Dt||(Dt={}));class Yp extends ki{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=Dt.MONOSCOPIC;break;case 1:this.stereoMode=Dt.TOP_BOTTOM;break;case 2:this.stereoMode=Dt.LEFT_RIGHT;break;case 3:this.stereoMode=Dt.STEREO_CUSTOM;break;case 4:this.stereoMode=Dt.RIGHT_LEFT;break}this.cursor+=1}}class qp extends ki{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class jp extends ki{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class zp extends et{parseChildrenBoxes(){return ii(this.content)}}class Wp extends ki{constructor(e){super(e),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}}class Qp extends et{parseChildrenBoxes(){return ii(this.content)}}class Kp extends et{parseChildrenBoxes(){return ii(this.content)}}const Jp={ftyp:Np,moov:Fp,mdat:Up,sidx:Vp,trak:Hp,mdia:zp,tkhd:Wp,minf:Qp,sv3d:Gp,st3d:Yp,prhd:qp,proj:Kp,equi:jp,unknown:Fo};class Xp{createBox(e,t){const i=Jp[e];return i?new i(t):new Fo(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return $s.createBox(i,new DataView(e.buffer,e.byteOffset))}}const $s=new Xp;function fi(s,e){const t=new TextDecoder("ascii");let i=s.byteOffset,r=[];for(;i<s.byteLength;){const a=t.decode(new DataView(s.buffer,i,1));if(a===e[r.length]?r.push(a):r=[],r.length===4&&r.join("")===e){const o=new DataView(s.buffer,i-7,4).getUint32(0);return i-7+o>s.byteLength?null:$s.createBox(e,new DataView(s.buffer,i-7))}i++}return null}function Zp(s,e){const t=[];let i=0;for(;i<s.byteLength;){const r=fi(new DataView(s.buffer,s.byteOffset+i,s.byteLength-i),e);if(r)t.push(r),i+=r.size+r.source.byteOffset;else break}return t}function ii(s){const e=[];let t=0;for(;t<s.byteLength;){const i=$s.createFromView(new DataView(s.buffer,s.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const em=new TextDecoder("ascii"),tm=s=>em.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",im=s=>{const e=$s.createFromView(s);let t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=a.subsegmentDuration/e.timescale*1e3,o={status:ee.NONE,time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},sm=s=>{const e=Zp(s,"mdat");if(e.length){const t=e.reduce((i,r)=>i+r.size,0);return new DataView(s.buffer,s.byteOffset,t)}return null},rm=s=>{const e={is3dVideo:!1,stereoMode:0,projectionType:us.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(fi(s,"sv3d")){e.is3dVideo=!0;const i=fi(s,"st3d");i&&(e.stereoMode=i.stereoMode);const r=fi(s,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const a=fi(s,"equi");a&&(e.projectionData.bounds.top=a.projectionBoundsTop,e.projectionData.bounds.right=a.projectionBoundsRight,e.projectionData.bounds.bottom=a.projectionBoundsBottom,e.projectionData.bounds.left=a.projectionBoundsLeft)}return e},am={validateData:tm,parseInit:rm,getIndexRange:()=>{},parseSegments:im,parseFeedableSegmentChunk:sm};var k;(function(s){s[s.EBML=440786851]="EBML",s[s.EBMLVersion=17030]="EBMLVersion",s[s.EBMLReadVersion=17143]="EBMLReadVersion",s[s.EBMLMaxIDLength=17138]="EBMLMaxIDLength",s[s.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",s[s.DocType=17026]="DocType",s[s.DocTypeVersion=17031]="DocTypeVersion",s[s.DocTypeReadVersion=17029]="DocTypeReadVersion",s[s.Void=236]="Void",s[s.Segment=408125543]="Segment",s[s.SeekHead=290298740]="SeekHead",s[s.Seek=19899]="Seek",s[s.SeekID=21419]="SeekID",s[s.SeekPosition=21420]="SeekPosition",s[s.Info=357149030]="Info",s[s.TimestampScale=2807729]="TimestampScale",s[s.Duration=17545]="Duration",s[s.Tracks=374648427]="Tracks",s[s.TrackEntry=174]="TrackEntry",s[s.Video=224]="Video",s[s.Projection=30320]="Projection",s[s.ProjectionType=30321]="ProjectionType",s[s.ProjectionPrivate=30322]="ProjectionPrivate",s[s.Chapters=272869232]="Chapters",s[s.Cluster=524531317]="Cluster",s[s.Timestamp=231]="Timestamp",s[s.SilentTracks=22612]="SilentTracks",s[s.SilentTrackNumber=22743]="SilentTrackNumber",s[s.Position=167]="Position",s[s.PrevSize=171]="PrevSize",s[s.SimpleBlock=163]="SimpleBlock",s[s.BlockGroup=160]="BlockGroup",s[s.EncryptedBlock=175]="EncryptedBlock",s[s.Attachments=423732329]="Attachments",s[s.Tags=307544935]="Tags",s[s.Cues=475249515]="Cues",s[s.CuePoint=187]="CuePoint",s[s.CueTime=179]="CueTime",s[s.CueTrackPositions=183]="CueTrackPositions",s[s.CueTrack=247]="CueTrack",s[s.CueClusterPosition=241]="CueClusterPosition",s[s.CueRelativePosition=240]="CueRelativePosition",s[s.CueDuration=178]="CueDuration",s[s.CueBlockNumber=21368]="CueBlockNumber",s[s.CueCodecState=234]="CueCodecState",s[s.CueReference=219]="CueReference",s[s.CueRefTime=150]="CueRefTime"})(k||(k={}));var x;(function(s){s.SignedInteger="int",s.UnsignedInteger="uint",s.Float="float",s.String="string",s.UTF8="utf8",s.Date="date",s.Master="master",s.Binary="binary"})(x||(x={}));const mn={[k.EBML]:{type:x.Master},[k.EBMLVersion]:{type:x.UnsignedInteger},[k.EBMLReadVersion]:{type:x.UnsignedInteger},[k.EBMLMaxIDLength]:{type:x.UnsignedInteger},[k.EBMLMaxSizeLength]:{type:x.UnsignedInteger},[k.DocType]:{type:x.String},[k.DocTypeVersion]:{type:x.UnsignedInteger},[k.DocTypeReadVersion]:{type:x.UnsignedInteger},[k.Void]:{type:x.Binary},[k.Segment]:{type:x.Master},[k.SeekHead]:{type:x.Master},[k.Seek]:{type:x.Master},[k.SeekID]:{type:x.Binary},[k.SeekPosition]:{type:x.UnsignedInteger},[k.Info]:{type:x.Master},[k.TimestampScale]:{type:x.UnsignedInteger},[k.Duration]:{type:x.Float},[k.Tracks]:{type:x.Master},[k.TrackEntry]:{type:x.Master},[k.Video]:{type:x.Master},[k.Projection]:{type:x.Master},[k.ProjectionType]:{type:x.UnsignedInteger},[k.ProjectionPrivate]:{type:x.Master},[k.Chapters]:{type:x.Master},[k.Cluster]:{type:x.Master},[k.Timestamp]:{type:x.UnsignedInteger},[k.SilentTracks]:{type:x.Master},[k.SilentTrackNumber]:{type:x.UnsignedInteger},[k.Position]:{type:x.UnsignedInteger},[k.PrevSize]:{type:x.UnsignedInteger},[k.SimpleBlock]:{type:x.Binary},[k.BlockGroup]:{type:x.Master},[k.EncryptedBlock]:{type:x.Binary},[k.Attachments]:{type:x.Master},[k.Tags]:{type:x.Master},[k.Cues]:{type:x.Master},[k.CuePoint]:{type:x.Master},[k.CueTime]:{type:x.UnsignedInteger},[k.CueTrackPositions]:{type:x.Master},[k.CueTrack]:{type:x.UnsignedInteger},[k.CueClusterPosition]:{type:x.UnsignedInteger},[k.CueRelativePosition]:{type:x.UnsignedInteger},[k.CueDuration]:{type:x.UnsignedInteger},[k.CueBlockNumber]:{type:x.UnsignedInteger},[k.CueCodecState]:{type:x.UnsignedInteger},[k.CueReference]:{type:x.Master},[k.CueRefTime]:{type:x.UnsignedInteger}},Uo=s=>{const e=s.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=ls(s,t),r=i in mn,a=r?mn[i].type:x.Binary,n=s.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const u=new DataView(s.buffer,s.byteOffset+t+1,o-1),d=n&255>>o,l=ls(u),c=d*2**((o-1)*8)+l,h=t+o;let f;return h+c>s.byteLength?f=new DataView(s.buffer,s.byteOffset+h):f=new DataView(s.buffer,s.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:f,valueSize:c}},ls=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{const t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Je=(s,e)=>{switch(e){case x.SignedInteger:return s.getInt8(0);case x.UnsignedInteger:return ls(s);case x.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case x.String:return new TextDecoder("ascii").decode(s);case x.UTF8:return new TextDecoder("utf-8").decode(s);case x.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case x.Master:return s;case x.Binary:return s;default:V(e)}},Xt=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=Uo(i);if(!e(r))return;r.type===x.Master&&Xt(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},nm=s=>{if(s.getUint32(0)!==k.EBML)return!1;let e,t,i;const r=Uo(s);return Xt(r.value,({tag:a,type:n,value:o})=>(a===k.EBMLReadVersion?e=Je(o,n):a===k.DocType?t=Je(o,n):a===k.DocTypeReadVersion&&(i=Je(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Vo=[k.Info,k.SeekHead,k.Tracks,k.TrackEntry,k.Video,k.Projection,k.ProjectionType,k.ProjectionPrivate,k.Chapters,k.Cluster,k.Cues,k.Attachments,k.Tags],om=[k.Timestamp,k.SilentTracks,k.SilentTrackNumber,k.Position,k.PrevSize,k.SimpleBlock,k.BlockGroup,k.EncryptedBlock],dm=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,d,l=!1;const c=0;return Xt(s,({tag:h,type:f,value:m,valueSize:g})=>{if(h===k.SeekID){const T=Je(m,f);d=ls(T)}else h!==k.SeekPosition&&(d=void 0);return h===k.Segment?(e=m.byteOffset,t=m.byteOffset+g):h===k.Info?a=!0:h===k.SeekHead?n=!0:h===k.TimestampScale?i=Je(m,f):h===k.Duration?r=Je(m,f):h===k.SeekPosition&&d===k.Cues?u=Je(m,f):h===k.Tracks?Xt(m,({tag:T,type:A,value:E})=>T===k.ProjectionType?(l=Je(E,A)===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"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:l,stereoMode:c,projectionType:us.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},um=s=>{if(te(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},lm=(s,e)=>{let t=!1,i=!1;const r=o=>_(o.time)&&_(o.position),a=[];let n;return Xt(s,({tag:o,type:u,value:d})=>{switch(o){case k.Cues:t=!0;break;case k.CuePoint:n&&r(n)&&a.push(n),n={};break;case k.CueTime:n&&(n.time=Je(d,u));break;case k.CueTrackPositions:break;case k.CueClusterPosition:n&&(n.position=Je(d,u));break;default:t&&Vo.includes(o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{const{time:d,position:l}=o,c=a[u+1];return{status:ee.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}}})},cm=s=>{let e=0,t=!1;try{Xt(s,i=>i.tag===k.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):om.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[k.SimpleBlock,k.BlockGroup,k.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},hm={validateData:nm,parseInit:dm,getIndexRange:um,parseSegments:lm,parseFeedableSegmentChunk:cm},Ho=1e4,fm=3e4,pm=5e3,mm=Ho,vm=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a})=>{var n;const o=(n=a?Ai(a):void 0)!==null&&n!==void 0?n:Rt({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r}},gm=({id:s,bitrate:e})=>({id:s,bitrate:e}),Sm=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=Qe(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:Qe(s,-1)},bm=({id:s,lang:e,url:t,isAuto:i})=>({id:s,url:t,isAuto:i,type:"internal",language:e}),Gi=s=>{const e=[];let t=0,i=s.length-1;for(;t<Ho&&i>=0;)e.unshift(s[i]),t+=s[i].time.to-s[i].time.from,i--;return e};class vn{constructor(e,t,i,r,{fetcher:a,tuning:n,getCurrentPosition:o,compatibilityMode:u=!1,manifest:d}){switch(this.onLastSegment$=new S(!1),this.fullyBuffered$=new S(!1),this.playingRepresentation$=new S(void 0),this.playingRepresentationInit$=new S(void 0),this.error$=new L,this.gaps=[],this.isSeekingLive=!1,this.subscription=new re,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.startWith=Re(this.destroyAbortController.signal,async function*(l){const c=this.representations.get(l);P(c,`Cannot find representation ${l}`),this.playingRepresentationId=l,this.downloadingRepresentationId=l,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${c.mime}; codecs="${c.codecs}"`),this.sourceBufferTaskQueue=new Mp(this.sourceBuffer),this.subscription.add(B(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},g=>this.error$.next({id:"SegmentEjection",category:C.WTF,message:"Error when trying to clear segments ejected by browser",thrown:g}))),this.subscription.add(B(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:C.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(g=>{if(!this.sourceBuffer)return;const T=Math.min(this.bufferLimit,pn(this.sourceBuffer.buffered)*.8);this.bufferLimit=T,this.pruneBuffer(this.getCurrentPosition(),g)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(g=>this.error$.next(g))),yield this.loadInit(c,"high",!0);const h=this.initData.get(c.id),f=this.segments.get(c.id),m=this.parsedInitData.get(c.id);P(h,"No init buffer for starting representation"),P(f,"No segments for starting representation"),h instanceof ArrayBuffer&&(this.searchGaps(f,c),yield this.sourceBufferTaskQueue.append(h,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(m))}.bind(this)),this.switchTo=Re(this.destroyAbortController.signal,async function*(l){if(l===this.downloadingRepresentationId||l===this.switchingToRepresentationId)return;this.switchingToRepresentationId=l;const c=this.representations.get(l);P(c,`No such representation ${l}`);let h=this.segments.get(l),f=this.initData.get(l);if(te(f)||te(h)?yield this.loadInit(c,"high",!1):f instanceof Promise&&(yield f),h=this.segments.get(l),P(h,"No segments for starting representation"),f=this.initData.get(l),!f||!(f instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=l,this.abort(),yield this.sourceBufferTaskQueue.append(f,this.downloadAbortController.signal);const m=this.getCurrentPosition();_(m)&&(this.searchGaps(h,c),this.maintain(m))}.bind(this)),this.seekLive=Re(this.destroyAbortController.signal,async function*(l){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!l)return;for(const T of this.representations.keys()){const A=l.find(b=>b.id===T);A&&this.representations.set(T,A);const E=this.representations.get(T);if(!E)return;const v=Gi(E.segmentReference.segments);this.segments.set(E.id,v)}const c=this.switchingToRepresentationId?this.switchingToRepresentationId:this.downloadingRepresentationId,h=this.representations.get(c);P(h);const f=Gi(h.segmentReference.segments),m=this.initData.get(h.id);if(P(m,"No init buffer for starting representation"),P(f,"No segments for starting representation"),!(m instanceof ArrayBuffer))return;const g=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),g&&(yield this.sourceBufferTaskQueue.remove(g.from*1e3,g.to*1e3,this.destroyAbortController.signal)),this.searchGaps(f,h),yield this.sourceBufferTaskQueue.append(m,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this)),this.fetcher=a,this.tuning=n,this.compatibilityMode=u,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isLive=!!(d!=null&&d.dynamic),this.container=i,i){case Jt.MP4:this.containerParser=am;break;case Jt.WEBM:this.containerParser=hm;break;default:V(i)}this.initData=new Map(r.map(l=>[l.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(l=>[l.id,l])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new zt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(te(e)||te(this.downloadingRepresentationId)||te(this.playingRepresentationId)||te(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(P(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const r=i.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const l=bt(this.sourceBuffer.buffered,e),c=r?r.time.to+100:-1/0;r&&l>=r.time.to-e+100&&(a=c)}if(isFinite(this.bufferLimit)&&pn(this.sourceBuffer.buffered)>=this.bufferLimit){const d=bt(this.sourceBuffer.buffered,e),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<l);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{const l=Qe(o,0);l&&l.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}!this.isLive&&!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===ee.FED&&!o.length&&bt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const u=Qe(i,-1);u&&u.status===ee.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===u))}searchGaps(e,t){this.gaps=[];let i=0;for(const r of e)r.time.from-i>0&&this.gaps.push({representation:t.id,from:i,to:r.time.from}),i=r.time.to;_(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(r=>r.id===this.downloadingRepresentationId);if(!t)return;const i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var t,i,r,a;for(const n of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!n)return;const o=n.segmentReference.segments.map(c=>({...c,status:ee.NONE,size:void 0})),u=(i=this.segments.get(n.id))!==null&&i!==void 0?i:[],d=(a=(r=Qe(u,-1))===null||r===void 0?void 0:r.time.to)!==null&&a!==void 0?a:0,l=o==null?void 0:o.findIndex(c=>Math.round(d)>=Math.round(c.time.from)&&Math.round(d)<=Math.round(c.time.to));if(l===-1){this.liveUpdateSegmentIndex=0;const c=Gi(o);this.segments.set(n.id,[...c])}else{const c=o.slice(l+1);this.segments.set(n.id,[...u,...c])}}}findSegmentStartTime(e){var t,i,r;const a=(i=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&i!==void 0?i:this.playingRepresentationId;if(!a)return;const n=this.segments.get(a);if(!n)return;const o=n.find(u=>u.time.from<=e&&u.time.to>=e);return(r=o==null?void 0:o.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){const i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const r=e.findIndex(({status:c,time:{from:h,to:f}},m)=>{const g=h<=i&&f>=i,T=h>i||g||m===0&&i===0,A=Math.min(this.forwardBufferTarget,this.bufferLimit),E=this.preloadOnly&&h<=i+A||f<=i+A;return(c===ee.NONE||c===ee.PARTIALLY_EJECTED&&T&&E&&this.sourceBuffer&&!Lr(this.sourceBuffer.buffered,i))&&T&&E});if(r===-1)return[];if(t!==Be.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===ee.NONE||h.status===ee.PARTIALLY_EJECTED)u.push(h);else break}return u}async loadSegments(e,t,i="auto"){if(!e.length)return;let r,a,n=e;const{type:o}=t.segmentReference;switch(o){case Be.BYTE_RANGE:{r=t.segmentReference.url,a={from:Qe(e,0).byte.from,to:Qe(e,-1).byte.to};break}case Be.TEMPLATE:{const d=Qe(e,0);r=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:V(o)}for(const d of n)d.status=ee.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:u}=this.downloadAbortController;if(this.failedDownloads&&(await Re(u,async function*(){const d=fa(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,d))}.bind(this))(),u.aborted))for(const d of this.activeSegments)e.includes(d.segment)&&this.abortSegment(d.segment);return void this.fetcher.fetch(r,{range:a,onProgress:(d,l)=>{if(!u.aborted)try{this.onSomeDataLoaded(d,t.id,a?a.from:0,l,u)}catch(c){this.error$.next({id:"SegmentFeeding",category:C.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}},signal:u,priority:i}).then(()=>this.failedDownloads=0,d=>{if(d.name!=="AbortError"){for(const l of this.activeSegments)e.includes(l.segment)&&this.abortSegment(l.segment);this.onSegmentDownloadError(d)}})}onSegmentDownloadError(e){var t;let i=!1;const r=this.getCurrentPosition();this.sourceBuffer&&_(r)&&(i=bt((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,i||this.error$.next({id:"SegmentDownload",category:C.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,i,r,a){if(!this.activeSegments.size)return;const n=()=>{this.abort()},o=c=>{var h;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),c.segment.status=ee.FED,"size"in c.segment&&(c.segment.size=c.fedBytes);for(const f of this.representations.values())if(f.id!==t)for(const m of(h=this.segments.get(f.id))!==null&&h!==void 0?h:[])m.status===ee.FED&&m.time.from===c.segment.time.from&&m.time.to===c.segment.time.to&&(m.status=ee.NONE);this.activeSegments.delete(c),this.detectGapsWhenIdle(t,[c.segment])},u=this.representations.get(t);if(!u)return;const d=u.segmentReference.type,l=e.byteLength;for(const c of this.activeSegments){const{segment:h}=c,f=d===Be.BYTE_RANGE,m=f?h.byte.to-h.byte.from+1:l;if(c.representationId!==t||!(!f||h.byte.from>=i&&h.byte.to<i+e.byteLength))continue;if(a.aborted){n();continue}const T=f?h.byte.from-i:0,A=f?h.byte.to-i:e.byteLength,E=T<r,v=A<=r;if(h.status===ee.DOWNLOADING&&E&&v){h.status=ee.DOWNLOADED,this.activeSegments.delete(c);const b=new DataView(e.buffer,e.byteOffset+T,m);this.sourceBufferTaskQueue.append(b,a).then($=>$&&!a.aborted?o(c):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&E&&(c.loadedBytes=Math.min(m,r-T),c.loadedBytes>c.feedingBytes)){const b=new DataView(e.buffer,e.byteOffset+T+c.feedingBytes,c.loadedBytes-c.feedingBytes),$=c.loadedBytes===m?b:this.containerParser.parseFeedableSegmentChunk(b);$!=null&&$.byteLength&&(h.status=ee.PARTIALLY_FED,c.feedingBytes+=$.byteLength,this.sourceBufferTaskQueue.append($,a).then(D=>{if(a.aborted)n();else if(D)c.fedBytes+=$.byteLength,c.fedBytes===m&&o(c);else{if(c.feedingBytes<m)return;n()}}))}}}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===ee.PARTIALLY_FED||e.status===ee.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=ee.NONE),e.status=ee.PARTIALLY_EJECTED):e.status=ee.NONE;for(const i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,a]of this.initData.entries()){const n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=fn(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Re(this.destroyAbortController.signal,async function*(){const o=fa(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),this.segments.set(e.id,this.isLive?Gi(l):l),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:C.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||te(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,n=-1/0,o=!1;const u=d=>{var l;a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const c="size"in d?(l=d.size)!==null&&l!==void 0?l:0:d.byte.to-d.byte.from;r+=c};for(const d of this.segments.values())for(const l of d){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;l.status===ee.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===ee.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===ee.NONE&&Math.round(f.time.from)<=Math.round(l)&&Math.round(f.time.to)>=Math.round(c)){a=l,n=c;break}}if(o=isFinite(a)&&isFinite(n),!o&&i){r=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const l of this.segments.values())for(const c of l)c.time.from>e+d&&c.status===ee.FED&&u(c)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=fn(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:C.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(te(this.sourceBuffer)||te(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}const t=1;for(const i of this.segments.values())for(const r of i){const{status:a}=r;if(a!==ee.FED&&a!==ee.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(l=>l.from-t<=n&&l.to+t>=o),d=e.filter(l=>n>=l.from-t&&n<=l.to+t||o>=l.from-t&&o<=l.to+t);u||(d.length===1?r.status=ee.PARTIALLY_EJECTED:r.status=ee.NONE)}}}var jt;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(jt||(jt={}));class ym{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new S(void 0),this.lastConnectionReused$=new S(void 0),this.lastRequestFirstBytes$=new S(void 0),this.abortAllController=new zt,this.subscription=new re,this.fetchManifest=Re(this.abortAllController.signal,async function*(r){let a=r;this.requestQuic&&(a=Kt(a));const n=yield bi(a,{signal:this.abortAllController.signal}).catch(li);return n?(this.onHeadersReceived(n.headers),n.text()):null}.bind(this)),this.fetch=Re(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}={}){var c,h,f,m;let g=r;const T=new Headers;if(n)switch(a){case jt.HEADER:{T.append("Range",`bytes=${n.from}-${n.to}`);break}case jt.PARAM:{const M=new URL(g,location.href);M.searchParams.append("bytes",`${n.from}-${n.to}`),g=M.toString();break}default:V(a)}this.requestQuic&&(g=Kt(g));let A=this.abortAllController.signal,E;if(d){const M=new zt;if(E=U(B(this.abortAllController.signal,"abort"),B(d,"abort")).subscribe(()=>{try{M.abort()}catch(X){li(X)}}),this.abortAllController.signal.aborted||d.aborted)try{M.abort()}catch(X){li(X)}A=M.signal}const v=pe(),b=yield bi(g,{priority:u,headers:T,signal:A}).catch(li),$=pe();if((c=this.throughputEstimator)===null||c===void 0||c.addRawRtt($-v),!b)return E==null||E.unsubscribe(),null;if(!b.ok||!b.body)return E==null||E.unsubscribe(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`));this.onHeadersReceived(b.headers);const D=parseInt((h=b.headers.get("Content-Length"))!==null&&h!==void 0?h:"",10)||n&&n.to-n.from+1||NaN;if(!D){const M=yield b.arrayBuffer();return(f=this.throughputEstimator)===null||f===void 0||f.addRawSpeed(M.byteLength,pe()-$),o==null||o(new DataView(M),M.byteLength),E==null||E.unsubscribe(),M}if(!o&&!l)return E==null||E.unsubscribe(),b.arrayBuffer();const[Y,J]=b.body.tee(),N=Y.getReader();l&&((m=this.throughputEstimator)===null||m===void 0||m.trackStream(J));let G=0;const Q=new ArrayBuffer(D),O=new Uint8Array(Q),H=new DataView(Q);let ae=!1;const F=M=>{E==null||E.unsubscribe(),ae=!0,li(M)},I=Re(A,async function*({done:M,value:X}){if(G===0&&this.lastRequestFirstBytes$.next(pe()-v),A.aborted){E==null||E.unsubscribe();return}!M&&X&&(O.set(X,G),G+=X.byteLength,o==null||o(H,G),yield N==null?void 0:N.read().then(I,F))}.bind(this));return yield N==null?void 0:N.read().then(I,F),E==null||E.unsubscribe(),ae?null:Q}.bind(this)),this.fetchByteRangeRepresentation=Re(this.abortAllController.signal,async function*(r,a,n){var o;if(r.type!==Be.BYTE_RANGE)return null;const{from:u,to:d}=r.initRange;let l=u,c=d,h=!1,f,m;r.indexRange&&(f=r.indexRange.from,m=r.indexRange.to,h=d+1===f,h&&(l=Math.min(f,u),c=Math.max(m,d))),l=Math.min(l,0);const g=yield this.fetch(r.url,{range:{from:l,to:c},priority:n,measureThroughput:!1});if(!g)return null;const T=new DataView(g,u-l,d-l+1);if(!a.validateData(T))throw new Error("Invalid media file");const A=a.parseInit(T),E=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(A);if(!E)throw new ReferenceError("No way to load representation index");let v;if(h)v=new DataView(g,E.from-l,E.to-E.from+1);else{const $=yield this.fetch(r.url,{range:E,priority:n,measureThroughput:!1});if(!$)return null;v=new DataView($)}const b=a.parseSegments(v,A,E);return{init:A,dataView:new DataView(g),segments:b}}.bind(this)),this.fetchTemplateRepresentation=Re(this.abortAllController.signal,async function*(r,a){if(r.type!==Be.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:ee.NONE,size:void 0})),dataView:new DataView(o)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=xo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var r,a;const{type:n}=e;switch(n){case Be.BYTE_RANGE:return(r=await this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case Be.TEMPLATE:return(a=await this.fetchTemplateRepresentation(e,i))!==null&&a!==void 0?a:null;default:V(n)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const li=s=>{if(!(s instanceof DOMException)||!(s.name==="AbortError"||s.code===20))throw s};var Tm=It,Em=fs,$m=qe,Am=$m("match"),km=function(s){var e;return Tm(s)&&((e=s[Am])!==void 0?!!e:Em(s)=="RegExp")},wm=bs,_m=String,Pm=function(s){if(wm(s)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return _m(s)},Dm=Lt,Rm=function(){var s=Dm(this),e="";return s.hasIndices&&(e+="d"),s.global&&(e+="g"),s.ignoreCase&&(e+="i"),s.multiline&&(e+="m"),s.dotAll&&(e+="s"),s.unicode&&(e+="u"),s.unicodeSets&&(e+="v"),s.sticky&&(e+="y"),e},Im=dt,xm=ut,Lm=Vr,Cm=Rm,gn=RegExp.prototype,Om=function(s){var e=s.flags;return e===void 0&&!("flags"in gn)&&!xm(s,"flags")&&Lm(gn,s)?Im(Cm,s):e},ea=ot,Bm=vs,Mm=Math.floor,ar=ea("".charAt),Nm=ea("".replace),nr=ea("".slice),Fm=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Um=/\$([$&'`]|\d{1,2})/g,Vm=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=Um;return r!==void 0&&(r=Bm(r),u=Fm),Nm(a,u,function(d,l){var c;switch(ar(l,0)){case"$":return"$";case"&":return s;case"`":return nr(e,0,t);case"'":return nr(e,n);case"<":c=r[nr(l,1,-1)];break;default:var h=+l;if(h===0)return d;if(h>o){var f=Mm(h/10);return f===0?d:f<=o?i[f-1]===void 0?ar(l,1):i[f-1]+ar(l,1):d}c=i[h-1]}return c===void 0?"":c})},Hm=Ss,Gm=dt,ta=ot,Sn=Nr,Ym=Ne,qm=ps,jm=km,Gt=Pm,zm=ms,Wm=Om,Qm=Vm,Km=qe,Jm=Km("replace"),Xm=TypeError,Go=ta("".indexOf),Zm=ta("".replace),bn=ta("".slice),ev=Math.max,yn=function(s,e,t){return t>s.length?-1:e===""?t:Go(s,e,t)};Hm({target:"String",proto:!0},{replaceAll:function(e,t){var i=Sn(this),r,a,n,o,u,d,l,c,h,f=0,m=0,g="";if(!qm(e)){if(r=jm(e),r&&(a=Gt(Sn(Wm(e))),!~Go(a,"g")))throw Xm("`.replaceAll` does not allow non-global regexes");if(n=zm(e,Jm),n)return Gm(n,e,i,t);if(r)return Zm(Gt(i),e,t)}for(o=Gt(i),u=Gt(e),d=Ym(t),d||(t=Gt(t)),l=u.length,c=ev(1,l),f=yn(o,u,0);f!==-1;)h=d?Gt(t(u,f,o)):Qm(u,o,f,[],void 0,t),g+=bn(o,m,f)+h,m=f+l,f=yn(o,u,f+c);return m<o.length&&(g+=bn(o,m)),g}});var tv=Ro,iv=tv("String","replaceAll"),sv=iv,rv=sv,av=rv,nv=av,Tn=Mr(nv);const En=s=>{if(!s.startsWith("P"))return;const e=(n,o)=>{const u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},or=(s,e)=>{let t=s;t=Tn(t,"$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,a]of Object.entries(i)){const n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=Tn(t,n,(o,u)=>te(a)?o:te(u)?a:a.padStart(parseInt(u,10),"0"))}return t},ov=(s,e)=>{var t,i,r,a,n,o,u,d,l,c,h,f,m,g,T,A,E,v,b,$,D,Y,J,N,G,Q,O,H,ae,F,I,M,X,he,ve,_e,je,pt,Z;const xe=new DOMParser().parseFromString(s,"application/xml"),Pe={video:[],audio:[],text:[]},Le=xe.children[0],Ot=Le.getElementsByTagName("Period")[0],$t=Ot.children,Bt=Le.getAttribute("type")==="dynamic",Mt=Le.getAttribute("availabilityStartTime"),wi=Mt?new Date(Mt).getTime():void 0;let At;const ia=Le.getAttribute("mediaPresentationDuration"),sa=Ot.getAttribute("duration"),As=Le.getElementsByTagName("vk:Attrs")[0],ra=As==null?void 0:As.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(ia)At=En(ia);else if(sa){const Fe=En(sa);_(Fe)&&(At=Fe)}else ra&&(At=parseInt(ra,10));let Jo=0;const ks=(i=(t=Le.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],Xo=ks.includes(ds.WEBM_AS_IN_FFMPEG)||ks.includes(ds.WEBM_AS_IN_SPEC)?Jt.WEBM:Jt.MP4;for(const Fe of $t){const _i=Fe.getAttribute("mimeType"),Zo=Fe.getAttribute("codecs"),aa=(r=Fe.getAttribute("contentType"))!==null&&r!==void 0?r:_i==null?void 0:_i.split("/")[0],ed=(n=(a=Fe.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],na=Fe.querySelectorAll("Representation"),td=Fe.querySelector("SegmentTemplate");if(aa===Te.TEXT){for(const ge of na){const mt=ge.getAttribute("id")||"",Pi=Fe.getAttribute("lang"),Nt=(d=(u=(o=ge.querySelector("BaseURL"))===null||o===void 0?void 0:o.textContent)===null||u===void 0?void 0:u.trim())!==null&&d!==void 0?d:"",ws=new URL(Nt,e).toString(),_s=mt.includes("_auto");Pe[Te.TEXT].push({id:mt,lang:Pi,isAuto:_s,kind:Te.TEXT,url:ws})}continue}for(const ge of na){const mt=(l=ge.getAttribute("mimeType"))!==null&&l!==void 0?l:_i,Pi=(h=(c=ge.getAttribute("codecs"))!==null&&c!==void 0?c:Zo)!==null&&h!==void 0?h:"",Nt=(m=(f=ge.getAttribute("contentType"))!==null&&f!==void 0?f:mt==null?void 0:mt.split("/")[0])!==null&&m!==void 0?m:aa,ws=(T=(g=Fe.getAttribute("profiles"))===null||g===void 0?void 0:g.split(","))!==null&&T!==void 0?T:[],_s=parseInt((A=ge.getAttribute("width"))!==null&&A!==void 0?A:"",10),oa=parseInt((E=ge.getAttribute("height"))!==null&&E!==void 0?E:"",10),da=parseInt((v=ge.getAttribute("bandwidth"))!==null&&v!==void 0?v:"",10)/1e3,ua=(b=ge.getAttribute("frameRate"))!==null&&b!==void 0?b:"",id=($=ge.getAttribute("quality"))!==null&&$!==void 0?$:void 0,sd=ua?Xr(ua):void 0,rd=(D=ge.getAttribute("id"))!==null&&D!==void 0?D:(Jo++).toString(10),ad=Nt==="video"?`${oa}p`:Nt==="audio"?`${da}Kbps`:Pi,nd=`${rd}@${ad}`,od=(N=(J=(Y=ge.querySelector("BaseURL"))===null||Y===void 0?void 0:Y.textContent)===null||J===void 0?void 0:J.trim())!==null&&N!==void 0?N:"",la=new URL(od,e).toString(),dd=[...ks,...ed,...ws];let Ps;const ud=ge.querySelector("SegmentBase"),kt=(G=ge.querySelector("SegmentTemplate"))!==null&&G!==void 0?G:td;if(ud){const si=(O=(Q=ge.querySelector("SegmentBase Initialization"))===null||Q===void 0?void 0:Q.getAttribute("range"))!==null&&O!==void 0?O:"",[ri,Rs]=si.split("-").map(Ft=>parseInt(Ft,10)),ai={from:ri,to:Rs},ni=(H=ge.querySelector("SegmentBase"))===null||H===void 0?void 0:H.getAttribute("indexRange"),[Is,Di]=ni?ni.split("-").map(Ft=>parseInt(Ft,10)):[],oi=ni?{from:Is,to:Di}:void 0;Ps={type:Be.BYTE_RANGE,url:la,initRange:ai,indexRange:oi}}else if(kt){const si={representationId:(ae=ge.getAttribute("id"))!==null&&ae!==void 0?ae:void 0,bandwidth:(F=ge.getAttribute("bandwidth"))!==null&&F!==void 0?F:void 0},ri=parseInt((I=kt.getAttribute("timescale"))!==null&&I!==void 0?I:"",10),Rs=(M=kt.getAttribute("initialization"))!==null&&M!==void 0?M:"",ai=kt.getAttribute("media"),ni=(he=parseInt((X=kt.getAttribute("startNumber"))!==null&&X!==void 0?X:"",10))!==null&&he!==void 0?he:1,Is=or(Rs,si);if(!ai)throw new ReferenceError("No media attribute in SegmentTemplate");const Di=(ve=kt.querySelectorAll("SegmentTimeline S"))!==null&&ve!==void 0?ve:[],oi=[];let Ft=0;if(Di.length){let xs=ni,tt=0;for(const di of Di){const vt=parseInt((_e=di.getAttribute("d"))!==null&&_e!==void 0?_e:"",10),wt=parseInt((je=di.getAttribute("r"))!==null&&je!==void 0?je:"",10)||0,Ri=parseInt((pt=di.getAttribute("t"))!==null&&pt!==void 0?pt:"",10);tt=Number.isFinite(Ri)?Ri:tt;const Ls=vt/ri*1e3,ca=tt/ri*1e3;for(let Ii=0;Ii<wt+1;Ii++){const ld=or(ai,{...si,segmentNumber:xs.toString(10),segmentTime:(tt+Ii*vt).toString(10)}),ha=(ca||0)+Ii*Ls,cd=ha+Ls;xs++,oi.push({time:{from:ha,to:cd},url:ld})}tt+=(wt+1)*vt,Ft+=(wt+1)*Ls}}else if(_(At)){const tt=parseInt((Z=kt.getAttribute("duration"))!==null&&Z!==void 0?Z:"",10)/ri*1e3,di=Math.ceil(At/tt);let vt=0;for(let wt=1;wt<di;wt++){const Ri=or(ai,{...si,segmentNumber:wt.toString(10),segmentTime:vt.toString(10)});oi.push({time:{from:vt,to:vt+tt},url:Ri}),vt+=tt}}Ps={type:Be.TEMPLATE,baseUrl:la,initUrl:Is,totalSegmentsDurationMs:Ft,segments:oi}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Nt||!mt)continue;const Ds={video:Te.VIDEO,audio:Te.AUDIO,text:Te.TEXT}[Nt];Ds&&Pe[Ds].push({id:nd,kind:Ds,segmentReference:Ps,profiles:dd,duration:At,bitrate:da,mime:mt,codecs:Pi,width:_s,height:oa,fps:sd,quality:id})}}return{dynamic:Bt,liveAvailabilityStartTime:wi,duration:At,container:Xo,representations:Pe}},Cr=1e3,$n=["timeupdate","progress","play","seeked","stalled","waiting"];var Oe;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(Oe||(Oe={}));let dv=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new re,this.representationSubscription=new re,this.state$=new ue(Oe.NONE),this.currentVideoRepresentation$=new S(void 0),this.currentVideoRepresentationInit$=new S(void 0),this.error$=new L,this.lastConnectionType$=new S(void 0),this.lastConnectionReused$=new S(void 0),this.lastRequestFirstBytes$=new S(void 0),this.isLive$=new S(!1),this.liveDuration$=new S(0),this.liveAvailabilityStartTime$=new S(void 0),this.bufferLength$=new S(0),this.liveLoadBufferLength$=new S(0),this.forceEnded$=new L,this.gapWatchdogStarted=!1,this.destroyController=new zt,this.initManifest=Re(this.destroyController.signal,async function*(t,i,r){var a;this.element=t,this.manifestUrlString=He(i,r,be.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Oe.MANIFEST_READY),this.manifest=yield this.updateManifest(),!((a=this.manifest)===null||a===void 0)&&a.representations.video.length?this.state$.setState(Oe.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:C.PARSER,message:"No playable video representations"})}.bind(this)),this.updateManifest=Re(this.destroyController.signal,async function*(){var t;const i=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:C.NETWORK,message:"Failed to load manifest",thrown:n})});if(!i)return this.manifest;let r;try{r=ov(i!=null?i:"",this.manifestUrlString)}catch(n){this.error$.next({id:"ManifestParsing",category:C.PARSER,message:"Failed to parse MPD manifest",thrown:n})}if(!r)return null;const a=({kind:n,mime:o,codecs:u})=>{var d,l,c,h;return!!(!((l=(d=this.element)===null||d===void 0?void 0:d.canPlayType)===null||l===void 0)&&l.call(d,o)&&(!((h=(c=window.MediaSource)===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0)&&h.call(c,`${o}; codecs="${u}"`))||n===Te.TEXT)};return this.isLive$.getValue()!==r.dynamic&&(this.isLive$.next(r.dynamic),this.liveDuration$.getValue()!==r.duration&&this.liveDuration$.next(-1*((t=r.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==r.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(r.liveAvailabilityStartTime)),{...r,representations:Qt(Object.entries(r.representations).map(([n,o])=>[n,o.filter(a)]))}}.bind(this)),this.initRepresentations=Re(this.destroyController.signal,async function*(t,i){P(this.manifest),P(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Oe.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,manifest:this.manifest};if(this.videoBufferManager=new vn(Te.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],_(i)&&(this.audioBufferManager=new vn(Te.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,r),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(is(Cr).subscribe(o=>{var u;if(!((u=this.element)===null||u===void 0)&&u.paused){const d=nn(this.manifestUrlString,be.DASH_CMAF_OFFSET_P);this.manifestUrlString=He(this.manifestUrlString,d+1e3,be.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(U(...$n.map(o=>B(this.element,o))).pipe(md(Cr),w(o=>this.element?bt(this.element.buffered,this.element.currentTime*1e3):0)).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.subscribe(u=>{var d,l;let c=0;if(u){const h=((l=(d=this.element)===null||d===void 0?void 0:d.currentTime)!==null&&l!==void 0?l:0)*1e3;c=Math.min(...this.bufferManagers.map(m=>{var g,T;return(T=(g=m.getLiveSegmentsToLoadState(this.manifest))===null||g===void 0?void 0:g.to)!==null&&T!==void 0?T:0}))-h}this.liveLoadBufferLength$.next(c)}));let o=0;this.representationSubscription.add(this.liveLoadBufferLength$.subscribe(async u=>{P(this.element);const d=this.element.playbackRate,l=nn(this.manifestUrlString,be.DASH_CMAF_OFFSET_P),c=fm*d,h=mm*d,f=pm*d;o=u>o?u:o;const m=l===0&&u<f,g=l!==0&&u<c+f&&u>=c,T=l!==0&&u<c;if(T||g){const A=o-(c+h),E=Math.trunc(l+A/d);let v;u?E>0?v=E:v=0:v=l,this.manifestUrlString=He(this.manifestUrlString,v,be.DASH_CMAF_OFFSET_P)}(m||T||g)&&(await this.updateLive(),o=0)}))}const a=U(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(w(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=U(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(w(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.representationSubscription.add(U(this.forceEnded$,Ie({allBuffersFull:a,someBufferEnded:n}).pipe(se(({allBuffersFull:o,someBufferEnded:u})=>o&&u))).subscribe(()=>{var o;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(u=>!u.updating))try{(o=this.source)===null||o===void 0||o.endOfStream()}catch(u){this.error$.next({id:"EndOfStream",category:C.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:u})}})),this.representationSubscription.add(U(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield new Promise(o=>{var u;return(u=this.source)===null||u===void 0?void 0:u.addEventListener("sourceopen",o)})),_(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&_(i)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)]):yield this.videoBufferManager.startWith(t),this.state$.setState(Oe.REPRESENTATIOS_READY)}.bind(this)),this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((i=this.audioBufferManager)===null||i===void 0)&&i.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=is(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:C.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new ym({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}async seekLive(e){var t,i,r,a;P(this.element),this.manifestUrlString=He(this.manifestUrlString,e,be.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),await((t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((i=this.manifest)===null||i===void 0?void 0:i.representations.video)),await((r=this.audioBufferManager)===null||r===void 0?void 0:r.seekLive((a=this.manifest)===null||a===void 0?void 0:a.representations.audio))}initBuffer(){P(this.element),this.state$.setState(Oe.RUNNING),this.subscription.add(U(...$n.map(e=>B(this.element,e)),B(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:C.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(B(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(B(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Lr(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){const i={[Te.VIDEO]:this.videoBufferManager,[Te.AUDIO]:this.audioBufferManager,[Te.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)}seek(e,t){var i,r,a,n,o;P(this.element),P(this.videoBufferManager);let u;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?u=e:u=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!==null&&i!==void 0?i:e,(a=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&a!==void 0?a:e),Lr(this.element.buffered,u)||(this.videoBufferManager.abort(),(n=this.audioBufferManager)===null||n===void 0||n.abort()),this.videoBufferManager.maintain(u),(o=this.audioBufferManager)===null||o===void 0||o.maintain(u),this.element.currentTime=u/1e3}stop(){var e,t;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(e=this.videoBufferManager)===null||e===void 0||e.destroy(),this.videoBufferManager=null,(t=this.audioBufferManager)===null||t===void 0||t.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Oe.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}async updateLive(){var e;this.manifest=await this.updateManifest(),(e=this.bufferManagers)===null||e===void 0||e.forEach(t=>t.updateLive(this.manifest))}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isLive$.getValue()&&this.element.currentTime>e.to&&(this.element.currentTime=0);const t=this.element.currentTime*1e3,i=[];for(const r of this.bufferManagers)for(const a of r.gaps)r.playingRepresentation$.getValue()===a.representation&&a.from<=t&&a.to>t&&(this.element.duration*1e3-a.to<this.tuning.endGapTolerance?i.push(1/0):i.push(a.to));if(i.length){const r=Math.max(...i);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=r/1e3}}};class uv{constructor(e,t){this.fov=e,this.orientation=t}}class lv{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,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);const r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,n=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:a,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){const e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){const t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}const t=e-this.lastTickTS,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){const r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var cv=`#define GLSLIFY 1
|
|
30
30
|
attribute vec2 a_vertex;attribute vec2 a_texel;varying vec2 v_texel;void main(void){gl_Position=vec4(a_vertex,0.0,1.0);v_texel=a_texel;}`,hv=`#ifdef GL_ES
|
|
31
31
|
precision highp float;precision highp int;
|
|
32
32
|
#else
|