@vkontakte/videoplayer-core 2.0.98-dev.27a468df.0 → 2.0.98-dev.489417ae.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +13 -13
- package/es2015.esm.js +9 -9
- package/es2018.cjs.js +12 -12
- package/es2018.esm.js +14 -14
- package/esnext.cjs.js +8 -8
- package/esnext.esm.js +10 -10
- package/evergreen.esm.js +9 -9
- package/index.d.ts +4 -1
- package/package.json +3 -4
package/es2018.esm.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.98-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.98-dev.489417ae.0
|
|
3
|
+
* Thu, 15 Feb 2024 17:01:30 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-98/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{ValueSubject as T,Subject as C,Subscription as ue,isNonNullable as D,ErrorCategory as R,isNullable as j,fromEvent as U,assertNever as q,merge as H,tap as Ks,map as _,observableFrom as He,filterChanged as ve,assertNonNullable as P,debounce as it,getHighestQuality as iu,timeout as su,getCurrentBrowser as hr,CurrentClientBrowser as qa,combine as Le,once as Ae,mapTo as Hi,filter as ae,now as le,assertNotEmptyArray as ru,videoSizeToQuality as si,isInvariantQuality as yi,isHigher as Vi,isLower as qs,isHigherOrEqual as Pa,isLowerOrEqual as Mo,Observable as fr,interval as Ti,VideoQuality as rt,videoQualityToHeight as au,abortable as ce,getExponentialDelay as ms,throttle as nu,isIOS as ou,CurrentClientDevice as du,safeStorage as Fr,fillWithDefault as uu,Logger as lu}from"@vkontakte/videoplayer-shared/es2018.esm.js";import{Observable as cb,Subject as hb,Subscription as fb,ValueSubject as pb,VideoQuality as mb}from"@vkontakte/videoplayer-shared/es2018.esm.js";import cu from"lodash/debounce.js";import{debounce as hu}from"lodash";const fu="2.0.98-dev.27a468df.0";var p;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(p||(p={}));var A;(function(s){s.MPEG="MPEG",s.DASH="DASH",s.DASH_SEP="DASH_SEP",s.DASH_SEP_VK="DASH_SEP",s.DASH_WEBM="DASH_WEBM",s.DASH_WEBM_AV1="DASH_WEBM_AV1",s.DASH_WEBM_VK="DASH_WEBM",s.DASH_ONDEMAND="DASH_ONDEMAND",s.DASH_ONDEMAND_VK="DASH_ONDEMAND",s.DASH_LIVE="DASH_LIVE",s.DASH_LIVE_CMAF="DASH_LIVE_CMAF",s.DASH_LIVE_WEBM="DASH_LIVE_WEBM",s.HLS="HLS",s.HLS_ONDEMAND="HLS_ONDEMAND",s.HLS_JS="HLS",s.HLS_LIVE="HLS_LIVE",s.HLS_LIVE_CMAF="HLS_LIVE_CMAF",s.WEB_RTC_LIVE="WEB_RTC_LIVE"})(A||(A={}));var Fe;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(Fe||(Fe={}));var xe;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})(xe||(xe={}));var vs;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(vs||(vs={}));var ee;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(ee||(ee={}));var Zt;(function(s){s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip"})(Zt||(Zt={}));var pu=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 mu{constructor(e){var t;this.connection$=new T(void 0),this.castState$=new T(xe.NOT_AVAILABLE),this.errorEvent$=new C,this.realCastState$=new T(xe.NOT_AVAILABLE),this.subscription=new ue,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const i="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${i}`}),e.isDisabled||!i)return;const r=D((t=window.chrome)===null||t===void 0?void 0:t.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||pu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:R.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())===null||i===void 0?void 0:i.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||a===void 0||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){D(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();j(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();j(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(U(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(a=i.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return q(r.sessionState)}})).add(H(U(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Ks(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),_(r=>r.castState)),He([i.getCastState()])).pipe(ve(),_(gu),Ks(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===xe.CONNECTED,o=D(this.connection$.getValue());if(n&&!o){const u=i.getCurrentSession();P(u);const d=u.getCastDevice(),l=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(j(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===xe.CONNECTED?D(this.connection$.getValue())?xe.CONNECTED:xe.AVAILABLE:r)}))}initializeCastApi(){var e;let t,i,r;try{t=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:i,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:R.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const gu=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return xe.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return xe.AVAILABLE;case cast.framework.CastState.CONNECTING:return xe.CONNECTING;case cast.framework.CastState.CONNECTED:return xe.CONNECTED;default:return q(s)}};var Ur=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function za(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var qt=function(s){try{return!!s()}catch(e){return!0}},vu=qt,pr=!vu(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),No=pr,Fo=Function.prototype,Da=Fo.call,Su=No&&Fo.bind.bind(Da,Da),zt=No?Su:function(s){return function(){return Da.apply(s,arguments)}},Uo=zt,bu=Uo({}.toString),yu=Uo("".slice),mr=function(s){return yu(bu(s),8,-1)},Tu=zt,Eu=qt,$u=mr,Vr=Object,Au=Tu("".split),ku=Eu(function(){return!Vr("z").propertyIsEnumerable(0)})?function(s){return $u(s)=="String"?Au(s,""):Vr(s)}:Vr,gr=function(s){return s==null},wu=gr,_u=TypeError,ja=function(s){if(wu(s))throw _u("Can't call method on "+s);return s},Pu=ku,Du=ja,Ts=function(s){return Pu(Du(s))},Wi={},_s=function(s){return s&&s.Math==Math&&s},St=_s(typeof globalThis=="object"&&globalThis)||_s(typeof window=="object"&&window)||_s(typeof self=="object"&&self)||_s(typeof Ur=="object"&&Ur)||function(){return this}()||Ur||Function("return this")(),Ra=typeof document=="object"&&document.all,Ru=typeof Ra=="undefined"&&Ra!==void 0,Vo={all:Ra,IS_HTMLDDA:Ru},Ho=Vo,Iu=Ho.all,lt=Ho.IS_HTMLDDA?function(s){return typeof s=="function"||s===Iu}:function(s){return typeof s=="function"},Lu=St,xu=lt,pn=Lu.WeakMap,Cu=xu(pn)&&/native code/.test(String(pn)),mn=lt,Go=Vo,Bu=Go.all,Ai=Go.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:mn(s)||s===Bu}:function(s){return typeof s=="object"?s!==null:mn(s)},Ou=qt,ki=!Ou(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Qi={},Mu=St,gn=Ai,Ia=Mu.document,Nu=gn(Ia)&&gn(Ia.createElement),Yo=function(s){return Nu?Ia.createElement(s):{}},Fu=ki,Uu=qt,Vu=Yo,qo=!Fu&&!Uu(function(){return Object.defineProperty(Vu("div"),"a",{get:function(){return 7}}).a!=7}),Hu=ki,Gu=qt,zo=Hu&&Gu(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Yu=Ai,qu=String,zu=TypeError,wi=function(s){if(Yu(s))return s;throw zu(qu(s)+" is not an object")},ju=pr,Ps=Function.prototype.call,jt=ju?Ps.bind(Ps):function(){return Ps.apply(Ps,arguments)},Wa={},Hr=Wa,Gr=St,Wu=lt,vn=function(s){return Wu(s)?s:void 0},Qa=function(s,e){return arguments.length<2?vn(Hr[s])||vn(Gr[s]):Hr[s]&&Hr[s][e]||Gr[s]&&Gr[s][e]},Qu=zt,Ka=Qu({}.isPrototypeOf),Ku=typeof navigator!="undefined"&&String(navigator.userAgent)||"",jo=St,Yr=Ku,Sn=jo.process,bn=jo.Deno,yn=Sn&&Sn.versions||bn&&bn.version,Tn=yn&&yn.v8,gt,Js;Tn&&(gt=Tn.split("."),Js=gt[0]>0&>[0]<4?1:+(gt[0]+gt[1]));!Js&&Yr&&(gt=Yr.match(/Edge\/(\d+)/),(!gt||gt[1]>=74)&&(gt=Yr.match(/Chrome\/(\d+)/),gt&&(Js=+gt[1])));var Ju=Js,En=Ju,Xu=qt,Zu=St,el=Zu.String,Wo=!!Object.getOwnPropertySymbols&&!Xu(function(){var s=Symbol();return!el(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&En&&En<41}),tl=Wo,Qo=tl&&!Symbol.sham&&typeof Symbol.iterator=="symbol",il=Qa,sl=lt,rl=Ka,al=Qo,nl=Object,Ko=al?function(s){return typeof s=="symbol"}:function(s){var e=il("Symbol");return sl(e)&&rl(e.prototype,nl(s))},ol=String,Ja=function(s){try{return ol(s)}catch(e){return"Object"}},dl=lt,ul=Ja,ll=TypeError,Xa=function(s){if(dl(s))return s;throw ll(ul(s)+" is not a function")},cl=Xa,hl=gr,vr=function(s,e){var t=s[e];return hl(t)?void 0:cl(t)},qr=jt,zr=lt,jr=Ai,fl=TypeError,pl=function(s,e){var t,i;if(e==="string"&&zr(t=s.toString)&&!jr(i=qr(t,s))||zr(t=s.valueOf)&&!jr(i=qr(t,s))||e!=="string"&&zr(t=s.toString)&&!jr(i=qr(t,s)))return i;throw fl("Can't convert object to primitive value")},Jo={exports:{}},$n=St,ml=Object.defineProperty,gl=function(s,e){try{ml($n,s,{value:e,configurable:!0,writable:!0})}catch(t){$n[s]=e}return e},vl=St,Sl=gl,An="__core-js_shared__",bl=vl[An]||Sl(An,{}),Xo=bl,kn=Xo;(Jo.exports=function(s,e){return kn[s]||(kn[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 Zo=Jo.exports,yl=ja,Tl=Object,Sr=function(s){return Tl(yl(s))},El=zt,$l=Sr,Al=El({}.hasOwnProperty),Wt=Object.hasOwn||function(e,t){return Al($l(e),t)},kl=zt,wl=0,_l=Math.random(),Pl=kl(1 .toString),ed=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Pl(++wl+_l,36)},Dl=St,Rl=Zo,wn=Wt,Il=ed,Ll=Wo,xl=Qo,Ni=Dl.Symbol,Wr=Rl("wks"),Cl=xl?Ni.for||Ni:Ni&&Ni.withoutSetter||Il,bt=function(s){return wn(Wr,s)||(Wr[s]=Ll&&wn(Ni,s)?Ni[s]:Cl("Symbol."+s)),Wr[s]},Bl=jt,_n=Ai,Pn=Ko,Ol=vr,Ml=pl,Nl=bt,Fl=TypeError,Ul=Nl("toPrimitive"),Vl=function(s,e){if(!_n(s)||Pn(s))return s;var t=Ol(s,Ul),i;if(t){if(e===void 0&&(e="default"),i=Bl(t,s,e),!_n(i)||Pn(i))return i;throw Fl("Can't convert object to primitive value")}return e===void 0&&(e="number"),Ml(s,e)},Hl=Vl,Gl=Ko,Za=function(s){var e=Hl(s,"string");return Gl(e)?e:e+""},Yl=ki,ql=qo,zl=zo,Ds=wi,Dn=Za,jl=TypeError,Qr=Object.defineProperty,Wl=Object.getOwnPropertyDescriptor,Kr="enumerable",Jr="configurable",Xr="writable";Qi.f=Yl?zl?function(e,t,i){if(Ds(e),t=Dn(t),Ds(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Xr in i&&!i[Xr]){var r=Wl(e,t);r&&r[Xr]&&(e[t]=i.value,i={configurable:Jr in i?i[Jr]:r[Jr],enumerable:Kr in i?i[Kr]:r[Kr],writable:!1})}return Qr(e,t,i)}:Qr:function(e,t,i){if(Ds(e),t=Dn(t),Ds(i),ql)try{return Qr(e,t,i)}catch(r){}if("get"in i||"set"in i)throw jl("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var br=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},Ql=ki,Kl=Qi,Jl=br,Es=Ql?function(s,e,t){return Kl.f(s,e,Jl(1,t))}:function(s,e,t){return s[e]=t,s},Xl=Zo,Zl=ed,Rn=Xl("keys"),en=function(s){return Rn[s]||(Rn[s]=Zl(s))},tn={},ec=Cu,td=St,tc=Ai,ic=Es,Zr=Wt,ea=Xo,sc=en,rc=tn,In="Object already initialized",La=td.TypeError,ac=td.WeakMap,Xs,Ss,Zs,nc=function(s){return Zs(s)?Ss(s):Xs(s,{})},oc=function(s){return function(e){var t;if(!tc(e)||(t=Ss(e)).type!==s)throw La("Incompatible receiver, "+s+" required");return t}};if(ec||ea.state){var Et=ea.state||(ea.state=new ac);Et.get=Et.get,Et.has=Et.has,Et.set=Et.set,Xs=function(s,e){if(Et.has(s))throw La(In);return e.facade=s,Et.set(s,e),e},Ss=function(s){return Et.get(s)||{}},Zs=function(s){return Et.has(s)}}else{var Ii=sc("state");rc[Ii]=!0,Xs=function(s,e){if(Zr(s,Ii))throw La(In);return e.facade=s,ic(s,Ii,e),e},Ss=function(s){return Zr(s,Ii)?s[Ii]:{}},Zs=function(s){return Zr(s,Ii)}}var dc={set:Xs,get:Ss,has:Zs,enforce:nc,getterFor:oc},uc=pr,id=Function.prototype,Ln=id.apply,xn=id.call,lc=typeof Reflect=="object"&&Reflect.apply||(uc?xn.bind(Ln):function(){return xn.apply(Ln,arguments)}),cc=mr,hc=zt,sd=function(s){if(cc(s)==="Function")return hc(s)},rd={},ad={},nd={}.propertyIsEnumerable,od=Object.getOwnPropertyDescriptor,fc=od&&!nd.call({1:2},1);ad.f=fc?function(e){var t=od(this,e);return!!t&&t.enumerable}:nd;var pc=ki,mc=jt,gc=ad,vc=br,Sc=Ts,bc=Za,yc=Wt,Tc=qo,Cn=Object.getOwnPropertyDescriptor;rd.f=pc?Cn:function(e,t){if(e=Sc(e),t=bc(t),Tc)try{return Cn(e,t)}catch(i){}if(yc(e,t))return vc(!mc(gc.f,e,t),e[t])};var Ec=qt,$c=lt,Ac=/#|\.prototype\./,$s=function(s,e){var t=wc[kc(s)];return t==Pc?!0:t==_c?!1:$c(e)?Ec(e):!!e},kc=$s.normalize=function(s){return String(s).replace(Ac,".").toLowerCase()},wc=$s.data={},_c=$s.NATIVE="N",Pc=$s.POLYFILL="P",Dc=$s,Bn=sd,Rc=Xa,Ic=pr,Lc=Bn(Bn.bind),dd=function(s,e){return Rc(s),e===void 0?s:Ic?Lc(s,e):function(){return s.apply(e,arguments)}},Rs=St,xc=lc,Cc=sd,Bc=lt,Oc=rd.f,Mc=Dc,Li=Wa,Nc=dd,xi=Es,On=Wt,Fc=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 xc(s,this,arguments)};return e.prototype=s.prototype,e},yr=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?Rs:r?Rs[t]:(Rs[t]||{}).prototype,o=i?Li:Li[t]||xi(Li,t,{})[t],u=o.prototype,d,l,c,h,f,m,S,b,g;for(h in e)d=Mc(i?h:t+(r?".":"#")+h,s.forced),l=!d&&n&&On(n,h),m=o[h],l&&(s.dontCallGetSet?(g=Oc(n,h),S=g&&g.value):S=n[h]),f=l&&S?S:e[h],!(l&&typeof m==typeof f)&&(s.bind&&l?b=Nc(f,Rs):s.wrap&&l?b=Fc(f):a&&Bc(f)?b=Cc(f):b=f,(s.sham||f&&f.sham||m&&m.sham)&&xi(b,"sham",!0),xi(o,h,b),a&&(c=t+"Prototype",On(Li,c)||xi(Li,c,{}),xi(Li[c],h,f),s.real&&u&&(d||!u[h])&&xi(u,h,f)))},xa=ki,Uc=Wt,ud=Function.prototype,Vc=xa&&Object.getOwnPropertyDescriptor,sn=Uc(ud,"name"),Hc=sn&&function(){}.name==="something",Gc=sn&&(!xa||xa&&Vc(ud,"name").configurable),Yc={EXISTS:sn,PROPER:Hc,CONFIGURABLE:Gc},ld={},qc=Math.ceil,zc=Math.floor,jc=Math.trunc||function(e){var t=+e;return(t>0?zc:qc)(t)},Wc=jc,rn=function(s){var e=+s;return e!==e||e===0?0:Wc(e)},Qc=rn,Kc=Math.max,Jc=Math.min,Xc=function(s,e){var t=Qc(s);return t<0?Kc(t+e,0):Jc(t,e)},Zc=rn,eh=Math.min,th=function(s){return s>0?eh(Zc(s),9007199254740991):0},ih=th,an=function(s){return ih(s.length)},sh=Ts,rh=Xc,ah=an,Mn=function(s){return function(e,t,i){var r=sh(e),a=ah(r),n=rh(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}},nh={includes:Mn(!0),indexOf:Mn(!1)},oh=zt,ta=Wt,dh=Ts,uh=nh.indexOf,lh=tn,Nn=oh([].push),ch=function(s,e){var t=dh(s),i=0,r=[],a;for(a in t)!ta(lh,a)&&ta(t,a)&&Nn(r,a);for(;e.length>i;)ta(t,a=e[i++])&&(~uh(r,a)||Nn(r,a));return r},cd=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],hh=ch,fh=cd,ph=Object.keys||function(e){return hh(e,fh)},mh=ki,gh=zo,vh=Qi,Sh=wi,bh=Ts,yh=ph;ld.f=mh&&!gh?Object.defineProperties:function(e,t){Sh(e);for(var i=bh(t),r=yh(t),a=r.length,n=0,o;a>n;)vh.f(e,o=r[n++],i[o]);return e};var Th=Qa,Eh=Th("document","documentElement"),$h=wi,Ah=ld,Fn=cd,kh=tn,wh=Eh,_h=Yo,Ph=en,Un=">",Vn="<",Ca="prototype",Ba="script",hd=Ph("IE_PROTO"),ia=function(){},fd=function(s){return Vn+Ba+Un+s+Vn+"/"+Ba+Un},Hn=function(s){s.write(fd("")),s.close();var e=s.parentWindow.Object;return s=null,e},Dh=function(){var s=_h("iframe"),e="java"+Ba+":",t;return s.style.display="none",wh.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(fd("document.F=Object")),t.close(),t.F},Is,zs=function(){try{Is=new ActiveXObject("htmlfile")}catch(e){}zs=typeof document!="undefined"?document.domain&&Is?Hn(Is):Dh():Hn(Is);for(var s=Fn.length;s--;)delete zs[Ca][Fn[s]];return zs()};kh[hd]=!0;var pd=Object.create||function(e,t){var i;return e!==null?(ia[Ca]=$h(e),i=new ia,ia[Ca]=null,i[hd]=e):i=zs(),t===void 0?i:Ah.f(i,t)},Rh=qt,Ih=!Rh(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),Lh=Wt,xh=lt,Ch=Sr,Bh=en,Oh=Ih,Gn=Bh("IE_PROTO"),Oa=Object,Mh=Oa.prototype,md=Oh?Oa.getPrototypeOf:function(s){var e=Ch(s);if(Lh(e,Gn))return e[Gn];var t=e.constructor;return xh(t)&&e instanceof t?t.prototype:e instanceof Oa?Mh:null},Nh=Es,gd=function(s,e,t,i){return i&&i.enumerable?s[e]=t:Nh(s,e,t),s},Fh=qt,Uh=lt,Vh=Ai,Hh=pd,Yn=md,Gh=gd,Yh=bt,Ma=Yh("iterator"),vd=!1,Ht,sa,ra;[].keys&&(ra=[].keys(),"next"in ra?(sa=Yn(Yn(ra)),sa!==Object.prototype&&(Ht=sa)):vd=!0);var qh=!Vh(Ht)||Fh(function(){var s={};return Ht[Ma].call(s)!==s});qh?Ht={}:Ht=Hh(Ht);Uh(Ht[Ma])||Gh(Ht,Ma,function(){return this});var Sd={IteratorPrototype:Ht,BUGGY_SAFARI_ITERATORS:vd},zh=bt,jh=zh("toStringTag"),bd={};bd[jh]="z";var nn=String(bd)==="[object z]",Wh=nn,Qh=lt,js=mr,Kh=bt,Jh=Kh("toStringTag"),Xh=Object,Zh=js(function(){return arguments}())=="Arguments",ef=function(s,e){try{return s[e]}catch(t){}},Tr=Wh?js:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=ef(e=Xh(s),Jh))=="string"?t:Zh?js(e):(i=js(e))=="Object"&&Qh(e.callee)?"Arguments":i},tf=nn,sf=Tr,rf=tf?{}.toString:function(){return"[object "+sf(this)+"]"},af=nn,nf=Qi.f,of=Es,df=Wt,uf=rf,lf=bt,qn=lf("toStringTag"),yd=function(s,e,t,i){if(s){var r=t?s:s.prototype;df(r,qn)||nf(r,qn,{configurable:!0,value:e}),i&&!af&&of(r,"toString",uf)}},cf=Sd.IteratorPrototype,hf=pd,ff=br,pf=yd,mf=Wi,gf=function(){return this},vf=function(s,e,t,i){var r=e+" Iterator";return s.prototype=hf(cf,{next:ff(+!i,t)}),pf(s,r,!1,!0),mf[r]=gf,s},Sf=yr,bf=jt,Td=Yc,yf=vf,Tf=md,Ef=yd,zn=gd,$f=bt,jn=Wi,Ed=Sd,Af=Td.PROPER;Td.CONFIGURABLE;Ed.IteratorPrototype;var Ls=Ed.BUGGY_SAFARI_ITERATORS,aa=$f("iterator"),Wn="keys",xs="values",Qn="entries",kf=function(){return this},wf=function(s,e,t,i,r,a,n){yf(t,e,i);var o=function(g){if(g===r&&h)return h;if(!Ls&&g in l)return l[g];switch(g){case Wn:return function(){return new t(this,g)};case xs:return function(){return new t(this,g)};case Qn:return function(){return new t(this,g)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,l=s.prototype,c=l[aa]||l["@@iterator"]||r&&l[r],h=!Ls&&c||o(r),f=e=="Array"&&l.entries||c,m,S,b;if(f&&(m=Tf(f.call(new s)),m!==Object.prototype&&m.next&&(Ef(m,u,!0,!0),jn[u]=kf)),Af&&r==xs&&c&&c.name!==xs&&(d=!0,h=function(){return bf(c,this)}),r)if(S={values:o(xs),keys:a?h:o(Wn),entries:o(Qn)},n)for(b in S)(Ls||d||!(b in l))&&zn(l,b,S[b]);else Sf({target:e,proto:!0,forced:Ls||d},S);return n&&l[aa]!==h&&zn(l,aa,h,{name:r}),jn[e]=h,S},_f=function(s,e){return{value:s,done:e}},Pf=Ts,Kn=Wi,$d=dc;Qi.f;var Df=wf,Cs=_f,Ad="Array Iterator",Rf=$d.set,If=$d.getterFor(Ad);Df(Array,"Array",function(s,e){Rf(this,{type:Ad,target:Pf(s),index:0,kind:e})},function(){var s=If(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,Cs(void 0,!0)):t=="keys"?Cs(i,!1):t=="values"?Cs(e[i],!1):Cs([i,e[i]],!1)},"values");Kn.Arguments=Kn.Array;var Lf=bt,xf=Wi,Cf=Lf("iterator"),Bf=Array.prototype,Of=function(s){return s!==void 0&&(xf.Array===s||Bf[Cf]===s)},Mf=Tr,Jn=vr,Nf=gr,Ff=Wi,Uf=bt,Vf=Uf("iterator"),kd=function(s){if(!Nf(s))return Jn(s,Vf)||Jn(s,"@@iterator")||Ff[Mf(s)]},Hf=jt,Gf=Xa,Yf=wi,qf=Ja,zf=kd,jf=TypeError,Wf=function(s,e){var t=arguments.length<2?zf(s):e;if(Gf(t))return Yf(Hf(t,s));throw jf(qf(s)+" is not iterable")},Qf=jt,Xn=wi,Kf=vr,Jf=function(s,e,t){var i,r;Xn(s);try{if(i=Kf(s,"return"),!i){if(e==="throw")throw t;return t}i=Qf(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return Xn(i),t},Xf=dd,Zf=jt,ep=wi,tp=Ja,ip=Of,sp=an,Zn=Ka,rp=Wf,ap=kd,eo=Jf,np=TypeError,Ws=function(s,e){this.stopped=s,this.result=e},to=Ws.prototype,op=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=Xf(e,i),d,l,c,h,f,m,S,b=function(y){return d&&eo(d,"normal",y),new Ws(!0,y)},g=function(y){return r?(ep(y),o?u(y[0],y[1],b):u(y[0],y[1])):o?u(y,b):u(y)};if(a)d=s.iterator;else if(n)d=s;else{if(l=ap(s),!l)throw np(tp(s)+" is not iterable");if(ip(l)){for(c=0,h=sp(s);h>c;c++)if(f=g(s[c]),f&&Zn(to,f))return f;return new Ws(!1)}d=rp(s,l)}for(m=a?s.next:d.next;!(S=Zf(m,d)).done;){try{f=g(S.value)}catch(y){eo(d,"throw",y)}if(typeof f=="object"&&f&&Zn(to,f))return f}return new Ws(!1)},dp=Za,up=Qi,lp=br,cp=function(s,e,t){var i=dp(e);i in s?up.f(s,i,lp(0,t)):s[i]=t},hp=yr,fp=op,pp=cp;hp({target:"Object",stat:!0},{fromEntries:function(e){var t={};return fp(e,function(i,r){pp(t,i,r)},{AS_ENTRIES:!0}),t}});var mp=Wa,gp=mp.Object.fromEntries,vp={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},Sp=vp,bp=St,yp=Tr,Tp=Es,io=Wi,Ep=bt,so=Ep("toStringTag");for(var na in Sp){var ro=bp[na],oa=ro&&ro.prototype;oa&&yp(oa)!==so&&Tp(oa,so,na),io[na]=io.Array}var $p=gp,Ap=$p,kp=Ap,wp=kp,Ei=za(wp),Se;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",s[s.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(Se||(Se={}));var Ve=(s,e=0,t=Se.OFFSET_P)=>{switch(t){case Se.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Se.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case Se.DASH_CMAF_OFFSET_P:{const i=new URL(s);return!i.searchParams.get("offset_p")&&e===0?s:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:q(t)}return s};const er=(s,e)=>{var t;switch(e){case Se.OFFSET_P:return NaN;case Se.PLAYBACK_SHIFT:{const i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case Se.DASH_CMAF_OFFSET_P:{const i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:q(e)}};var I=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};class he{constructor(e){this.transitionStarted$=new C,this.transitionEnded$=new C,this.transitionUpdated$=new C,this.forceChanged$=new C,this.stateChangeStarted$=H(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=H(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||D(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const _p=s=>{switch(s){case A.MPEG:case A.DASH:case A.DASH_SEP:case A.DASH_ONDEMAND:case A.DASH_WEBM:case A.DASH_WEBM_AV1:case A.HLS:case A.HLS_ONDEMAND:return!1;case A.DASH_LIVE:case A.DASH_LIVE_CMAF:case A.HLS_LIVE:case A.HLS_LIVE_CMAF:case A.DASH_LIVE_WEBM:case A.WEB_RTC_LIVE:return!0;default:return q(s)}};var X;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(X||(X={}));const Pp=5,Dp=5,Rp=500,ao=7e3;class Ip{constructor(e){this.subscription=new ue,this.loadMediaTimeoutSubscription=new ue,this.videoState=new he(X.STOPPED),this.syncPlayback=()=>{const i=this.videoState.getState(),r=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${a}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(o)};`}),a===p.STOPPED){i!==X.STOPPED&&(this.videoState.startTransitionTo(X.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==p.PAUSED&&o.state===ee.Requested&&i!==X.STOPPED){this.seek(o.position/1e3);return}switch(a){case p.READY:{switch(i){case X.PLAYING:case X.PAUSED:case X.READY:break;case X.STOPPED:this.videoState.startTransitionTo(X.READY),this.prepare();break;default:q(i)}break}case p.PLAYING:{switch(i){case X.PLAYING:break;case X.PAUSED:this.videoState.startTransitionTo(X.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case X.READY:this.videoState.startTransitionTo(X.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case X.STOPPED:this.videoState.startTransitionTo(X.READY),this.prepare();break;default:q(i)}break}case p.PAUSED:{switch(i){case X.PLAYING:this.videoState.startTransitionTo(X.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case X.PAUSED:break;case X.READY:this.videoState.startTransitionTo(X.PAUSED),this.videoState.setState(X.PAUSED);break;case X.STOPPED:this.videoState.startTransitionTo(X.READY),this.prepare();break;default:q(i)}break}default:q(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(_p(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new ue;this.subscription.add(e),this.subscription.add(H(this.videoState.stateChangeStarted$.pipe(_(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(_(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));const t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const r=new C;e.add(r.pipe(it(Rp)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===ee.Applying||Math.abs(o-a)>Pp)&&r.next(o),a=o})),e.add(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<Dp&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),I(this.params.desiredState.playbackState,p.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:q(n)}}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const i=H(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,He(["init"])).pipe(it(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(X.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):(this.videoState.setState(X.PLAYING),I(this.params.desiredState.playbackState,p.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:ee.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===X.PAUSED||e===X.PLAYING)&&(this.videoState.setState(X.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===X.PLAYING||e===X.PAUSED)&&(this.videoState.setState(X.PLAYING),I(this.params.desiredState.playbackState,p.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===X.READY&&this.videoState.setState(X.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===p.READY&&I(this.params.desiredState.playbackState,p.READY)}handleRemoteStop(){this.videoState.getState()!==X.STOPPED&&this.videoState.setState(X.STOPPED)}handleRemoteVolumeChange(e){var t,i;const r=this.params.output.volume$.getValue(),a={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(i=e.muted)!==null&&i!==void 0?i:r.muted};(a.volume!==r.volume||a.muted!==a.muted)&&this.params.output.volume$.next(a)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const i=this.params.source;let r,a,n;switch(e){case A.MPEG:{const l=i[e];P(l);const c=iu(Object.keys(l));P(c);const h=l[c];P(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case A.HLS:case A.HLS_ONDEMAND:{const l=i[e];P(l),r=l.url,a="application/x-mpegurl",n=chrome.cast.media.StreamType.BUFFERED;break}case A.DASH_SEP:case A.DASH_ONDEMAND:case A.DASH_WEBM:case A.DASH_WEBM_AV1:{const l=i[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case A.DASH_LIVE_CMAF:{const l=i[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case A.HLS_LIVE:case A.HLS_LIVE_CMAF:{const l=i[e];P(l),r=Ve(l.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case A.DASH:case A.DASH_LIVE:case A.WEB_RTC_LIVE:{const l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:R.VIDEO_PIPELINE,message:l,thrown:c}),c}case A.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return q(e)}const o=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,a);o.contentUrl=r,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return D(u)&&(o.metadata.title=u),D(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===ee.Applying||i.state===ee.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(su(ao).subscribe(()=>a(`timeout(${ao})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===ee.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{const a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:R.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}var Lp=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)},xp=s=>{const e=new T(1/0),t=new C,i=new T(void 0),r=new T(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},u=l=>{var c,h,f,m,S;const b=Ei(l.getAllResponseHeaders().trim().split(/[\n\r]+/).map(v=>v.split(": ")));if("x-playback-duration"in b||"x-playback-duration-millis"in b){const v=parseInt((c=l.getResponseHeader("X-Playback-Duration"))!==null&&c!==void 0?c:"",10),E=parseInt((h=l.getResponseHeader("X-Playback-Duration-Millis"))!==null&&h!==void 0?h:"",10),$=(f=E!=null?E:v*1e3)!==null&&f!==void 0?f:NaN;D($)&&!isNaN($)&&e.next($)}const g=(m=b["x-delivery-type"])!==null&&m!==void 0?m:vs.HTTP1,y=(S={1:!0,0:!1}[b["x-reused"]])!==null&&S!==void 0?S:void 0;i.next(g),r.next(y)},d=l=>{l.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return s.extend("XHRLoader",function(){const{parent:l}=this,c=l.load.bind(l);return{load:function(h){if(h.request.type==="MPD"){const f=h.onload,m=h.progress;h.onload=function(...S){return u(this),f(...S)},h.progress=function(...S){return d(this),m(...S)},o()}return c(h)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:i}},ii=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},Cp=s=>s.extend("RequestModifier",()=>({modifyRequestURL:ii}),!0),Bp=s=>{s.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[r,a]=i.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(i.request.url,location.href);n.searchParams.append("bytes",`${r}-${a}`),i.request.url=n.toString(),i.request.range=void 0}t(i)}}},!0)};const vt=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=s.getState(),o=e(),u=j(r),d=new ue;return r&&d.add(r.subscribe(l=>{const c=s.getState();i(l,c)&&s.setState(l)},a)),i(o,n)||(t(n),u&&s.setState(n)),d.add(s.stateChangeStarted$.subscribe(l=>{t(l.to),u&&s.setState(l.to)},a)),d},ri=(s,e,t)=>vt(e,()=>s.loop,i=>{D(i)&&(s.loop=i)},{onError:t}),Dt=(s,e,t,i)=>vt(e,()=>({muted:s.muted,volume:s.volume}),r=>{D(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),Qt=(s,e,t,i)=>vt(e,()=>s.playbackRate,r=>{D(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Op=s=>["__",s.language,s.label].join("|"),Mp=(s,e)=>{if(s.id===e)return!0;const[t,i,r]=e.split("|");return s.language===i&&s.label===r};class yt{constructor(){this.available$=new C,this.current$=new T(void 0),this.error$=new C,this.subscription=new ue,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:R.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(vt(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{D(a)&&this.setInternal(a)},{equal:(a,n)=>D(a)&&D(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(_(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(vt(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{D(a)&&this.setExternal(a)},{equal:(a,n)=>D(a)&&D(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(_(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(vt(t.currentTextTrack,()=>{if(this.video)return;const a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(vt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){P(this.video);const{textTracks:e}=this.video;this.subscription.add(U(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(H(U(e,"addtrack"),U(e,"removetrack"),He(["init"])).pipe(_(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),ve((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(H(U(e,"change"),He(["init"])).pipe(_(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),_(i=>i&&this.htmlTextTrackToITextTrack(i).id),ve()).subscribe(this.current$));const t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(U(e,"addtrack").subscribe(i=>{var r,a;(r=i.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var u,d,l,c,h;const f=(d=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&d!==void 0?d:null;f&&f.length&&(this.applyCueSettings((c=(l=o.target)===null||l===void 0?void 0:l.cues)!==null&&c!==void 0?c:null),(h=o.target)===null||h===void 0||h.removeEventListener("cuechange",n))};(a=i.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(U(e,"removetrack").subscribe(i=>{var r;(r=i.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const r=i;D(t.align)&&(r.align=t.align),D(t.position)&&(r.position=t.position),D(t.size)&&(r.size=t.size),D(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){P(this.video);const t=[...this.video.textTracks];return e?t:t.filter(yt.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,i;const{language:r,label:a}=e,n=e.id?e.id:Op(e),o=this.externalTracks.has(n),u=n.includes("auto");return o?{id:n,type:"external",isAuto:u,language:r,label:a,url:(t=this.externalTracks.get(n))===null||t===void 0?void 0:t.url}:{id:n,type:"internal",isAuto:u,language:r,label:a,url:(i=this.internalTracks.get(n))===null||i===void 0?void 0:i.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){P(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(j(e)||!Mp(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 on=s=>{s.removeAttribute("src"),s.load()},Np=s=>{try{s.pause(),s.playbackRate=0,on(s),s.remove()}catch(e){console.error(e)}};class Fp{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 Na=window.WeakMap?new WeakMap:new Fp,Rt=s=>{let e=s.querySelector("video");const t=!!e;return e?on(e):(e=document.createElement("video"),s.appendChild(e)),Na.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},It=s=>{const e=Na.get(s);Na.delete(s),e?on(s):Np(s)};class As{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 wd=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},no=s=>{const e=wd(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},Up=s=>{const e=wd(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)},Fa=3;class Vp{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<Fa&&(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||Fa))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 _d=(s,e,t=Fa)=>{let i=0,r=0;for(let a=0;a<s.length;a++){const n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};const Lt=s=>{const e=v=>U(s,v).pipe(Hi(void 0)),i=H(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>U(s,v))).pipe(_(v=>v.type==="ended"?s.readyState<2:s.readyState<3),ve()),r=H(U(s,"progress"),U(s,"timeupdate")).pipe(_(()=>_d(s.buffered,s.currentTime))),n=hr().browser===qa.Safari?Le({play:e("play").pipe(Ae()),playing:e("playing")}).pipe(Hi(void 0)):e("playing"),o=U(s,"volumechange").pipe(_(()=>({muted:s.muted,volume:s.volume}))),u=U(s,"ratechange").pipe(_(()=>s.playbackRate)),d=U(s,"error").pipe(ae(()=>!!(s.error||s.played.length)),_(()=>{var v;const E=s.error;return{id:E?`MediaError#${E.code}`:"HtmlVideoError",category:R.VIDEO_PIPELINE,message:E?E.message:"Error event from HTML video element",thrown:(v=s.error)!==null&&v!==void 0?v:void 0}})),l=U(s,"timeupdate").pipe(_(()=>s.currentTime)),c=new C,h=.3;let f;l.subscribe(v=>{s.loop&&D(f)&&D(v)&&f>=s.duration-h&&v<=h&&c.next(f),f=v});const m=U(s,"enterpictureinpicture"),S=U(s,"leavepictureinpicture"),b=new T(Up(s));m.subscribe(()=>b.next(!0)),S.subscribe(()=>b.next(!1));const g=new T(no(s));return U(s,"fullscreenchange").pipe(_(()=>no(s))).subscribe(g),{playing$:n,pause$:e("pause").pipe(ae(()=>!s.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:U(s,"durationchange").pipe(_(()=>s.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:o,playbackRateState$:u,inPiP$:b,inFullscreen$:g}},Er=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var Hp=yr,Gp=Sr,Yp=an,qp=rn;Hp({target:"Array",proto:!0},{at:function(e){var t=Gp(this),i=Yp(t),r=qp(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});var zp=Qa,Pd=zp,jp=Pd,Wp=jp("Array","at"),Qp=Wp,Kp=Qp,Jp=Kp,Xp=Jp,Ie=za(Xp);let dn=!1,Vt={};const Zp=s=>{dn=s},em=()=>{Vt={}},tm=s=>{s(Vt)},Bs=(s,e)=>{var t;dn&&(Vt.meta=(t=Vt.meta)!==null&&t!==void 0?t:{},Vt.meta[s]=e)};class kt{constructor(e){this.name=e}next(e){var t,i;if(!dn)return;Vt.series=(t=Vt.series)!==null&&t!==void 0?t:{};const r=(i=Vt.series[this.name])!==null&&i!==void 0?i:[];r.push([Date.now(),e]),Vt.series[this.name]=r}}var vi;(function(s){s.FitsContainer="FitsContainer",s.FitsThroughput="FitsThroughput",s.Buffer="Buffer",s.DroppedFramesLimit="DroppedFramesLimit",s.FitsQualityLimits="FitsQualityLimits"})(vi||(vi={}));const im=new kt("best_bitrate"),sm=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class Dd{constructor(){this.history={}}recordSelection(e){this.history[e.id]=le()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const rm='Assertion "ABR Tracks is empty array" failed',_i=(s,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:d,droppedVideoMaxQualityLimit:l,abrLogger:c})=>{var h,f,m,S,b;ru(s,rm);const g=i.usePixelRatio&&(h=window.devicePixelRatio)!==null&&h!==void 0?h:1,y=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*g*i.containerSizeFactor,height:e.height*g*i.containerSizeFactor},v=y&&si(y),E=i.considerPlaybackRate&&D(o)?o:1,$=s.filter(M=>!yi(M.quality)).sort((M,x)=>Vi(M.quality,x.quality)?-1:1),L=(f=Ie($,-1))===null||f===void 0?void 0:f.quality,G=(m=Ie($,0))===null||m===void 0?void 0:m.quality,Q=j(r)||D(r.min)&&D(r.max)&&qs(r.max,r.min)||D(r.min)&&G&&Vi(r.min,G)||D(r.max)&&L&&qs(r.max,L),V=E*sm(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),z={},B=$.filter(M=>(v?qs(M.quality,v):!0)?(D(t)&&isFinite(t)&&D(M.bitrate)?t-a>=M.bitrate*V:!0)?i.lazyQualitySwitch&&D(i.minBufferToSwitchUp)&&u&&!yi(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Vi(M.quality,u.quality)?(z[M.quality]=vi.Buffer,!1):!!l&&Pa(M.quality,l)?(z[M.quality]=vi.DroppedFramesLimit,!1):Q||(j(r.max)||Mo(M.quality,r.max))&&(j(r.min)||Pa(M.quality,r.min))?!0:(z[M.quality]=vi.FitsQualityLimits,!1):(z[M.quality]=vi.FitsThroughput,!1):(z[M.quality]=vi.FitsContainer,!1))[0];B&&B.bitrate&&im.next(B.bitrate);const O=(S=B!=null?B:$[Math.ceil(($.length-1)/2)])!==null&&S!==void 0?S:s[0];O.quality!==((b=d==null?void 0:d.last)===null||b===void 0?void 0:b.quality)&&c({message:`
|
|
6
|
+
import{ValueSubject as T,Subject as C,Subscription as ue,isNonNullable as D,ErrorCategory as R,isNullable as j,fromEvent as U,assertNever as z,merge as H,tap as vs,map as _,observableFrom as Ge,filterChanged as ve,assertNonNullable as P,debounce as st,getHighestQuality as ru,timeout as au,getCurrentBrowser as hr,CurrentClientBrowser as ja,combine as Le,once as Ae,mapTo as Hi,filter as ae,now as le,assertNotEmptyArray as nu,videoSizeToQuality as si,isInvariantQuality as yi,isHigher as Vi,isLower as qs,isHigherOrEqual as Ra,isLowerOrEqual as Fo,Observable as fr,debounceFn as ou,interval as Ti,VideoQuality as at,videoQualityToHeight as du,abortable as ce,getExponentialDelay as ms,throttle as uu,isIOS as lu,CurrentClientDevice as cu,safeStorage as Fr,fillWithDefault as hu,Logger as fu}from"@vkontakte/videoplayer-shared/es2018.esm.js";import{Observable as lb,Subject as cb,Subscription as hb,ValueSubject as fb,VideoQuality as pb}from"@vkontakte/videoplayer-shared/es2018.esm.js";const pu="2.0.98-dev.489417ae.0";var p;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(p||(p={}));var A;(function(s){s.MPEG="MPEG",s.DASH="DASH",s.DASH_SEP="DASH_SEP",s.DASH_SEP_VK="DASH_SEP",s.DASH_WEBM="DASH_WEBM",s.DASH_WEBM_AV1="DASH_WEBM_AV1",s.DASH_WEBM_VK="DASH_WEBM",s.DASH_ONDEMAND="DASH_ONDEMAND",s.DASH_ONDEMAND_VK="DASH_ONDEMAND",s.DASH_LIVE="DASH_LIVE",s.DASH_LIVE_CMAF="DASH_LIVE_CMAF",s.DASH_LIVE_WEBM="DASH_LIVE_WEBM",s.HLS="HLS",s.HLS_ONDEMAND="HLS_ONDEMAND",s.HLS_JS="HLS",s.HLS_LIVE="HLS_LIVE",s.HLS_LIVE_CMAF="HLS_LIVE_CMAF",s.WEB_RTC_LIVE="WEB_RTC_LIVE"})(A||(A={}));var Ue;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(Ue||(Ue={}));var Ce;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})(Ce||(Ce={}));var Ss;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(Ss||(Ss={}));var ee;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(ee||(ee={}));var Zt;(function(s){s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip"})(Zt||(Zt={}));var mu=s=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class gu{constructor(e){var t;this.connection$=new T(void 0),this.castState$=new T(Ce.NOT_AVAILABLE),this.errorEvent$=new C,this.realCastState$=new T(Ce.NOT_AVAILABLE),this.subscription=new ue,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const i="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${i}`}),e.isDisabled||!i)return;const r=D((t=window.chrome)===null||t===void 0?void 0:t.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||mu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:R.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())===null||i===void 0?void 0:i.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||a===void 0||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){D(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();j(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();j(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(U(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(a=i.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return z(r.sessionState)}})).add(H(U(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(vs(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),_(r=>r.castState)),Ge([i.getCastState()])).pipe(ve(),_(vu),vs(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===Ce.CONNECTED,o=D(this.connection$.getValue());if(n&&!o){const u=i.getCurrentSession();P(u);const d=u.getCastDevice(),l=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(j(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===Ce.CONNECTED?D(this.connection$.getValue())?Ce.CONNECTED:Ce.AVAILABLE:r)}))}initializeCastApi(){var e;let t,i,r;try{t=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:i,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:R.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const vu=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return Ce.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return Ce.AVAILABLE;case cast.framework.CastState.CONNECTING:return Ce.CONNECTING;case cast.framework.CastState.CONNECTED:return Ce.CONNECTED;default:return z(s)}};var Ur=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Wa(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var zt=function(s){try{return!!s()}catch(e){return!0}},Su=zt,pr=!Su(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),Uo=pr,Vo=Function.prototype,Ia=Vo.call,bu=Uo&&Vo.bind.bind(Ia,Ia),qt=Uo?bu:function(s){return function(){return Ia.apply(s,arguments)}},Ho=qt,yu=Ho({}.toString),Tu=Ho("".slice),mr=function(s){return Tu(yu(s),8,-1)},Eu=qt,$u=zt,Au=mr,Vr=Object,wu=Eu("".split),ku=$u(function(){return!Vr("z").propertyIsEnumerable(0)})?function(s){return Au(s)=="String"?wu(s,""):Vr(s)}:Vr,gr=function(s){return s==null},_u=gr,Pu=TypeError,Qa=function(s){if(_u(s))throw Pu("Can't call method on "+s);return s},Du=ku,Ru=Qa,Es=function(s){return Du(Ru(s))},Wi={},Ps=function(s){return s&&s.Math==Math&&s},St=Ps(typeof globalThis=="object"&&globalThis)||Ps(typeof window=="object"&&window)||Ps(typeof self=="object"&&self)||Ps(typeof Ur=="object"&&Ur)||function(){return this}()||Ur||Function("return this")(),La=typeof document=="object"&&document.all,Iu=typeof La=="undefined"&&La!==void 0,Go={all:La,IS_HTMLDDA:Iu},Yo=Go,Lu=Yo.all,ct=Yo.IS_HTMLDDA?function(s){return typeof s=="function"||s===Lu}:function(s){return typeof s=="function"},xu=St,Cu=ct,gn=xu.WeakMap,Bu=Cu(gn)&&/native code/.test(String(gn)),vn=ct,zo=Go,Mu=zo.all,Ai=zo.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:vn(s)||s===Mu}:function(s){return typeof s=="object"?s!==null:vn(s)},Ou=zt,wi=!Ou(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Qi={},Nu=St,Sn=Ai,xa=Nu.document,Fu=Sn(xa)&&Sn(xa.createElement),qo=function(s){return Fu?xa.createElement(s):{}},Uu=wi,Vu=zt,Hu=qo,jo=!Uu&&!Vu(function(){return Object.defineProperty(Hu("div"),"a",{get:function(){return 7}}).a!=7}),Gu=wi,Yu=zt,Wo=Gu&&Yu(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),zu=Ai,qu=String,ju=TypeError,ki=function(s){if(zu(s))return s;throw ju(qu(s)+" is not an object")},Wu=pr,Ds=Function.prototype.call,jt=Wu?Ds.bind(Ds):function(){return Ds.apply(Ds,arguments)},Ka={},Hr=Ka,Gr=St,Qu=ct,bn=function(s){return Qu(s)?s:void 0},Ja=function(s,e){return arguments.length<2?bn(Hr[s])||bn(Gr[s]):Hr[s]&&Hr[s][e]||Gr[s]&&Gr[s][e]},Ku=qt,Xa=Ku({}.isPrototypeOf),Ju=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Qo=St,Yr=Ju,yn=Qo.process,Tn=Qo.Deno,En=yn&&yn.versions||Tn&&Tn.version,$n=En&&En.v8,gt,Js;$n&&(gt=$n.split("."),Js=gt[0]>0&>[0]<4?1:+(gt[0]+gt[1]));!Js&&Yr&&(gt=Yr.match(/Edge\/(\d+)/),(!gt||gt[1]>=74)&&(gt=Yr.match(/Chrome\/(\d+)/),gt&&(Js=+gt[1])));var Xu=Js,An=Xu,Zu=zt,el=St,tl=el.String,Ko=!!Object.getOwnPropertySymbols&&!Zu(function(){var s=Symbol();return!tl(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&An&&An<41}),il=Ko,Jo=il&&!Symbol.sham&&typeof Symbol.iterator=="symbol",sl=Ja,rl=ct,al=Xa,nl=Jo,ol=Object,Xo=nl?function(s){return typeof s=="symbol"}:function(s){var e=sl("Symbol");return rl(e)&&al(e.prototype,ol(s))},dl=String,Za=function(s){try{return dl(s)}catch(e){return"Object"}},ul=ct,ll=Za,cl=TypeError,en=function(s){if(ul(s))return s;throw cl(ll(s)+" is not a function")},hl=en,fl=gr,vr=function(s,e){var t=s[e];return fl(t)?void 0:hl(t)},zr=jt,qr=ct,jr=Ai,pl=TypeError,ml=function(s,e){var t,i;if(e==="string"&&qr(t=s.toString)&&!jr(i=zr(t,s))||qr(t=s.valueOf)&&!jr(i=zr(t,s))||e!=="string"&&qr(t=s.toString)&&!jr(i=zr(t,s)))return i;throw pl("Can't convert object to primitive value")},Zo={exports:{}},wn=St,gl=Object.defineProperty,vl=function(s,e){try{gl(wn,s,{value:e,configurable:!0,writable:!0})}catch(t){wn[s]=e}return e},Sl=St,bl=vl,kn="__core-js_shared__",yl=Sl[kn]||bl(kn,{}),ed=yl,_n=ed;(Zo.exports=function(s,e){return _n[s]||(_n[s]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"});var td=Zo.exports,Tl=Qa,El=Object,Sr=function(s){return El(Tl(s))},$l=qt,Al=Sr,wl=$l({}.hasOwnProperty),Wt=Object.hasOwn||function(e,t){return wl(Al(e),t)},kl=qt,_l=0,Pl=Math.random(),Dl=kl(1 .toString),id=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Dl(++_l+Pl,36)},Rl=St,Il=td,Pn=Wt,Ll=id,xl=Ko,Cl=Jo,Ni=Rl.Symbol,Wr=Il("wks"),Bl=Cl?Ni.for||Ni:Ni&&Ni.withoutSetter||Ll,bt=function(s){return Pn(Wr,s)||(Wr[s]=xl&&Pn(Ni,s)?Ni[s]:Bl("Symbol."+s)),Wr[s]},Ml=jt,Dn=Ai,Rn=Xo,Ol=vr,Nl=ml,Fl=bt,Ul=TypeError,Vl=Fl("toPrimitive"),Hl=function(s,e){if(!Dn(s)||Rn(s))return s;var t=Ol(s,Vl),i;if(t){if(e===void 0&&(e="default"),i=Ml(t,s,e),!Dn(i)||Rn(i))return i;throw Ul("Can't convert object to primitive value")}return e===void 0&&(e="number"),Nl(s,e)},Gl=Hl,Yl=Xo,tn=function(s){var e=Gl(s,"string");return Yl(e)?e:e+""},zl=wi,ql=jo,jl=Wo,Rs=ki,In=tn,Wl=TypeError,Qr=Object.defineProperty,Ql=Object.getOwnPropertyDescriptor,Kr="enumerable",Jr="configurable",Xr="writable";Qi.f=zl?jl?function(e,t,i){if(Rs(e),t=In(t),Rs(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Xr in i&&!i[Xr]){var r=Ql(e,t);r&&r[Xr]&&(e[t]=i.value,i={configurable:Jr in i?i[Jr]:r[Jr],enumerable:Kr in i?i[Kr]:r[Kr],writable:!1})}return Qr(e,t,i)}:Qr:function(e,t,i){if(Rs(e),t=In(t),Rs(i),ql)try{return Qr(e,t,i)}catch(r){}if("get"in i||"set"in i)throw Wl("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var br=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},Kl=wi,Jl=Qi,Xl=br,$s=Kl?function(s,e,t){return Jl.f(s,e,Xl(1,t))}:function(s,e,t){return s[e]=t,s},Zl=td,ec=id,Ln=Zl("keys"),sn=function(s){return Ln[s]||(Ln[s]=ec(s))},rn={},tc=Bu,sd=St,ic=Ai,sc=$s,Zr=Wt,ea=ed,rc=sn,ac=rn,xn="Object already initialized",Ca=sd.TypeError,nc=sd.WeakMap,Xs,bs,Zs,oc=function(s){return Zs(s)?bs(s):Xs(s,{})},dc=function(s){return function(e){var t;if(!ic(e)||(t=bs(e)).type!==s)throw Ca("Incompatible receiver, "+s+" required");return t}};if(tc||ea.state){var Et=ea.state||(ea.state=new nc);Et.get=Et.get,Et.has=Et.has,Et.set=Et.set,Xs=function(s,e){if(Et.has(s))throw Ca(xn);return e.facade=s,Et.set(s,e),e},bs=function(s){return Et.get(s)||{}},Zs=function(s){return Et.has(s)}}else{var Ii=rc("state");ac[Ii]=!0,Xs=function(s,e){if(Zr(s,Ii))throw Ca(xn);return e.facade=s,sc(s,Ii,e),e},bs=function(s){return Zr(s,Ii)?s[Ii]:{}},Zs=function(s){return Zr(s,Ii)}}var uc={set:Xs,get:bs,has:Zs,enforce:oc,getterFor:dc},lc=pr,rd=Function.prototype,Cn=rd.apply,Bn=rd.call,cc=typeof Reflect=="object"&&Reflect.apply||(lc?Bn.bind(Cn):function(){return Bn.apply(Cn,arguments)}),hc=mr,fc=qt,ad=function(s){if(hc(s)==="Function")return fc(s)},nd={},od={},dd={}.propertyIsEnumerable,ud=Object.getOwnPropertyDescriptor,pc=ud&&!dd.call({1:2},1);od.f=pc?function(e){var t=ud(this,e);return!!t&&t.enumerable}:dd;var mc=wi,gc=jt,vc=od,Sc=br,bc=Es,yc=tn,Tc=Wt,Ec=jo,Mn=Object.getOwnPropertyDescriptor;nd.f=mc?Mn:function(e,t){if(e=bc(e),t=yc(t),Ec)try{return Mn(e,t)}catch(i){}if(Tc(e,t))return Sc(!gc(vc.f,e,t),e[t])};var $c=zt,Ac=ct,wc=/#|\.prototype\./,As=function(s,e){var t=_c[kc(s)];return t==Dc?!0:t==Pc?!1:Ac(e)?$c(e):!!e},kc=As.normalize=function(s){return String(s).replace(wc,".").toLowerCase()},_c=As.data={},Pc=As.NATIVE="N",Dc=As.POLYFILL="P",Rc=As,On=ad,Ic=en,Lc=pr,xc=On(On.bind),ld=function(s,e){return Ic(s),e===void 0?s:Lc?xc(s,e):function(){return s.apply(e,arguments)}},Is=St,Cc=cc,Bc=ad,Mc=ct,Oc=nd.f,Nc=Rc,Li=Ka,Fc=ld,xi=$s,Nn=Wt,Uc=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return Cc(s,this,arguments)};return e.prototype=s.prototype,e},yr=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?Is:r?Is[t]:(Is[t]||{}).prototype,o=i?Li:Li[t]||xi(Li,t,{})[t],u=o.prototype,d,l,c,h,f,m,S,b,v;for(h in e)d=Nc(i?h:t+(r?".":"#")+h,s.forced),l=!d&&n&&Nn(n,h),m=o[h],l&&(s.dontCallGetSet?(v=Oc(n,h),S=v&&v.value):S=n[h]),f=l&&S?S:e[h],!(l&&typeof m==typeof f)&&(s.bind&&l?b=Fc(f,Is):s.wrap&&l?b=Uc(f):a&&Mc(f)?b=Bc(f):b=f,(s.sham||f&&f.sham||m&&m.sham)&&xi(b,"sham",!0),xi(o,h,b),a&&(c=t+"Prototype",Nn(Li,c)||xi(Li,c,{}),xi(Li[c],h,f),s.real&&u&&(d||!u[h])&&xi(u,h,f)))},Ba=wi,Vc=Wt,cd=Function.prototype,Hc=Ba&&Object.getOwnPropertyDescriptor,an=Vc(cd,"name"),Gc=an&&function(){}.name==="something",Yc=an&&(!Ba||Ba&&Hc(cd,"name").configurable),zc={EXISTS:an,PROPER:Gc,CONFIGURABLE:Yc},hd={},qc=Math.ceil,jc=Math.floor,Wc=Math.trunc||function(e){var t=+e;return(t>0?jc:qc)(t)},Qc=Wc,nn=function(s){var e=+s;return e!==e||e===0?0:Qc(e)},Kc=nn,Jc=Math.max,Xc=Math.min,Zc=function(s,e){var t=Kc(s);return t<0?Jc(t+e,0):Xc(t,e)},eh=nn,th=Math.min,ih=function(s){return s>0?th(eh(s),9007199254740991):0},sh=ih,on=function(s){return sh(s.length)},rh=Es,ah=Zc,nh=on,Fn=function(s){return function(e,t,i){var r=rh(e),a=nh(r),n=ah(i,a),o;if(s&&t!=t){for(;a>n;)if(o=r[n++],o!=o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}},oh={includes:Fn(!0),indexOf:Fn(!1)},dh=qt,ta=Wt,uh=Es,lh=oh.indexOf,ch=rn,Un=dh([].push),hh=function(s,e){var t=uh(s),i=0,r=[],a;for(a in t)!ta(ch,a)&&ta(t,a)&&Un(r,a);for(;e.length>i;)ta(t,a=e[i++])&&(~lh(r,a)||Un(r,a));return r},fd=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],fh=hh,ph=fd,mh=Object.keys||function(e){return fh(e,ph)},gh=wi,vh=Wo,Sh=Qi,bh=ki,yh=Es,Th=mh;hd.f=gh&&!vh?Object.defineProperties:function(e,t){bh(e);for(var i=yh(t),r=Th(t),a=r.length,n=0,o;a>n;)Sh.f(e,o=r[n++],i[o]);return e};var Eh=Ja,$h=Eh("document","documentElement"),Ah=ki,wh=hd,Vn=fd,kh=rn,_h=$h,Ph=qo,Dh=sn,Hn=">",Gn="<",Ma="prototype",Oa="script",pd=Dh("IE_PROTO"),ia=function(){},md=function(s){return Gn+Oa+Hn+s+Gn+"/"+Oa+Hn},Yn=function(s){s.write(md("")),s.close();var e=s.parentWindow.Object;return s=null,e},Rh=function(){var s=Ph("iframe"),e="java"+Oa+":",t;return s.style.display="none",_h.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(md("document.F=Object")),t.close(),t.F},Ls,js=function(){try{Ls=new ActiveXObject("htmlfile")}catch(e){}js=typeof document!="undefined"?document.domain&&Ls?Yn(Ls):Rh():Yn(Ls);for(var s=Vn.length;s--;)delete js[Ma][Vn[s]];return js()};kh[pd]=!0;var gd=Object.create||function(e,t){var i;return e!==null?(ia[Ma]=Ah(e),i=new ia,ia[Ma]=null,i[pd]=e):i=js(),t===void 0?i:wh.f(i,t)},Ih=zt,Lh=!Ih(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),xh=Wt,Ch=ct,Bh=Sr,Mh=sn,Oh=Lh,zn=Mh("IE_PROTO"),Na=Object,Nh=Na.prototype,vd=Oh?Na.getPrototypeOf:function(s){var e=Bh(s);if(xh(e,zn))return e[zn];var t=e.constructor;return Ch(t)&&e instanceof t?t.prototype:e instanceof Na?Nh:null},Fh=$s,Sd=function(s,e,t,i){return i&&i.enumerable?s[e]=t:Fh(s,e,t),s},Uh=zt,Vh=ct,Hh=Ai,Gh=gd,qn=vd,Yh=Sd,zh=bt,Fa=zh("iterator"),bd=!1,Ht,sa,ra;[].keys&&(ra=[].keys(),"next"in ra?(sa=qn(qn(ra)),sa!==Object.prototype&&(Ht=sa)):bd=!0);var qh=!Hh(Ht)||Uh(function(){var s={};return Ht[Fa].call(s)!==s});qh?Ht={}:Ht=Gh(Ht);Vh(Ht[Fa])||Yh(Ht,Fa,function(){return this});var yd={IteratorPrototype:Ht,BUGGY_SAFARI_ITERATORS:bd},jh=bt,Wh=jh("toStringTag"),Td={};Td[Wh]="z";var dn=String(Td)==="[object z]",Qh=dn,Kh=ct,Ws=mr,Jh=bt,Xh=Jh("toStringTag"),Zh=Object,ef=Ws(function(){return arguments}())=="Arguments",tf=function(s,e){try{return s[e]}catch(t){}},Tr=Qh?Ws:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=tf(e=Zh(s),Xh))=="string"?t:ef?Ws(e):(i=Ws(e))=="Object"&&Kh(e.callee)?"Arguments":i},sf=dn,rf=Tr,af=sf?{}.toString:function(){return"[object "+rf(this)+"]"},nf=dn,of=Qi.f,df=$s,uf=Wt,lf=af,cf=bt,jn=cf("toStringTag"),Ed=function(s,e,t,i){if(s){var r=t?s:s.prototype;uf(r,jn)||of(r,jn,{configurable:!0,value:e}),i&&!nf&&df(r,"toString",lf)}},hf=yd.IteratorPrototype,ff=gd,pf=br,mf=Ed,gf=Wi,vf=function(){return this},Sf=function(s,e,t,i){var r=e+" Iterator";return s.prototype=ff(hf,{next:pf(+!i,t)}),mf(s,r,!1,!0),gf[r]=vf,s},bf=yr,yf=jt,$d=zc,Tf=Sf,Ef=vd,$f=Ed,Wn=Sd,Af=bt,Qn=Wi,Ad=yd,wf=$d.PROPER;$d.CONFIGURABLE;Ad.IteratorPrototype;var xs=Ad.BUGGY_SAFARI_ITERATORS,aa=Af("iterator"),Kn="keys",Cs="values",Jn="entries",kf=function(){return this},_f=function(s,e,t,i,r,a,n){Tf(t,e,i);var o=function(v){if(v===r&&h)return h;if(!xs&&v in l)return l[v];switch(v){case Kn:return function(){return new t(this,v)};case Cs:return function(){return new t(this,v)};case Jn:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,l=s.prototype,c=l[aa]||l["@@iterator"]||r&&l[r],h=!xs&&c||o(r),f=e=="Array"&&l.entries||c,m,S,b;if(f&&(m=Ef(f.call(new s)),m!==Object.prototype&&m.next&&($f(m,u,!0,!0),Qn[u]=kf)),wf&&r==Cs&&c&&c.name!==Cs&&(d=!0,h=function(){return yf(c,this)}),r)if(S={values:o(Cs),keys:a?h:o(Kn),entries:o(Jn)},n)for(b in S)(xs||d||!(b in l))&&Wn(l,b,S[b]);else bf({target:e,proto:!0,forced:xs||d},S);return n&&l[aa]!==h&&Wn(l,aa,h,{name:r}),Qn[e]=h,S},Pf=function(s,e){return{value:s,done:e}},Df=Es,Xn=Wi,wd=uc;Qi.f;var Rf=_f,Bs=Pf,kd="Array Iterator",If=wd.set,Lf=wd.getterFor(kd);Rf(Array,"Array",function(s,e){If(this,{type:kd,target:Df(s),index:0,kind:e})},function(){var s=Lf(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,Bs(void 0,!0)):t=="keys"?Bs(i,!1):t=="values"?Bs(e[i],!1):Bs([i,e[i]],!1)},"values");Xn.Arguments=Xn.Array;var xf=bt,Cf=Wi,Bf=xf("iterator"),Mf=Array.prototype,Of=function(s){return s!==void 0&&(Cf.Array===s||Mf[Bf]===s)},Nf=Tr,Zn=vr,Ff=gr,Uf=Wi,Vf=bt,Hf=Vf("iterator"),_d=function(s){if(!Ff(s))return Zn(s,Hf)||Zn(s,"@@iterator")||Uf[Nf(s)]},Gf=jt,Yf=en,zf=ki,qf=Za,jf=_d,Wf=TypeError,Qf=function(s,e){var t=arguments.length<2?jf(s):e;if(Yf(t))return zf(Gf(t,s));throw Wf(qf(s)+" is not iterable")},Kf=jt,eo=ki,Jf=vr,Xf=function(s,e,t){var i,r;eo(s);try{if(i=Jf(s,"return"),!i){if(e==="throw")throw t;return t}i=Kf(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return eo(i),t},Zf=ld,ep=jt,tp=ki,ip=Za,sp=Of,rp=on,to=Xa,ap=Qf,np=_d,io=Xf,op=TypeError,Qs=function(s,e){this.stopped=s,this.result=e},so=Qs.prototype,dp=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=Zf(e,i),d,l,c,h,f,m,S,b=function(y){return d&&io(d,"normal",y),new Qs(!0,y)},v=function(y){return r?(tp(y),o?u(y[0],y[1],b):u(y[0],y[1])):o?u(y,b):u(y)};if(a)d=s.iterator;else if(n)d=s;else{if(l=np(s),!l)throw op(ip(s)+" is not iterable");if(sp(l)){for(c=0,h=rp(s);h>c;c++)if(f=v(s[c]),f&&to(so,f))return f;return new Qs(!1)}d=ap(s,l)}for(m=a?s.next:d.next;!(S=ep(m,d)).done;){try{f=v(S.value)}catch(y){io(d,"throw",y)}if(typeof f=="object"&&f&&to(so,f))return f}return new Qs(!1)},up=tn,lp=Qi,cp=br,hp=function(s,e,t){var i=up(e);i in s?lp.f(s,i,cp(0,t)):s[i]=t},fp=yr,pp=dp,mp=hp;fp({target:"Object",stat:!0},{fromEntries:function(e){var t={};return pp(e,function(i,r){mp(t,i,r)},{AS_ENTRIES:!0}),t}});var gp=Ka,vp=gp.Object.fromEntries,Sp={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},bp=Sp,yp=St,Tp=Tr,Ep=$s,ro=Wi,$p=bt,ao=$p("toStringTag");for(var na in bp){var no=yp[na],oa=no&&no.prototype;oa&&Tp(oa)!==ao&&Ep(oa,ao,na),ro[na]=ro.Array}var Ap=vp,wp=Ap,kp=wp,_p=kp,Ei=Wa(_p),Se;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",s[s.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(Se||(Se={}));var He=(s,e=0,t=Se.OFFSET_P)=>{switch(t){case Se.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Se.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case Se.DASH_CMAF_OFFSET_P:{const i=new URL(s);return!i.searchParams.get("offset_p")&&e===0?s:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:z(t)}return s};const er=(s,e)=>{var t;switch(e){case Se.OFFSET_P:return NaN;case Se.PLAYBACK_SHIFT:{const i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case Se.DASH_CMAF_OFFSET_P:{const i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:z(e)}};var I=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};class he{constructor(e){this.transitionStarted$=new C,this.transitionEnded$=new C,this.transitionUpdated$=new C,this.forceChanged$=new C,this.stateChangeStarted$=H(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=H(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||D(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const Pp=s=>{switch(s){case A.MPEG:case A.DASH:case A.DASH_SEP:case A.DASH_ONDEMAND:case A.DASH_WEBM:case A.DASH_WEBM_AV1:case A.HLS:case A.HLS_ONDEMAND:return!1;case A.DASH_LIVE:case A.DASH_LIVE_CMAF:case A.HLS_LIVE:case A.HLS_LIVE_CMAF:case A.DASH_LIVE_WEBM:case A.WEB_RTC_LIVE:return!0;default:return z(s)}};var X;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(X||(X={}));const Dp=5,Rp=5,Ip=500,oo=7e3;class Lp{constructor(e){this.subscription=new ue,this.loadMediaTimeoutSubscription=new ue,this.videoState=new he(X.STOPPED),this.syncPlayback=()=>{const i=this.videoState.getState(),r=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${a}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(o)};`}),a===p.STOPPED){i!==X.STOPPED&&(this.videoState.startTransitionTo(X.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==p.PAUSED&&o.state===ee.Requested&&i!==X.STOPPED){this.seek(o.position/1e3);return}switch(a){case p.READY:{switch(i){case X.PLAYING:case X.PAUSED:case X.READY:break;case X.STOPPED:this.videoState.startTransitionTo(X.READY),this.prepare();break;default:z(i)}break}case p.PLAYING:{switch(i){case X.PLAYING:break;case X.PAUSED:this.videoState.startTransitionTo(X.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case X.READY:this.videoState.startTransitionTo(X.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case X.STOPPED:this.videoState.startTransitionTo(X.READY),this.prepare();break;default:z(i)}break}case p.PAUSED:{switch(i){case X.PLAYING:this.videoState.startTransitionTo(X.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case X.PAUSED:break;case X.READY:this.videoState.startTransitionTo(X.PAUSED),this.videoState.setState(X.PAUSED);break;case X.STOPPED:this.videoState.startTransitionTo(X.READY),this.prepare();break;default:z(i)}break}default:z(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Pp(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new ue;this.subscription.add(e),this.subscription.add(H(this.videoState.stateChangeStarted$.pipe(_(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(_(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));const t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const r=new C;e.add(r.pipe(st(Ip)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===ee.Applying||Math.abs(o-a)>Dp)&&r.next(o),a=o})),e.add(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<Rp&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),I(this.params.desiredState.playbackState,p.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:z(n)}}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const i=H(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ge(["init"])).pipe(st(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(X.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):(this.videoState.setState(X.PLAYING),I(this.params.desiredState.playbackState,p.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:ee.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===X.PAUSED||e===X.PLAYING)&&(this.videoState.setState(X.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===X.PLAYING||e===X.PAUSED)&&(this.videoState.setState(X.PLAYING),I(this.params.desiredState.playbackState,p.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===X.READY&&this.videoState.setState(X.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===p.READY&&I(this.params.desiredState.playbackState,p.READY)}handleRemoteStop(){this.videoState.getState()!==X.STOPPED&&this.videoState.setState(X.STOPPED)}handleRemoteVolumeChange(e){var t,i;const r=this.params.output.volume$.getValue(),a={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(i=e.muted)!==null&&i!==void 0?i:r.muted};(a.volume!==r.volume||a.muted!==a.muted)&&this.params.output.volume$.next(a)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const i=this.params.source;let r,a,n;switch(e){case A.MPEG:{const l=i[e];P(l);const c=ru(Object.keys(l));P(c);const h=l[c];P(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case A.HLS:case A.HLS_ONDEMAND:{const l=i[e];P(l),r=l.url,a="application/x-mpegurl",n=chrome.cast.media.StreamType.BUFFERED;break}case A.DASH_SEP:case A.DASH_ONDEMAND:case A.DASH_WEBM:case A.DASH_WEBM_AV1:{const l=i[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case A.DASH_LIVE_CMAF:{const l=i[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case A.HLS_LIVE:case A.HLS_LIVE_CMAF:{const l=i[e];P(l),r=He(l.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case A.DASH:case A.DASH_LIVE:case A.WEB_RTC_LIVE:{const l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:R.VIDEO_PIPELINE,message:l,thrown:c}),c}case A.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return z(e)}const o=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,a);o.contentUrl=r,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return D(u)&&(o.metadata.title=u),D(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===ee.Applying||i.state===ee.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(au(oo).subscribe(()=>a(`timeout(${oo})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===ee.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{const a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:R.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}var xp=s=>{let e,t=!1,i=!1;s.on("playbackTimeUpdated",({timeToEnd:r})=>{i=r<=3,t&&i&&(e==null||e())}),s.extend("MediaSourceController",function(){const{parent:r}=this,a=r.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>a(n),t&&i&&(e==null||e())}}},!0)},Cp=s=>{const e=new T(1/0),t=new C,i=new T(void 0),r=new T(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},u=l=>{var c,h,f,m,S;const b=Ei(l.getAllResponseHeaders().trim().split(/[\n\r]+/).map(g=>g.split(": ")));if("x-playback-duration"in b||"x-playback-duration-millis"in b){const g=parseInt((c=l.getResponseHeader("X-Playback-Duration"))!==null&&c!==void 0?c:"",10),E=parseInt((h=l.getResponseHeader("X-Playback-Duration-Millis"))!==null&&h!==void 0?h:"",10),$=(f=E!=null?E:g*1e3)!==null&&f!==void 0?f:NaN;D($)&&!isNaN($)&&e.next($)}const v=(m=b["x-delivery-type"])!==null&&m!==void 0?m:Ss.HTTP1,y=(S={1:!0,0:!1}[b["x-reused"]])!==null&&S!==void 0?S:void 0;i.next(v),r.next(y)},d=l=>{l.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return s.extend("XHRLoader",function(){const{parent:l}=this,c=l.load.bind(l);return{load:function(h){if(h.request.type==="MPD"){const f=h.onload,m=h.progress;h.onload=function(...S){return u(this),f(...S)},h.progress=function(...S){return d(this),m(...S)},o()}return c(h)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:i}},ii=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},Bp=s=>s.extend("RequestModifier",()=>({modifyRequestURL:ii}),!0),Mp=s=>{s.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[r,a]=i.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(i.request.url,location.href);n.searchParams.append("bytes",`${r}-${a}`),i.request.url=n.toString(),i.request.range=void 0}t(i)}}},!0)};const vt=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=s.getState(),o=e(),u=j(r),d=new ue;return r&&d.add(r.subscribe(l=>{const c=s.getState();i(l,c)&&s.setState(l)},a)),i(o,n)||(t(n),u&&s.setState(n)),d.add(s.stateChangeStarted$.subscribe(l=>{t(l.to),u&&s.setState(l.to)},a)),d},ri=(s,e,t)=>vt(e,()=>s.loop,i=>{D(i)&&(s.loop=i)},{onError:t}),Dt=(s,e,t,i)=>vt(e,()=>({muted:s.muted,volume:s.volume}),r=>{D(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),Qt=(s,e,t,i)=>vt(e,()=>s.playbackRate,r=>{D(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Op=s=>["__",s.language,s.label].join("|"),Np=(s,e)=>{if(s.id===e)return!0;const[t,i,r]=e.split("|");return s.language===i&&s.label===r};class yt{constructor(){this.available$=new C,this.current$=new T(void 0),this.error$=new C,this.subscription=new ue,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:R.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(vt(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{D(a)&&this.setInternal(a)},{equal:(a,n)=>D(a)&&D(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(_(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(vt(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{D(a)&&this.setExternal(a)},{equal:(a,n)=>D(a)&&D(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(_(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(vt(t.currentTextTrack,()=>{if(this.video)return;const a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(vt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){P(this.video);const{textTracks:e}=this.video;this.subscription.add(U(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(H(U(e,"addtrack"),U(e,"removetrack"),Ge(["init"])).pipe(_(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),ve((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(H(U(e,"change"),Ge(["init"])).pipe(_(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),_(i=>i&&this.htmlTextTrackToITextTrack(i).id),ve()).subscribe(this.current$));const t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(U(e,"addtrack").subscribe(i=>{var r,a;(r=i.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var u,d,l,c,h;const f=(d=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&d!==void 0?d:null;f&&f.length&&(this.applyCueSettings((c=(l=o.target)===null||l===void 0?void 0:l.cues)!==null&&c!==void 0?c:null),(h=o.target)===null||h===void 0||h.removeEventListener("cuechange",n))};(a=i.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(U(e,"removetrack").subscribe(i=>{var r;(r=i.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const r=i;D(t.align)&&(r.align=t.align),D(t.position)&&(r.position=t.position),D(t.size)&&(r.size=t.size),D(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){P(this.video);const t=[...this.video.textTracks];return e?t:t.filter(yt.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,i;const{language:r,label:a}=e,n=e.id?e.id:Op(e),o=this.externalTracks.has(n),u=n.includes("auto");return o?{id:n,type:"external",isAuto:u,language:r,label:a,url:(t=this.externalTracks.get(n))===null||t===void 0?void 0:t.url}:{id:n,type:"internal",isAuto:u,language:r,label:a,url:(i=this.internalTracks.get(n))===null||i===void 0?void 0:i.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){P(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(j(e)||!Np(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){P(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){P(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const un=s=>{s.removeAttribute("src"),s.load()},Fp=s=>{try{s.pause(),s.playbackRate=0,un(s),s.remove()}catch(e){console.error(e)}};class Up{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}}const Ua=window.WeakMap?new WeakMap:new Up,Rt=s=>{let e=s.querySelector("video");const t=!!e;return e?un(e):(e=document.createElement("video"),s.appendChild(e)),Ua.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},It=s=>{const e=Ua.get(s);Ua.delete(s),e?un(s):Fp(s)};class ws{constructor(){this.pausedTime=0,this.streamOffset=0,this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}}const Pd=s=>{var e;let t=s;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},uo=s=>{const e=Pd(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},Vp=s=>{const e=Pd(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)},Va=3;class Hp{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let r=this._source.buffered.start(t);const a=this._source.buffered.end(t);r>e&&r-e<Va&&(r=e),this._buffer.push({from:r,to:a,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||Va))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:r,to:a})=>{const n=r>=e&&r<t,o=a>=e&&a<t;n&&o||(n?i(t,a):o?i(r,e):r<e&&a>t?(i(t,a),i(r,e)):i(r,a))})}destroy(){this._buffer=[]}}var Dd=(s,e,t=Va)=>{let i=0,r=0;for(let a=0;a<s.length;a++){const n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};const Lt=s=>{const e=g=>U(s,g).pipe(Hi(void 0)),i=H(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(g=>U(s,g))).pipe(_(g=>g.type==="ended"?s.readyState<2:s.readyState<3),ve()),r=H(U(s,"progress"),U(s,"timeupdate")).pipe(_(()=>Dd(s.buffered,s.currentTime))),n=hr().browser===ja.Safari?Le({play:e("play").pipe(Ae()),playing:e("playing")}).pipe(Hi(void 0)):e("playing"),o=U(s,"volumechange").pipe(_(()=>({muted:s.muted,volume:s.volume}))),u=U(s,"ratechange").pipe(_(()=>s.playbackRate)),d=U(s,"error").pipe(ae(()=>!!(s.error||s.played.length)),_(()=>{var g;const E=s.error;return{id:E?`MediaError#${E.code}`:"HtmlVideoError",category:R.VIDEO_PIPELINE,message:E?E.message:"Error event from HTML video element",thrown:(g=s.error)!==null&&g!==void 0?g:void 0}})),l=U(s,"timeupdate").pipe(_(()=>s.currentTime)),c=new C,h=.3;let f;l.subscribe(g=>{s.loop&&D(f)&&D(g)&&f>=s.duration-h&&g<=h&&c.next(f),f=g});const m=U(s,"enterpictureinpicture"),S=U(s,"leavepictureinpicture"),b=new T(Vp(s));m.subscribe(()=>b.next(!0)),S.subscribe(()=>b.next(!1));const v=new T(uo(s));return U(s,"fullscreenchange").pipe(_(()=>uo(s))).subscribe(v),{playing$:n,pause$:e("pause").pipe(ae(()=>!s.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:U(s,"durationchange").pipe(_(()=>s.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:o,playbackRateState$:u,inPiP$:b,inFullscreen$:v}},Er=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var Gp=yr,Yp=Sr,zp=on,qp=nn;Gp({target:"Array",proto:!0},{at:function(e){var t=Yp(this),i=zp(t),r=qp(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});var jp=Ja,Rd=jp,Wp=Rd,Qp=Wp("Array","at"),Kp=Qp,Jp=Kp,Xp=Jp,Zp=Xp,Ie=Wa(Zp);let ln=!1,Vt={};const em=s=>{ln=s},tm=()=>{Vt={}},im=s=>{s(Vt)},Ms=(s,e)=>{var t;ln&&(Vt.meta=(t=Vt.meta)!==null&&t!==void 0?t:{},Vt.meta[s]=e)};class wt{constructor(e){this.name=e}next(e){var t,i;if(!ln)return;Vt.series=(t=Vt.series)!==null&&t!==void 0?t:{};const r=(i=Vt.series[this.name])!==null&&i!==void 0?i:[];r.push([Date.now(),e]),Vt.series[this.name]=r}}var vi;(function(s){s.FitsContainer="FitsContainer",s.FitsThroughput="FitsThroughput",s.Buffer="Buffer",s.DroppedFramesLimit="DroppedFramesLimit",s.FitsQualityLimits="FitsQualityLimits"})(vi||(vi={}));const sm=new wt("best_bitrate"),rm=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class Id{constructor(){this.history={}}recordSelection(e){this.history[e.id]=le()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const am='Assertion "ABR Tracks is empty array" failed',_i=(s,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:d,droppedVideoMaxQualityLimit:l,abrLogger:c})=>{var h,f,m,S,b;nu(s,am);const v=i.usePixelRatio&&(h=window.devicePixelRatio)!==null&&h!==void 0?h:1,y=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*v*i.containerSizeFactor,height:e.height*v*i.containerSizeFactor},g=y&&si(y),E=i.considerPlaybackRate&&D(o)?o:1,$=s.filter(O=>!yi(O.quality)).sort((O,x)=>Vi(O.quality,x.quality)?-1:1),L=(f=Ie($,-1))===null||f===void 0?void 0:f.quality,G=(m=Ie($,0))===null||m===void 0?void 0:m.quality,Q=j(r)||D(r.min)&&D(r.max)&&qs(r.max,r.min)||D(r.min)&&G&&Vi(r.min,G)||D(r.max)&&L&&qs(r.max,L),V=E*rm(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),q={},B=$.filter(O=>(g?qs(O.quality,g):!0)?(D(t)&&isFinite(t)&&D(O.bitrate)?t-a>=O.bitrate*V:!0)?i.lazyQualitySwitch&&D(i.minBufferToSwitchUp)&&u&&!yi(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Vi(O.quality,u.quality)?(q[O.quality]=vi.Buffer,!1):!!l&&Ra(O.quality,l)?(q[O.quality]=vi.DroppedFramesLimit,!1):Q||(j(r.max)||Fo(O.quality,r.max))&&(j(r.min)||Ra(O.quality,r.min))?!0:(q[O.quality]=vi.FitsQualityLimits,!1):(q[O.quality]=vi.FitsThroughput,!1):(q[O.quality]=vi.FitsContainer,!1))[0];B&&B.bitrate&&sm.next(B.bitrate);const M=(S=B!=null?B:$[Math.ceil(($.length-1)/2)])!==null&&S!==void 0?S:s[0];M.quality!==((b=d==null?void 0:d.last)===null||b===void 0?void 0:b.quality)&&c({message:`
|
|
7
7
|
[available tracks]
|
|
8
|
-
${s.map(
|
|
8
|
+
${s.map(O=>`{ id: ${O.id}, quality: ${O.quality}, bitrate: ${O.bitrate} }`).join(`
|
|
9
9
|
`)}
|
|
10
10
|
|
|
11
11
|
[tuning]
|
|
12
|
-
${Object.entries(i!=null?i:{}).map(([
|
|
12
|
+
${Object.entries(i!=null?i:{}).map(([O,x])=>`${O}: ${x}`).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[limit params]
|
|
16
|
-
containerQualityLimit: ${
|
|
16
|
+
containerQualityLimit: ${g},
|
|
17
17
|
throughput: ${t},
|
|
18
18
|
reserve: ${a},
|
|
19
19
|
playbackRate: ${o},
|
|
@@ -27,20 +27,20 @@ import{ValueSubject as T,Subject as C,Subscription as ue,isNonNullable as D,Erro
|
|
|
27
27
|
minQualityLimit: ${r==null?void 0:r.min},
|
|
28
28
|
|
|
29
29
|
[limited tracks]
|
|
30
|
-
${Object.entries(
|
|
30
|
+
${Object.entries(q).map(([O,x])=>`${O}: ${x}`).join(`
|
|
31
31
|
`)||"All tracks are available"}
|
|
32
32
|
|
|
33
33
|
[best track] ${B==null?void 0:B.quality}
|
|
34
|
-
[selected track] ${
|
|
35
|
-
`});const K=
|
|
36
|
-
[last selected] ${
|
|
37
|
-
`}),M}return d==null||d.recordSwitch(O),O};var Ge=s=>new URL(s).hostname;const am=300,bs=(s,e=am)=>new fr(t=>{const{width:i,height:r}=s.getBoundingClientRect();if(t.next({width:i,height:r}),!window.ResizeObserver)return;const a=new ResizeObserver(cu(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),D(u)&&D(d)&&t.next({width:u,height:d})},e));return a.observe(s),()=>a.disconnect()});class ks{constructor(){this.onDroopedVideoFramesLimit$=new C,this.subscription=new ue,this.playing=!1,this.tracks=[],this.forceChecker$=new C,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&&!yi(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&&Vi(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(U(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=Ti(this.droppedFramesChecker.checkTime).pipe(ae(()=>this.playing),ae(()=>{const r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(it(this.droppedFramesChecker.checkTime)),i=H(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])=>qs(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 ds={};var re;(function(s){s.DOWNLOADING_LIB="downloading_lib",s.STOPPED="stopped",s.STREAM_INITIALIZED="stream_initialized",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(re||(re={}));const _e=(s,e)=>new fr(t=>{const i=r=>t.next(r);return s.on(e,i),()=>s.off(e,i)});class oo{constructor(e){this.subscription=new ue,this.videoState=new he(re.DOWNLOADING_LIB),this.textTracksManager=new yt,this.droppedFramesManager=new ks,this.videoTracks$=new T([]),this.frameRatesByFrameHeight={},this.isLive$=new T(void 0),this.maxSeekBackTime$=new T(1/0),this.availableFrom$=new T(void 0),this.elementSize$=new T(void 0),this.liveOffset=new As,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===re.DOWNLOADING_LIB||t===re.STREAM_INITIALIZED))switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===ee.Requested&&t!==re.STOPPED&&i!==p.STOPPED&&(n?this.seek(a.position-this.liveOffset.getTotalPausedTime()):this.seek(a.position)),i){case p.STOPPED:{switch(t){case re.STOPPED:break;case re.PLAYING:case re.PAUSED:case re.READY:this.stop();break;default:q(t)}break}case p.READY:{switch(t){case re.STOPPED:this.prepare();break;case re.PLAYING:case re.PAUSED:case re.READY:break;default:q(t)}break}case p.PLAYING:{switch(t){case re.PLAYING:break;case re.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 re.READY:this.play();break;case re.STOPPED:this.prepare();break;default:q(t)}break}case p.PAUSED:{switch(t){case re.PLAYING:this.pause(),this.liveOffset.pause();break;case re.PAUSED:break;case re.READY:this.videoState.setState(re.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED);break;case re.STOPPED:this.prepare();break;default:q(t)}break}default:q(i)}},this.video=Rt(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(Ge(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:R.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||(ds.MediaPlayer=r.MediaPlayer,ds.Debug=r.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){P(ds.MediaPlayer,"dashjs not loaded"),P(ds.Debug,"dashjs not loaded"),this.player=ds.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?Er(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&Bp(this.player),Lp(this.player),this.params.tuning.requestQuick&&Cp(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(re.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=v=>{e.error$.next({id:"DashIFProvider",category:R.WTF,message:"DashIFProvider internal logic error",thrown:v})},r=(v,E)=>this.subscription.add(v.subscribe(E,i));r(bs(this.video),this.elementSize$),r(_e(this.player,"error").pipe(_(v=>{const E=typeof v.error=="object"?v.error.code:v.error,$=typeof v.error=="object"?v.error.message:void 0;return{id:`DashJS#${E}`,message:$}})),e.error$),r(_e(this.player,"playbackError").pipe(_(v=>({id:"DashJSPlayback",message:v.error}))),e.error$);const a=_e(this.player,"qualityChangeRendered").pipe(ae(({mediaType:v})=>v==="video"),_(({newQuality:v})=>{var E;return(E=this.videoTracks$.getValue().find(({bitrateInfo:$})=>$.qualityIndex===v))===null||E===void 0?void 0:E.track}));a.pipe(ae(D)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(ae(({to:v})=>v===re.STREAM_INITIALIZED),Ae()).subscribe(()=>{this.subscription.add(vt(t.videoTrack,()=>{var v;const E=this.player.getQualityFor("video");return(v=this.videoTracks$.getValue().find(({bitrateInfo:$})=>$.qualityIndex===E))===null||v===void 0?void 0:v.track},v=>{var E;if(j(v))return;const $=(E=this.videoTracks$.getValue().find(({track:L})=>L.id===v.id))===null||E===void 0?void 0:E.bitrateInfo;$&&this.player.setQualityFor("video",$.qualityIndex)},{changed$:a,onError:i}))},i)),this.subscription.add(vt(t.autoVideoTrackSwitching,()=>{var v,E,$;return($=(E=(v=this.player.getSettings().streaming)===null||v===void 0?void 0:v.abr)===null||E===void 0?void 0:E.autoSwitchBitrate)===null||$===void 0?void 0:$.video},v=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:v}}}}),{onError:i})),r(_e(this.player,"bufferStateChanged").pipe(ae(({mediaType:v})=>v==="video"),_(({state:v})=>v==="bufferStalled")),e.isBuffering$),r(_e(this.player,"fragmentLoadingStarted"),({mediaType:v,request:{url:E}})=>{var $,L;const G=this.player.getDashMetrics(),Q=G.getLatestFragmentRequestHeaderValueByID(v,"X-Reused"),V=($=G.getLatestFragmentRequestHeaderValueByID(v,"X-Delivery-Type"))!==null&&$!==void 0?$:vs.HTTP1,z=(L={1:!0,0:!1}[Q])!==null&&L!==void 0?L:void 0;this.params.output.httpConnectionType$.next(V),this.params.output.httpConnectionReused$.next(z),e.hostname$.next(Ge(E))}),r(_e(this.player,"streamInitialized"),({streamInfo:{duration:v,manifestInfo:{isDynamic:E,availableFrom:$}}})=>{this.isLive$.next(E),this.availableFrom$.next($.getTime()),E||e.duration$.next(v);const L=[],G=this.player.getQualityFor("video");let Q;for(const V of this.player.getBitrateInfoListFor("video")){const z=V.qualityIndex.toString(10),W=si(V),B=V.bitrate/1e3,O={width:V.width,height:V.height},K=this.frameRatesByFrameHeight[V.height];if(W){const M={id:z,quality:W,bitrate:B,size:O,fps:K};L.push({track:M,bitrateInfo:V}),V.qualityIndex===G&&(Q=M)}}this.videoTracks$.next(L),e.availableVideoTracks$.next(L.map(({track:V})=>V)),Q&&e.currentVideoTrack$.next(Q),this.videoState.setState(re.STREAM_INITIALIZED),this.videoState.startTransitionTo(re.READY)}),r(_e(this.player,"fragmentLoadingCompleted"),({request:v})=>{if(!v.requestEndDate||!v.firstByteDate||!v.bytesLoaded)return;const E=v.requestEndDate.getTime()-v.firstByteDate.getTime(),$=v.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed($,E)}),r(H(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeStarted$,this.droppedFramesManager.onDroopedVideoFramesLimit$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks$.getValue().length)return;const v=this.params.dependencies.throughputEstimator.throughput$.getValue(),E=_i(this.videoTracks$.getValue().map(({track:G})=>G),{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 L=this.videoTracks$.getValue().find(({track:G})=>G===E);L!=null&&L.bitrateInfo&&this.player.setQualityFor("video",L==null?void 0:L.bitrateInfo.qualityIndex,!1)}),r(Le({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(ae(D))}).pipe(ae(({isLive:v})=>v),_(({maxSeekBackTime:v})=>-v/1e3)),this.params.output.duration$);const n=_e(this.player,"playbackTimeUpdated").pipe(_(({time:v})=>v!=null?v:0));r(Le({availableFrom:this.availableFrom$.pipe(ae(D)),currentTime:n}),({availableFrom:v,currentTime:E})=>this.params.output.liveTime$.next(v+E*1e3)),r(n.pipe(ae(()=>this.isLive$.getValue()===!1)),e.position$),r(_e(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),r(_e(this.player,"playbackEnded"),e.endedEvent$),r(_e(this.player,"playbackProgress").pipe(_(()=>_d(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(_e(this.player,"playbackPlaying"),()=>{this.videoState.setState(re.PLAYING),I(t.playbackState,p.PLAYING)}),r(_e(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(re.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(_e(this.player,"playbackPaused"),()=>{this.videoState.setState(re.PAUSED),I(t.playbackState,p.PAUSED)}),r(_e(this.player,"canPlay"),()=>{var v;((v=this.videoState.getTransition())===null||v===void 0?void 0:v.to)===re.READY&&this.videoState.setState(re.READY)}),r(this.isLive$,e.isLive$),r(bs(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=H(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,He(["init"])).pipe(it(0));r(o,this.syncPlayback);const{playbackDuration$:u,ping$:d,connectionType$:l,connectionReused$:c}=xp(this.player);r(l,this.params.output.httpConnectionType$),r(c,this.params.output.httpConnectionReused$),r(u,this.maxSeekBackTime$),r(d.pipe(Ae()),e.firstBytesEvent$),r(_e(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(Le({isLive:this.isLive$,isShort:e.duration$.pipe(_(v=>v<60))}),({isLive:v,isShort:E})=>{const $=!v&&E;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:$}}})}),r(n.pipe(ae(v=>v>this.params.tuning.insufficientBufferRuleMargin),Ae()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(_e(this.player,"manifestLoaded").pipe(Ae()).subscribe(()=>{this.subscription.add(_e(this.player,"playbackPlaying").pipe(Ae(),Hi(void 0)).subscribe(e.firstFrameEvent$,i))},i)),r(_e(this.player,"manifestLoaded"),v=>{var E,$,L,G,Q,V,z;if(!(($=(E=v.data)===null||E===void 0?void 0:E.Period)===null||$===void 0)&&$.AdaptationSet){const W=[];for(const B of(G=(L=v.data)===null||L===void 0?void 0:L.Period)===null||G===void 0?void 0:G.AdaptationSet)if(B.contentType==="text"){const O=(Q=B.Representation)===null||Q===void 0?void 0:Q.id,K=new URL((V=B.Representation)===null||V===void 0?void 0:V.BaseURL,(z=v.data)===null||z===void 0?void 0:z.baseUri).toString(),M="internal",x=B.lang;W.push({id:O,url:K,type:M,language:x})}t.internalTextTracks.startTransitionTo(W)}}),this.subscription.add(ri(this.video,t.isLooped,i));const{volumeState$:h,looped$:f,playbackRateState$:m,inPiP$:S,inFullscreen$:b,pause$:g,playing$:y}=Lt(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:y,pause$:g,tracks$:this.videoTracks$.pipe(_(v=>v.map(({track:E})=>E)))}),this.subscription.add(Dt(this.video,t.volume,h,i)),this.subscription.add(h.subscribe(e.volume$,i)),this.subscription.add(f.subscribe(e.loopedEvent$)),this.subscription.add(Qt(this.video,t.playbackRate,m,i)),this.subscription.add(S.subscribe(e.inPiP$)),this.subscription.add(b.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(re.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(re.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=Ve(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Se.PLAYBACK_SHIFT);this.player.attachSource(r)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(re.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(re.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){}It(this.video),this.params.output.element$.next(void 0)}}var Ki=s=>{switch(s){case"mobile":return rt.Q_144P;case"lowest":return rt.Q_240P;case"low":return rt.Q_360P;case"sd":case"medium":return rt.Q_480P;case"hd":case"high":return rt.Q_720P;case"fullhd":case"full":return rt.Q_1080P;case"quadhd":case"quad":return rt.Q_1440P;case"ultrahd":case"ultra":return rt.Q_2160P}};const uo=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 Kt=async s=>{const e=s.muted;try{await s.play()}catch(t){if(!uo(t))return!1;if(e)return console.warn(t),!1;s.muted=!0;try{await s.play()}catch(i){return uo(i)&&(s.muted=!1,console.warn(i)),!1}}return!0};function Ue(){return le()}function Rd(s){return Ue()-s}function lo(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 nm(s,e,t){const i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Qs(s,e,t,i){const r=window.XMLHttpRequest;let a,n,o,u=!1,d=0,l,c,h=!1,f="arraybuffer",m=7e3,S=2e3,b=()=>{if(u)return;P(l);const B=Rd(l);let O;if(B<S){O=S-B,setTimeout(b,O);return}S*=2,S>m&&(S=m),n&&n.abort(),n=new r,L()};const g=B=>(a=B,W),y=B=>(c=B,W),v=()=>(f="json",W),E=()=>{if(!u){if(--d>=0){b(),i&&i();return}u=!0,c&&c(),t&&t()}},$=B=>(h=B,W),L=()=>{l=Ue(),n=new r,n.open("get",s);let B=0,O,K=0;const M=()=>(P(l),Math.max(l,Math.max(O||0,K||0)));if(a&&n.addEventListener("progress",x=>{const Y=Ue();a.updateChunk&&x.loaded>B&&(a.updateChunk(M(),x.loaded-B),B=x.loaded,O=Y)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(u)return;P(n);const x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&a){const Y=n.response.byteLength-B;Y&&a.updateChunk&&a.updateChunk(M(),Y)}c&&c(),n&&e(n.response)}else E()}),n.addEventListener("error",()=>{E()}),h){const x=()=>{P(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(K=Ue(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=f,n.send(),W},W={withBitrateReporting:g,withParallel:$,withJSONResponse:v,withRetryCount:B=>(d=B,W),withRetryInterval:(B,O)=>(D(B)&&(S=B),D(O)&&(m=O),W),withTimeout:B=>(o=B,W),withFinally:y,send:L,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return W}const om=100,dm=2e3,um=500;let lm=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-um;if(t-e>dm){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>om&&(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 cm{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=Ue(),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=Ue()-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=Qs(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=Ue()}_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=Ue();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 Os=1e4,Ms=3,hm=300,fm=2e3,pm=6e4,mm=10,gm=1,vm=500;class Sm{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 lm(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=lo(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=lo(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||D(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=()=>{nm(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 cm(Ms,Os,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 E=a&&(!l||l===this.rep);return E||t("Not running!"),E},h=(E,$,L)=>{u&&u.abort(),u=Qs(this.urlResolver.resolve(E,!1),$,L,()=>this._retryCallback()).withTimeout(Os).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ms).withFinally(()=>{u=null}).send()},f=(E,$,L)=>{P(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),$,L,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=E=>{const $=i.playbackRate;i.playbackRate!==E&&(t(`Playback rate switch: ${$}=>${E}`),i.playbackRate=E)},S=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}const L=Ue()-1e4;let G=0;for(let V=0;V<this.bufferStates.length;V++){const z=this.bufferStates[V];E=Math.min(E,z.buf),z.ts<L&&G++}this.bufferStates.splice(0,G),t(`update playback rate; minBuffer=${E} drop=${G} jitter=${this.sourceJitter}`);let Q=E-gm;this.sourceJitter>=0?Q-=this.sourceJitter/2:this.sourceJitter-=1,Q>3?m(1.15):Q>1?m(1.1):Q>.3?m(1.05):m(1)}},g=E=>{let $;const L=()=>$&&$.start?$.start.length:0,G=x=>$.start[x]/1e3,Q=x=>$.dur[x]/1e3,V=x=>$.fragIndex+x,z=(x,Y)=>({chunkIdx:V(x),startTS:G(x),dur:Q(x),discontinuity:Y}),W=()=>{let x=0;if($&&$.dur){let Y=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,te=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,fe=Y;this.sourceJitter>1&&(fe+=this.sourceJitter-1);let be=$.dur.length-1;for(;be>=0&&(fe-=$.dur[be],!(fe<=0));--be);x=Math.min(be,$.dur.length-1-te),x=Math.max(x,0)}return z(x,!0)},B=x=>{const Y=L();if(!(Y<=0)){if(D(x)){for(let te=0;te<Y;te++)if(G(te)>x)return z(te)}return W()}},O=x=>{const Y=L(),te=x?x.chunkIdx+1:0,fe=te-$.fragIndex;if(!(Y<=0)){if(!x||fe<0||fe-Y>mm)return t(`Resync: offset=${fe} bChunks=${Y} chunk=`+JSON.stringify(x)),W();if(!(fe>=Y))return z(te-$.fragIndex,!1)}},K=(x,Y,te)=>{d&&d.abort(),d=Qs(this.urlResolver.resolve(x,!0,this.lowLatency),Y,te,()=>this._retryCallback()).withTimeout(Os).withRetryCount(Ms).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(x,Y)=>{K(E,te=>{if(!c())return;$=te;const fe=!!$.lowLatency;fe!==this.lowLatency&&S(fe);let be=0;for(let Pe=0;Pe<$.dur.length;++Pe)be+=$.dur[Pe];be>0&&(P(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(be/$.dur.length)),r({name:"index",zeroTime:$.zeroTime,shiftDuration:$.shiftDuration}),this.sourceJitter=$.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,$.jitter/1e3)):1,x(B(Y))},()=>this._handleNetworkError())},nextChunk:O}},y=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),P(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:E=>{const{videoElement:$,logger:L}=this.params;let G=g(e.jidxUrl),Q,V,z,W,B=0,O,K,M;const x=()=>{O&&(clearTimeout(O),O=void 0);const ie=Math.max(vm,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Oe=B+ie,qe=Ue(),De=Math.min(1e4,Oe-qe);B=qe;const ke=()=>{d||c()&&G.seek(()=>{c()&&(B=Ue(),Y(),x())})};De>0?O=window.setTimeout(()=>{this.paused?x():ke()},De):ke()},Y=()=>{let ie;for(;ie=G.nextChunk(W);)W=ie,Ye(ie);const Oe=G.nextChunk(z);if(Oe){if(z&&Oe.discontinuity){L("Detected discontinuity; restarting playback"),this.paused?x():(y(),this._initPlayerWith(e));return}Pe(Oe)}else x()},te=(ie,Oe)=>{if(!c()||!this.sourceBuffer)return;let qe,De,ke;const Ct=Bt=>{window.setTimeout(()=>{c()&&te(ie,Oe)},Bt)};if(this.sourceBuffer.updating)L("Source buffer is updating; delaying appendBuffer"),Ct(100);else{const Bt=Ue(),Xt=$.currentTime;!this.paused&&$.buffered.length>1&&K===Xt&&Bt-M>500&&(L("Stall suspected; trying to fix"),this._fixupStall()),K!==Xt&&(K=Xt,M=Bt);const Ot=this._getBufferSizeSec();if(Ot>30)L(`Buffered ${Ot} seconds; delaying appendBuffer`),Ct(2e3);else try{this.sourceBuffer.appendBuffer(ie),this.videoPlayStarted?(this.bufferStates.push({ts:Bt,buf:Ot}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Oe&&Oe()}catch(Pi){if(Pi.name==="QuotaExceededError")L("QuotaExceededError; delaying appendBuffer"),ke=this.sourceBuffer.buffered.length,ke!==0&&(qe=this.sourceBuffer.buffered.start(0),De=Xt,De-qe>4&&this.sourceBuffer.remove(qe,De-3)),Ct(1e3);else throw Pi}}},fe=()=>{V&&Q&&(L([`Appending chunk, sz=${V.byteLength}:`,JSON.stringify(z)]),te(V,function(){V=null,Y()}))},be=ie=>e.fragUrlTemplate.replace("%%id%%",ie.chunkIdx),Pe=ie=>{c()&&f(be(ie),(Oe,qe)=>{if(c()){if(qe/=1e3,V=Oe,z=ie,n=ie.startTS,qe){const De=Math.min(10,ie.dur/qe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*De:De}fe()}},()=>this._handleNetworkError())},Ye=ie=>{c()&&(P(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(be(ie),!1)))},st=ie=>{c()&&(e.cachedHeader=ie,te(ie,()=>{Q=!0,fe()}))};a=!0,G.seek(ie=>{if(c()){if(B=Ue(),!ie){x();return}W=ie,!j(E)||ie.startTS>E?Pe(ie):(z=ie,Y())}},E),e.cachedHeader?st(e.cachedHeader):h(e.headerUrl,st,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>n},l}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),D(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,P(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return D(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=Ue();if(this.chunkRateEstimator.addInterval(h,m,f)){const b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:m-h,speed:b}),!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&&Rd(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=Ue();c<o&&(n=h),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Qs(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Os).withRetryCount(Ms).withRetryInterval(hm,fm).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;Kt(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))},pm))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var se;(function(s){s.STOPPED="stopped",s.MANIFEST_READY="manifest_ready",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(se||(se={}));const bm=[se.PAUSED,se.PLAYING,se.READY],ym=[se.PAUSED,se.PLAYING,se.READY];class Tm{constructor(e){this.subscription=new ue,this.videoState=new he(se.STOPPED),this.representations$=new T([]),this.textTracksManager=new yt,this.droppedFramesManager=new ks,this.maxSeekBackTime$=new T(1/0),this.zeroTime$=new T(void 0),this.liveOffset=new As,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:R.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=Ki(c.name))!==null&&n!==void 0?n:si(c.video),m=c.bitrate/1e3,S={...c.video};if(!f)continue;const b={id:h,quality:f,bitrate:m,size:S};l.push({track:b,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)===se.MANIFEST_READY&&this.videoState.setState(se.MANIFEST_READY);break}case"qualitySwitch":{const d=r.quality,l=(u=this.representations$.getValue().find(({representation:c})=>c===d))===null||u===void 0?void 0:u.track;this.params.output.hostname$.next(new URL(d.headerUrl,this.params.source.url).hostname),D(l)&&this.params.output.currentVideoTrack$.next(l);break}case"bandwidth":{const{size:d,duration:l}=r;this.params.dependencies.throughputEstimator.addRawSpeed(d,l);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration||0),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{const r=this.videoState.getState(),a=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${r}; videoTransition: ${JSON.stringify(a)}; desiredPlaybackState: ${n}; seekState: ${JSON.stringify(u)};`}),n===p.STOPPED){r!==se.STOPPED&&(this.videoState.startTransitionTo(se.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(se.STOPPED));return}if(a)return;const d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(ym.includes(r)&&(d||l)){this.prepare();return}if((o==null?void 0:o.to)!==p.PAUSED&&u.state===ee.Requested&&bm.includes(r)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(r){case se.STOPPED:this.videoState.startTransitionTo(se.MANIFEST_READY),this.dash.attachSource(Ve(this.params.source.url));return;case se.MANIFEST_READY:this.videoState.startTransitionTo(se.READY),this.prepare();break;case se.READY:if(n===p.PAUSED)this.videoState.setState(se.PAUSED);else if(n===p.PLAYING){this.videoState.startTransitionTo(se.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(se.PAUSED)})}return;case se.PLAYING:n===p.PAUSED&&(this.videoState.startTransitionTo(se.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case se.PAUSED:if(n===p.PLAYING)if(this.videoState.startTransitionTo(se.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(se.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(Ve(this.params.source.url,c))}return;default:return q(r)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:R.WTF,message:"DashLiveProvider internal logic error",thrown:r})};H(this.videoState.stateChangeStarted$.pipe(_(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(_(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=Rt(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Ge(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=Lt(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(_(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)===se.READY&&this.videoState.setState(se.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(se.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===ee.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(se.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(ve(),_(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Le({zeroTime:this.zeroTime$.pipe(ae(D)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(ri(this.video,this.params.desiredState.isLooped,t)).add(Dt(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Qt(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&&au(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case se.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(p.STOPPED);break;case se.MANIFEST_READY:case se.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 se.PAUSED:this.params.desiredState.playbackState.setState(p.PAUSED);break;case se.PLAYING:this.params.desiredState.playbackState.setState(p.PLAYING);break;default:return q(r.to)}},t)).add(H(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,He(["init"])).pipe(it(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),It(this.video)}createLiveDashPlayer(){const e=new Sm({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&&D(u)?u:_i(o.map(({track:S})=>S),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),c=l==null?void 0:l.id,h=this.params.desiredState.videoTrack.getTransition(),f=(a=this.params.desiredState.videoTrack.getState())===null||a===void 0?void 0:a.id,m=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(h||c!==f)&&this.setVideoTrack(l),m&&this.setAutoQuality(d),h||m||c!==f){const S=(n=o.find(({track:b})=>b.id===c))===null||n===void 0?void 0:n.representation;P(S,"Representations missing"),this.dash.startPlay(S,d)}}setVideoTrack(e){var t;const i=(t=this.representations$.getValue().find(({track:r})=>r.id===e.id))===null||t===void 0?void 0:t.representation;P(i,`No such representation ${e.id}`),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===se.PAUSED,a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Ve(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}}var un=s=>{var e,t;const i=s.get("X-Delivery-Type"),r=s.get("X-Reused"),a=i===null?vs.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}},We=(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 Em=s=>{const e=document.createElement("a");return e.href=s,e.origin},$m=s=>{const e=document.createElement("a");return e.href=s,e.host};class Id{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=Ei(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($m(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 tr{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=S=>{r(tr._str2ua(S.substr(u))),u=S.length};let m=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(m=ii(m)),this._lastXhr=new Id(m,e.failoverHosts,S=>{this._lastXhr=void 0,f(S);const b=Date.now()-d;this._params.onBandwidthChange({size:S.length,duration:b,speed:8*S.length/(b/1e3)}),this._onDashCallback("loading",{size:S.length,done:!0}),a==null||a()},S=>{if(S.length-u>o&&f(S),c===0){c=Date.now();return}h=S.length-l;const b=Date.now()-c;h>=100*1024&&b>=1e3&&(this._params.onBandwidthChange({size:h,duration:b,speed:8*h/(b/1e3)}),h=0,l=S.length,c=Date.now()),this._onDashCallback("loading",{size:S.length,done:!1})},n,(S,b,g)=>this._params.onError(S,b,g))})}abort(e){var t;(t=this._lastXhr)===null||t===void 0||t.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e==null||e()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(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=tr._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 Am{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=ii(i)),new Id(i,t,r=>{this.attachManifest(r,t,Em(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,S,b,g,y,v,E,$,L,G,Q,V,z,W,B;const O=d.getElementsByTagName("SegmentBase")[0],K=O&&n(O,"indexRange").split("-"),M=O&&O.getElementsByTagName("Initialization")[0],x=M&&n(M,"range").split("-");if(!x||!K){const Ye=d.parentElement;if((Ye==null?void 0:Ye.getAttribute("contentType"))==="text"){const st=(l=d.getAttribute("id"))!==null&&l!==void 0?l:void 0,ie=(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),Oe=(S=Ye.getAttribute("lang"))!==null&&S!==void 0?S:void 0;ie&&u.push({id:st,url:ie,language:Oe})}return}const Y=.1,te=Number((b=d.attributes.getNamedItem("bandwidth"))===null||b===void 0?void 0:b.value),fe=(i?i+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let be;const Pe=(y=(g=d.attributes.getNamedItem("frameRate"))===null||g===void 0?void 0:g.value)!==null&&y!==void 0?y:void 0;be=Pe?Er(Pe):void 0,o.push({width:Number((v=d.attributes.getNamedItem("width"))===null||v===void 0?void 0:v.value),height:Number((E=d.attributes.getNamedItem("height"))===null||E===void 0?void 0:E.value),bandwidth:te,baseURL:fe,failoverHosts:t,indexFrom:Number(K[0]),indexTo:Number(K[1]),initFrom:Number(x[0]),initTo:Number(x[1]),codecs:(L=($=d.attributes.getNamedItem("codecs"))===null||$===void 0?void 0:$.value)!==null&&L!==void 0?L:void 0,mimeType:(Q=(G=d.attributes.getNamedItem("mimeType"))===null||G===void 0?void 0:G.value)!==null&&Q!==void 0?Q:void 0,fps:be,bufferSize:Y*te/8,bufferLength:Y,name:(z=(V=d.attributes.getNamedItem("okQuality"))===null||V===void 0?void 0:V.value)!==null&&z!==void 0?z:void 0,id:(B=(W=d.attributes.getNamedItem("id"))===null||W===void 0?void 0:W.value)!==null&&B!==void 0?B: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 tr({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||j(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 ne;(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"})(ne||(ne={}));const km=[ne.PAUSED,ne.PLAYING];class wm{constructor(e){this.videoState=new he(ne.STOPPED),this.subscription=new ue,this.representations$=new T([]),this.currentRepresentation$=new T(void 0),this.textTracksManager=new yt,this.droppedFramesManager=new ks,this.elementSize$=new T(void 0),this.dashLiteEvents={idxRequestPing$:new C,responseHeaders$:new C,manifestReady$:new C,representationPlay$:new C,error$:new C},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&&Ki(u.name))!==null&&n!==void 0?n:si(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(ne.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))},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!==ne.STOPPED&&(this.videoState.startTransitionTo(ne.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(ne.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(!i)switch((a==null?void 0:a.to)!==p.PAUSED&&n.state===ee.Requested&&km.includes(t)&&this.seek(n.position,n.forcePrecise),t){case ne.STOPPED:this.videoState.startTransitionTo(ne.MANIFEST_LOADED),this.prepare();return;case ne.MANIFEST_LOADED:this.videoState.startTransitionTo(ne.INITIAL_REPRESENTATION_SELECTED);return;case ne.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(ne.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case ne.METADATA_LOADED:this.videoState.startTransitionTo(ne.READY),this.dash.updateRefsForCurrentTime();return;case ne.READY:r===p.READY?I(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(ne.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(ne.PLAYING),this.playIfAllowed());return;case ne.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(ne.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case ne.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(ne.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return q(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),H(this.videoState.stateChangeStarted$.pipe(_(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(_(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=Rt(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(Ge(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Vp(this.video),this.dash=new Am({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:R.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:R.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=Lt(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(()=>{j(this.params.desiredState.seekState.getState().state!==ee.Applying)&&(this.videoState.getState()===ne.PLAYING||this.videoState.getState()===ne.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(ri(this.video,t.isLooped,i)),this.subscription.add(Dt(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Qt(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(_(o=>o.map(({track:u})=>u)))}),n(bs(this.video),this.elementSize$),this.subscription.add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ne.READY&&this.videoState.setState(ne.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(ne.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)})).add(a.playing$.subscribe(()=>{this.videoState.setState(ne.PLAYING),I(this.params.desiredState.playbackState,p.PLAYING)},i)).add(a.loadedMetadata$.subscribe(()=>{this.videoState.setState(ne.METADATA_LOADED)},i)).add(a.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},i)).add(this.dashLiteEvents.error$.pipe(_(({id:o,message:u,thrown:d})=>({id:`DashLite_${o}`,category:R.WTF,message:u,thrown:d}))).subscribe(this.params.output.error$)).add(H(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$,this.params.output.element$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,U(this.video,"progress")).pipe(_(()=>{var o,u,d,l;const c=this.currentRepresentation$.getValue(),h=this.representations$.getValue(),f=this.params.desiredState.autoVideoTrackSwitching.getTransition(),m=(o=this.params.desiredState.videoTrack.getState())===null||o===void 0?void 0:o.id,S=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),b=this.elementSize$.getValue(),g=r();f&&this.params.desiredState.autoVideoTrackSwitching.setState(f.to);let y;if(!g&&D(m))y=m;else{const v=We(this.video.buffered,this.video.currentTime*1e3),E=g?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,$=Math.min(v/E,1);y=(d=_i(h.map(({track:G})=>G),{container:b,throughput:S,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:$,playbackRate:this.video.playbackRate,current:(u=h.find(({representation:G})=>G===c))===null||u===void 0?void 0:u.track,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}))===null||d===void 0?void 0:d.id;const L=t.autoVideoTrackLimits.getTransition();L&&e.autoVideoTrackLimits$.next(L.to)}return D(y)?(l=h.find(({track:v})=>v.id===y))===null||l===void 0?void 0:l.representation:void 0}),ve()).subscribe(this.currentRepresentation$,i)).add(Le({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(ae(o=>o.to===ne.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(ae(D))}).pipe(Ae()).subscribe(()=>this.videoState.setState(ne.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(ae(D),ve((o,u)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?o.height<=u.height:o===u)).subscribe(o=>{const u=We(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(Ge(o.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:u,reused:d}=un(o);this.params.output.httpConnectionType$.next(u),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(Ae(),Hi(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(ae(D)).subscribe(this.handleRepresentationPlay,i)).add(H(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,He(["init"])).pipe(it(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),It(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 q(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){Kt(this.video).then(e=>{e||(this.videoState.setState(ne.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}}var Ce;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(Ce||(Ce={}));var ir;(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"})(ir||(ir={}));var ot;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(ot||(ot={}));var oe;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(oe||(oe={}));var Gi;(function(s){s.MP4="mp4",s.WEBM="webm"})(Gi||(Gi={}));var sr;(function(s){s[s.RECTANGULAR=0]="RECTANGULAR",s[s.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",s[s.CUBEMAP=2]="CUBEMAP",s[s.MESH=3]="MESH"})(sr||(sr={}));var Te;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Te||(Te={}));class co{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 Ld extends co{constructor(){super(),this.listeners||co.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 xd=class{constructor(){Object.defineProperty(this,"signal",{value:new Ld,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&&(xd.prototype[Symbol.toStringTag]="AbortController",Ld.prototype[Symbol.toStringTag]="AbortSignal");function Cd(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 _m(s){typeof s=="function"&&(s={fetch:s});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!Cd({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 $r=Cd({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Bd=$r?_m({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,$i=$r?Bd.fetch:window.fetch;$r?Bd.Request:window.Request;const ut=$r?xd:window.AbortController;var Yi=(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 Pm=(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)},Dm=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",rr=Dm?Pm:window.requestIdleCallback;var da,ua;const Rm=16;let Od=!1;try{Od=hr().browser===qa.Safari&&parseInt((ua=(da=navigator.userAgent.match(/Version\/(\d+)/))===null||da===void 0?void 0:da[1])!==null&&ua!==void 0?ua:"",10)<=Rm}catch(s){console.error(s)}let Im=class{constructor(e){this.bufferFull$=new C,this.error$=new C,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const i=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!i),this.currentTask=null}this.queue.length&&this.pull()}catch(i){this.error$.next({id:"BufferTaskQueueUnknown",category:R.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i;Od&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:i}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&i==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${i}`,category:R.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:q(t)}}};var ar=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};let xt=class{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}},Md=class extends xt{},Lm=class extends xt{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}}},xm=class extends xt{parseChildrenBoxes(){return Ji(this.content)}},Cm=class extends xt{constructor(e){super(e),this.data=this.content}},ws=class extends xt{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}},Bm=class extends ws{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})}}},Om=class extends xt{parseChildrenBoxes(){return Ji(this.content)}},Mm=class extends xt{parseChildrenBoxes(){return Ji(this.content)}};var Si;(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"})(Si||(Si={}));let Nm=class extends ws{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=Si.MONOSCOPIC;break;case 1:this.stereoMode=Si.TOP_BOTTOM;break;case 2:this.stereoMode=Si.LEFT_RIGHT;break;case 3:this.stereoMode=Si.STEREO_CUSTOM;break;case 4:this.stereoMode=Si.RIGHT_LEFT;break}this.cursor+=1}},Fm=class extends ws{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}},Um=class extends ws{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}},Vm=class extends xt{parseChildrenBoxes(){return Ji(this.content)}},Hm=class extends ws{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()}},Gm=class extends xt{parseChildrenBoxes(){return Ji(this.content)}},Ym=class extends xt{parseChildrenBoxes(){return Ji(this.content)}};const qm={ftyp:Lm,moov:xm,mdat:Cm,sidx:Bm,trak:Om,mdia:Vm,tkhd:Hm,minf:Gm,sv3d:Mm,st3d:Nm,prhd:Fm,proj:Ym,equi:Um,unknown:Md};let zm=class{createBox(e,t){const i=qm[e];return i?new i(t):new Md(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Ar.createBox(i,new DataView(e.buffer,e.byteOffset))}};const Ar=new zm;function fs(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:Ar.createBox(e,new DataView(s.buffer,i-7))}i++}return null}function jm(s,e){const t=[];let i=0;for(;i<s.byteLength;){const r=fs(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 Ji(s){const e=[];let t=0;for(;t<s.byteLength;){const i=Ar.createFromView(new DataView(s.buffer,s.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const Wm=new TextDecoder("ascii"),Qm=s=>Wm.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",Km=s=>{const e=Ar.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:oe.NONE,time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},Jm=s=>{const e=jm(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},Xm=s=>{const e={is3dVideo:!1,stereoMode:0,projectionType:sr.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(fs(s,"sv3d")){e.is3dVideo=!0;const i=fs(s,"st3d");i&&(e.stereoMode=i.stereoMode);const r=fs(s,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const a=fs(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},Zm={validateData:Qm,parseInit:Xm,getIndexRange:()=>{},parseSegments:Km,parseFeedableSegmentChunk:Jm};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 N;(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"})(N||(N={}));const ho={[k.EBML]:{type:N.Master},[k.EBMLVersion]:{type:N.UnsignedInteger},[k.EBMLReadVersion]:{type:N.UnsignedInteger},[k.EBMLMaxIDLength]:{type:N.UnsignedInteger},[k.EBMLMaxSizeLength]:{type:N.UnsignedInteger},[k.DocType]:{type:N.String},[k.DocTypeVersion]:{type:N.UnsignedInteger},[k.DocTypeReadVersion]:{type:N.UnsignedInteger},[k.Void]:{type:N.Binary},[k.Segment]:{type:N.Master},[k.SeekHead]:{type:N.Master},[k.Seek]:{type:N.Master},[k.SeekID]:{type:N.Binary},[k.SeekPosition]:{type:N.UnsignedInteger},[k.Info]:{type:N.Master},[k.TimestampScale]:{type:N.UnsignedInteger},[k.Duration]:{type:N.Float},[k.Tracks]:{type:N.Master},[k.TrackEntry]:{type:N.Master},[k.Video]:{type:N.Master},[k.Projection]:{type:N.Master},[k.ProjectionType]:{type:N.UnsignedInteger},[k.ProjectionPrivate]:{type:N.Master},[k.Chapters]:{type:N.Master},[k.Cluster]:{type:N.Master},[k.Timestamp]:{type:N.UnsignedInteger},[k.SilentTracks]:{type:N.Master},[k.SilentTrackNumber]:{type:N.UnsignedInteger},[k.Position]:{type:N.UnsignedInteger},[k.PrevSize]:{type:N.UnsignedInteger},[k.SimpleBlock]:{type:N.Binary},[k.BlockGroup]:{type:N.Master},[k.EncryptedBlock]:{type:N.Binary},[k.Attachments]:{type:N.Master},[k.Tags]:{type:N.Master},[k.Cues]:{type:N.Master},[k.CuePoint]:{type:N.Master},[k.CueTime]:{type:N.UnsignedInteger},[k.CueTrackPositions]:{type:N.Master},[k.CueTrack]:{type:N.UnsignedInteger},[k.CueClusterPosition]:{type:N.UnsignedInteger},[k.CueRelativePosition]:{type:N.UnsignedInteger},[k.CueDuration]:{type:N.UnsignedInteger},[k.CueBlockNumber]:{type:N.UnsignedInteger},[k.CueCodecState]:{type:N.UnsignedInteger},[k.CueReference]:{type:N.Master},[k.CueRefTime]:{type:N.UnsignedInteger}},Nd=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=nr(s,t),r=i in ho,a=r?ho[i].type:N.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=nr(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}},nr=(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},wt=(s,e)=>{switch(e){case N.SignedInteger:return s.getInt8(0);case N.UnsignedInteger:return nr(s);case N.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case N.String:return new TextDecoder("ascii").decode(s);case N.UTF8:return new TextDecoder("utf-8").decode(s);case N.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case N.Master:return s;case N.Binary:return s;default:q(e)}},qi=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=Nd(i);if(!e(r))return;r.type===N.Master&&qi(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},eg=s=>{if(s.getUint32(0)!==k.EBML)return!1;let e,t,i;const r=Nd(s);return qi(r.value,({tag:a,type:n,value:o})=>(a===k.EBMLReadVersion?e=wt(o,n):a===k.DocType?t=wt(o,n):a===k.DocTypeReadVersion&&(i=wt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Fd=[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],tg=[k.Timestamp,k.SilentTracks,k.SilentTrackNumber,k.Position,k.PrevSize,k.SimpleBlock,k.BlockGroup,k.EncryptedBlock],ig=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,d,l=!1;const c=0;return qi(s,({tag:h,type:f,value:m,valueSize:S})=>{if(h===k.SeekID){const b=wt(m,f);d=nr(b)}else h!==k.SeekPosition&&(d=void 0);return h===k.Segment?(e=m.byteOffset,t=m.byteOffset+S):h===k.Info?a=!0:h===k.SeekHead?n=!0:h===k.TimestampScale?i=wt(m,f):h===k.Duration?r=wt(m,f):h===k.SeekPosition&&d===k.Cues?u=wt(m,f):h===k.Tracks?qi(m,({tag:b,type:g,value:y})=>b===k.ProjectionType?(l=wt(y,g)===1,!1):!0):a&&n&&Fd.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:sr.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},sg=s=>{if(j(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},rg=(s,e)=>{let t=!1,i=!1;const r=o=>D(o.time)&&D(o.position),a=[];let n;return qi(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=wt(d,u));break;case k.CueTrackPositions:break;case k.CueClusterPosition:n&&(n.position=wt(d,u));break;default:t&&Fd.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:oe.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}}})},ag=s=>{let e=0,t=!1;try{qi(s,i=>i.tag===k.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):tg.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},ng={validateData:eg,parseInit:ig,getIndexRange:sg,parseSegments:rg,parseFeedableSegmentChunk:ag},Ud=1e4,og=3e4,dg=5e3,ug=Ud,lg=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a})=>{var n;const o=(n=a?Ki(a):void 0)!==null&&n!==void 0?n:si({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r}},cg=({id:s,bitrate:e})=>({id:s,bitrate:e}),hg=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=Ie(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:Ie(s,-1)},fg=({id:s,lang:e,url:t,isAuto:i})=>({id:s,url:t,isAuto:i,type:"internal",language:e}),Ns=s=>{const e=[];let t=0,i=s.length-1;for(;t<Ud&&i>=0;)e.unshift(s[i]),t+=s[i].time.to-s[i].time.from,i--;return e};let fo=class{constructor(e,t,i,r,{fetcher:a,tuning:n,getCurrentPosition:o,compatibilityMode:u=!1,manifest:d}){switch(this.onLastSegment$=new T(!1),this.fullyBuffered$=new T(!1),this.playingRepresentation$=new T(void 0),this.playingRepresentationInit$=new T(void 0),this.error$=new C,this.gaps=[],this.isSeekingLive=!1,this.subscription=new ue,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new ut,this.destroyAbortController=new ut,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.startWith=ce(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 Im(this.sourceBuffer),this.subscription.add(U(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},S=>this.error$.next({id:"SegmentEjection",category:R.WTF,message:"Error when trying to clear segments ejected by browser",thrown:S}))),this.subscription.add(U(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:R.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(S=>{if(!this.sourceBuffer)return;const b=Math.min(this.bufferLimit,ar(this.sourceBuffer.buffered)*.8);this.bufferLimit=b,this.pruneBuffer(this.getCurrentPosition(),S)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(S=>this.error$.next(S))),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=ce(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(j(f)||j(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();D(m)&&(this.searchGaps(h,c),this.maintain(m))}.bind(this)),this.seekLive=ce(this.destroyAbortController.signal,async function*(l){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!l)return;for(const b of this.representations.keys()){const g=l.find(E=>E.id===b);g&&this.representations.set(b,g);const y=this.representations.get(b);if(!y)return;const v=Ns(y.segmentReference.segments);this.segments.set(y.id,v)}const c=this.switchingToRepresentationId?this.switchingToRepresentationId:this.downloadingRepresentationId,h=this.representations.get(c);P(h);const f=Ns(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 S=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),S&&(yield this.sourceBufferTaskQueue.remove(S.from*1e3,S.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 Gi.MP4:this.containerParser=Zm;break;case Gi.WEBM:this.containerParser=ng;break;default:q(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 ut,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(j(e)||j(this.downloadingRepresentationId)||j(this.playingRepresentationId)||j(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(P(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const r=i.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const l=We(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)&&ar(this.sourceBuffer.buffered)>=this.bufferLimit){const d=We(this.sourceBuffer.buffered,e),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<l);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{const l=Ie(o,0);l&&l.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}!this.isLive&&!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===oe.FED&&!o.length&&We(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const u=Ie(i,-1);u&&u.status===oe.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;D(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:oe.NONE,size:void 0})),u=(i=this.segments.get(n.id))!==null&&i!==void 0?i:[],d=(a=(r=Ie(u,-1))===null||r===void 0?void 0:r.time.to)!==null&&a!==void 0?a:0,l=o==null?void 0:o.findIndex(c=>Math.round(d)>=Math.round(c.time.from)&&Math.round(d)<=Math.round(c.time.to));if(l===-1){this.liveUpdateSegmentIndex=0;const c=Ns(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 S=h<=i&&f>=i,b=h>i||S||m===0&&i===0,g=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&h<=i+g||f<=i+g;return(c===oe.NONE||c===oe.PARTIALLY_EJECTED&&b&&y&&this.sourceBuffer&&!Yi(this.sourceBuffer.buffered,i))&&b&&y});if(r===-1)return[];if(t!==ot.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===oe.NONE||h.status===oe.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 ot.BYTE_RANGE:{r=t.segmentReference.url,a={from:Ie(e,0).byte.from,to:Ie(e,-1).byte.to};break}case ot.TEMPLATE:{const d=Ie(e,0);r=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:q(o)}for(const d of n)d.status=oe.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:u}=this.downloadAbortController;if(this.failedDownloads&&(await ce(u,async function*(){const d=ms(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:R.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&&D(r)&&(i=We((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,i||this.error$.next({id:"SegmentDownload",category:R.NETWORK,message:"Error when fetching segments",thrown:e})}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=oe.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===oe.FED&&m.time.from===c.segment.time.from&&m.time.to===c.segment.time.to&&(m.status=oe.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===ot.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 b=f?h.byte.from-i:0,g=f?h.byte.to-i:e.byteLength,y=b<r,v=g<=r;if(h.status===oe.DOWNLOADING&&y&&v){h.status=oe.DOWNLOADED,this.activeSegments.delete(c);const E=new DataView(e.buffer,e.byteOffset+b,m);this.sourceBufferTaskQueue.append(E,a).then($=>$&&!a.aborted?o(c):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&y&&(c.loadedBytes=Math.min(m,r-b),c.loadedBytes>c.feedingBytes)){const E=new DataView(e.buffer,e.byteOffset+b+c.feedingBytes,c.loadedBytes-c.feedingBytes),$=c.loadedBytes===m?E:this.containerParser.parseFeedableSegmentChunk(E);$!=null&&$.byteLength&&(h.status=oe.PARTIALLY_FED,c.feedingBytes+=$.byteLength,this.sourceBufferTaskQueue.append($,a).then(L=>{if(a.aborted)n();else if(L)c.fedBytes+=$.byteLength,c.fedBytes===m&&o(c);else{if(c.feedingBytes<m)return;n()}}))}}}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===oe.PARTIALLY_FED||e.status===oe.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=oe.NONE),e.status=oe.PARTIALLY_EJECTED):e.status=oe.NONE;for(const i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,a]of this.initData.entries()){const n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=rr(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?ce(this.destroyAbortController.signal,async function*(){const o=ms(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(async o=>{if(!o)return;const{init:u,dataView:d,segments:l}=o,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c),this.segments.set(e.id,this.isLive?Ns(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:R.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||j(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,n=-1/0,o=!1;const u=d=>{var l;a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const c="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===oe.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===oe.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===oe.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===oe.FED&&u(c)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=rr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:R.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(j(this.sourceBuffer)||j(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}const t=1;for(const i of this.segments.values())for(const r of i){const{status:a}=r;if(a!==oe.FED&&a!==oe.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=oe.PARTIALLY_EJECTED:r.status=oe.NONE)}}};var Fi;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(Fi||(Fi={}));let pg=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new T(void 0),this.lastConnectionReused$=new T(void 0),this.lastRequestFirstBytes$=new T(void 0),this.abortAllController=new ut,this.subscription=new ue,this.fetchManifest=ce(this.abortAllController.signal,async function*(r){let a=r;this.requestQuic&&(a=ii(a));const n=yield $i(a,{signal:this.abortAllController.signal}).catch(us);return n?(this.onHeadersReceived(n.headers),n.text()):null}.bind(this)),this.fetch=ce(this.abortAllController.signal,async function*(r,{rangeMethod:a=this.compatibilityMode?Fi.HEADER:Fi.PARAM,range:n,onProgress:o,priority:u="auto",signal:d,measureThroughput:l=!0}={}){var c,h,f,m;let S=r;const b=new Headers;if(n)switch(a){case Fi.HEADER:{b.append("Range",`bytes=${n.from}-${n.to}`);break}case Fi.PARAM:{const Y=new URL(S,location.href);Y.searchParams.append("bytes",`${n.from}-${n.to}`),S=Y.toString();break}default:q(a)}this.requestQuic&&(S=ii(S));let g=this.abortAllController.signal,y;if(d){const Y=new ut;if(y=H(U(this.abortAllController.signal,"abort"),U(d,"abort")).subscribe(()=>{try{Y.abort()}catch(te){us(te)}}),this.abortAllController.signal.aborted||d.aborted)try{Y.abort()}catch(te){us(te)}g=Y.signal}const v=le(),E=yield $i(S,{priority:u,headers:b,signal:g}).catch(us),$=le();if((c=this.throughputEstimator)===null||c===void 0||c.addRawRtt($-v),!E)return y==null||y.unsubscribe(),null;if(!E.ok||!E.body)return y==null||y.unsubscribe(),Promise.reject(new Error(`Fetch error ${E.status}: ${E.statusText}`));this.onHeadersReceived(E.headers);const L=parseInt((h=E.headers.get("Content-Length"))!==null&&h!==void 0?h:"",10)||n&&n.to-n.from+1||NaN;if(!L){const Y=yield E.arrayBuffer();return(f=this.throughputEstimator)===null||f===void 0||f.addRawSpeed(Y.byteLength,le()-$),o==null||o(new DataView(Y),Y.byteLength),y==null||y.unsubscribe(),Y}if(!o&&!l)return y==null||y.unsubscribe(),E.arrayBuffer();const[G,Q]=E.body.tee(),V=G.getReader();l&&((m=this.throughputEstimator)===null||m===void 0||m.trackStream(Q));let z=0;const W=new ArrayBuffer(L),B=new Uint8Array(W),O=new DataView(W);let K=!1;const M=Y=>{y==null||y.unsubscribe(),K=!0,us(Y)},x=ce(g,async function*({done:Y,value:te}){if(z===0&&this.lastRequestFirstBytes$.next(le()-v),g.aborted){y==null||y.unsubscribe();return}!Y&&te&&(B.set(te,z),z+=te.byteLength,o==null||o(O,z),yield V==null?void 0:V.read().then(x,M))}.bind(this));return yield V==null?void 0:V.read().then(x,M),y==null||y.unsubscribe(),K?null:W}.bind(this)),this.fetchByteRangeRepresentation=ce(this.abortAllController.signal,async function*(r,a,n){var o;if(r.type!==ot.BYTE_RANGE)return null;const{from:u,to:d}=r.initRange;let l=u,c=d,h=!1,f,m;r.indexRange&&(f=r.indexRange.from,m=r.indexRange.to,h=d+1===f,h&&(l=Math.min(f,u),c=Math.max(m,d))),l=Math.min(l,0);const S=yield this.fetch(r.url,{range:{from:l,to:c},priority:n,measureThroughput:!1});if(!S)return null;const b=new DataView(S,u-l,d-l+1);if(!a.validateData(b))throw new Error("Invalid media file");const g=a.parseInit(b),y=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(g);if(!y)throw new ReferenceError("No way to load representation index");let v;if(h)v=new DataView(S,y.from-l,y.to-y.from+1);else{const $=yield this.fetch(r.url,{range:y,priority:n,measureThroughput:!1});if(!$)return null;v=new DataView($)}const E=a.parseSegments(v,g,y);return{init:g,dataView:new DataView(S),segments:E}}.bind(this)),this.fetchTemplateRepresentation=ce(this.abortAllController.signal,async function*(r,a){if(r.type!==ot.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:oe.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}=un(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 ot.BYTE_RANGE:return(r=await this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case ot.TEMPLATE:return(a=await this.fetchTemplateRepresentation(e,i))!==null&&a!==void 0?a:null;default:q(n)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}};const us=s=>{if(!(s instanceof DOMException)||!(s.name==="AbortError"||s.code===20))throw s};var mg=Ai,gg=mr,vg=bt,Sg=vg("match"),bg=function(s){var e;return mg(s)&&((e=s[Sg])!==void 0?!!e:gg(s)=="RegExp")},yg=Tr,Tg=String,Eg=function(s){if(yg(s)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return Tg(s)},$g=wi,Ag=function(){var s=$g(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},kg=jt,wg=Wt,_g=Ka,Pg=Ag,po=RegExp.prototype,Dg=function(s){var e=s.flags;return e===void 0&&!("flags"in po)&&!wg(s,"flags")&&_g(po,s)?kg(Pg,s):e},ln=zt,Rg=Sr,Ig=Math.floor,la=ln("".charAt),Lg=ln("".replace),ca=ln("".slice),xg=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Cg=/\$([$&'`]|\d{1,2})/g,Bg=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=Cg;return r!==void 0&&(r=Rg(r),u=xg),Lg(a,u,function(d,l){var c;switch(la(l,0)){case"$":return"$";case"&":return s;case"`":return ca(e,0,t);case"'":return ca(e,n);case"<":c=r[ca(l,1,-1)];break;default:var h=+l;if(h===0)return d;if(h>o){var f=Ig(h/10);return f===0?d:f<=o?i[f-1]===void 0?la(l,1):i[f-1]+la(l,1):d}c=i[h-1]}return c===void 0?"":c})},Og=yr,Mg=jt,cn=zt,mo=ja,Ng=lt,Fg=gr,Ug=bg,Ci=Eg,Vg=vr,Hg=Dg,Gg=Bg,Yg=bt,qg=Yg("replace"),zg=TypeError,Vd=cn("".indexOf),jg=cn("".replace),go=cn("".slice),Wg=Math.max,vo=function(s,e,t){return t>s.length?-1:e===""?t:Vd(s,e,t)};Og({target:"String",proto:!0},{replaceAll:function(e,t){var i=mo(this),r,a,n,o,u,d,l,c,h,f=0,m=0,S="";if(!Fg(e)){if(r=Ug(e),r&&(a=Ci(mo(Hg(e))),!~Vd(a,"g")))throw zg("`.replaceAll` does not allow non-global regexes");if(n=Vg(e,qg),n)return Mg(n,e,i,t);if(r)return jg(Ci(i),e,t)}for(o=Ci(i),u=Ci(e),d=Ng(t),d||(t=Ci(t)),l=u.length,c=Wg(1,l),f=vo(o,u,0);f!==-1;)h=d?Ci(t(u,f,o)):Gg(u,o,f,[],void 0,t),S+=go(o,m,f)+h,m=f+l,f=vo(o,u,f+c);return m<o.length&&(S+=go(o,m)),S}});var Qg=Pd,Kg=Qg("String","replaceAll"),Jg=Kg,Xg=Jg,Zg=Xg,ev=Zg,or=za(ev);const So=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},ha=(s,e)=>{let t=s;t=or(t,"$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,a]of Object.entries(i)){const n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=or(t,n,(o,u)=>j(a)?o:j(u)?a:a.padStart(parseInt(u,10),"0"))}return t},tv=(s,e)=>{var t,i,r,a,n,o,u,d,l,c,h,f,m,S,b,g,y,v,E,$,L,G,Q,V,z,W,B,O,K,M,x,Y,te,fe,be,Pe,Ye,st,ie;const qe=new DOMParser().parseFromString(s,"application/xml"),De={video:[],audio:[],text:[]},ke=qe.children[0],Ct=ke.getElementsByTagName("Period")[0],Bt=Ct.children,Xt=ke.getAttribute("type")==="dynamic",Ot=ke.getAttribute("availabilityStartTime"),Pi=Ot?new Date(Ot).getTime():void 0;let Me;const Xi=ke.getAttribute("mediaPresentationDuration"),Zi=Ct.getAttribute("duration"),ni=ke.getElementsByTagName("vk:Attrs")[0],es=ni==null?void 0:ni.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(Xi)Me=So(Xi);else if(Zi){const ye=So(Zi);D(ye)&&(Me=ye)}else es&&(Me=parseInt(es,10));let wr=0;const oi=(i=(t=ke.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],_r=oi.includes(ir.WEBM_AS_IN_FFMPEG)||oi.includes(ir.WEBM_AS_IN_SPEC)?Gi.WEBM:Gi.MP4;for(const ye of Bt){const Mt=ye.getAttribute("mimeType"),Pr=ye.getAttribute("codecs"),ts=(r=ye.getAttribute("contentType"))!==null&&r!==void 0?r:Mt==null?void 0:Mt.split("/")[0],Dr=(n=(a=ye.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],is=ye.querySelectorAll("Representation"),Rr=ye.querySelector("SegmentTemplate");if(ts===Ce.TEXT){for(const J of is){const Re=J.getAttribute("id")||"",Nt=ye.getAttribute("lang"),Qe=(d=(u=(o=J.querySelector("BaseURL"))===null||o===void 0?void 0:o.textContent)===null||u===void 0?void 0:u.trim())!==null&&d!==void 0?d:"",di=new URL(Qe,e).toString(),ui=Re.includes("_auto");De[Ce.TEXT].push({id:Re,lang:Nt,isAuto:ui,kind:Ce.TEXT,url:di})}continue}for(const J of is){const Re=(l=J.getAttribute("mimeType"))!==null&&l!==void 0?l:Mt,Nt=(h=(c=J.getAttribute("codecs"))!==null&&c!==void 0?c:Pr)!==null&&h!==void 0?h:"",Qe=(m=(f=J.getAttribute("contentType"))!==null&&f!==void 0?f:Re==null?void 0:Re.split("/")[0])!==null&&m!==void 0?m:ts,di=(b=(S=ye.getAttribute("profiles"))===null||S===void 0?void 0:S.split(","))!==null&&b!==void 0?b:[],ui=parseInt((g=J.getAttribute("width"))!==null&&g!==void 0?g:"",10),ss=parseInt((y=J.getAttribute("height"))!==null&&y!==void 0?y:"",10),rs=parseInt((v=J.getAttribute("bandwidth"))!==null&&v!==void 0?v:"",10)/1e3,as=(E=J.getAttribute("frameRate"))!==null&&E!==void 0?E:"",Ir=($=J.getAttribute("quality"))!==null&&$!==void 0?$:void 0,Lr=as?Er(as):void 0,xr=(L=J.getAttribute("id"))!==null&&L!==void 0?L:(wr++).toString(10),Cr=Qe==="video"?`${ss}p`:Qe==="audio"?`${rs}Kbps`:Nt,Br=`${xr}@${Cr}`,Or=(V=(Q=(G=J.querySelector("BaseURL"))===null||G===void 0?void 0:G.textContent)===null||Q===void 0?void 0:Q.trim())!==null&&V!==void 0?V:"",ns=new URL(Or,e).toString(),Mr=[...oi,...Dr,...di];let li;const Nr=J.querySelector("SegmentBase"),Ne=(z=J.querySelector("SegmentTemplate"))!==null&&z!==void 0?z:Rr;if(Nr){const Ke=(B=(W=J.querySelector("SegmentBase Initialization"))===null||W===void 0?void 0:W.getAttribute("range"))!==null&&B!==void 0?B:"",[Je,hi]=Ke.split("-").map(Xe=>parseInt(Xe,10)),ze={from:Je,to:hi},ht=(O=J.querySelector("SegmentBase"))===null||O===void 0?void 0:O.getAttribute("indexRange"),[fi,Ft]=ht?ht.split("-").map(Xe=>parseInt(Xe,10)):[],ft=ht?{from:fi,to:Ft}:void 0;li={type:ot.BYTE_RANGE,url:ns,initRange:ze,indexRange:ft}}else if(Ne){const Ke={representationId:(K=J.getAttribute("id"))!==null&&K!==void 0?K:void 0,bandwidth:(M=J.getAttribute("bandwidth"))!==null&&M!==void 0?M:void 0},Je=parseInt((x=Ne.getAttribute("timescale"))!==null&&x!==void 0?x:"",10),hi=(Y=Ne.getAttribute("initialization"))!==null&&Y!==void 0?Y:"",ze=Ne.getAttribute("media"),ht=(fe=parseInt((te=Ne.getAttribute("startNumber"))!==null&&te!==void 0?te:"",10))!==null&&fe!==void 0?fe:1,fi=ha(hi,Ke);if(!ze)throw new ReferenceError("No media attribute in SegmentTemplate");const Ft=(be=Ne.querySelectorAll("SegmentTimeline S"))!==null&&be!==void 0?be:[],ft=[];let Xe=0;if(Ft.length){let pi=ht,Ze=0;for(const mi of Ft){const et=parseInt((Pe=mi.getAttribute("d"))!==null&&Pe!==void 0?Pe:"",10),we=parseInt((Ye=mi.getAttribute("r"))!==null&&Ye!==void 0?Ye:"",10)||0,pt=parseInt((st=mi.getAttribute("t"))!==null&&st!==void 0?st:"",10);Ze=Number.isFinite(pt)?pt:Ze;const je=et/Je*1e3,Tt=Ze/Je*1e3;for(let Ut=0;Ut<we+1;Ut++){const os=ha(ze,{...Ke,segmentNumber:pi.toString(10),segmentTime:(Ze+Ut*et).toString(10)}),Di=(Tt||0)+Ut*je,Ri=Di+je;pi++,ft.push({time:{from:Di,to:Ri},url:os})}Ze+=(we+1)*et,Xe+=(we+1)*je}}else if(D(Me)){const Ze=parseInt((ie=Ne.getAttribute("duration"))!==null&&ie!==void 0?ie:"",10)/Je*1e3,mi=Math.ceil(Me/Ze);let et=0;for(let we=1;we<mi;we++){const pt=ha(ze,{...Ke,segmentNumber:we.toString(10),segmentTime:et.toString(10)});ft.push({time:{from:et,to:et+Ze},url:pt}),et+=Ze}}li={type:ot.TEMPLATE,baseUrl:ns,initUrl:fi,totalSegmentsDurationMs:Xe,segments:ft}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Qe||!Re)continue;const ci={video:Ce.VIDEO,audio:Ce.AUDIO,text:Ce.TEXT}[Qe];ci&&De[ci].push({id:Br,kind:ci,segmentReference:li,profiles:Mr,duration:Me,bitrate:rs,mime:Re,codecs:Nt,width:ui,height:ss,fps:Lr,quality:Ir})}}return{dynamic:Xt,liveAvailabilityStartTime:Pi,duration:Me,container:_r,representations:De}},Ua=1e3,bo=["timeupdate","progress","play","seeked","stalled","waiting"];var at;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(at||(at={}));let iv=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new ue,this.representationSubscription=new ue,this.state$=new he(at.NONE),this.currentVideoRepresentation$=new T(void 0),this.currentVideoRepresentationInit$=new T(void 0),this.error$=new C,this.lastConnectionType$=new T(void 0),this.lastConnectionReused$=new T(void 0),this.lastRequestFirstBytes$=new T(void 0),this.isLive$=new T(!1),this.liveDuration$=new T(0),this.liveAvailabilityStartTime$=new T(void 0),this.bufferLength$=new T(0),this.liveLoadBufferLength$=new T(0),this.forceEnded$=new C,this.gapWatchdogStarted=!1,this.destroyController=new ut,this.initManifest=ce(this.destroyController.signal,async function*(t,i,r){var a;this.element=t,this.manifestUrlString=Ve(i,r,Se.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(at.MANIFEST_READY),this.manifest=yield this.updateManifest(),!((a=this.manifest)===null||a===void 0)&&a.representations.video.length?this.state$.setState(at.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:R.PARSER,message:"No playable video representations"})}.bind(this)),this.updateManifest=ce(this.destroyController.signal,async function*(){var t;const i=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:R.NETWORK,message:"Failed to load manifest",thrown:n})});if(!i)return this.manifest;let r;try{r=tv(i!=null?i:"",this.manifestUrlString)}catch(n){this.error$.next({id:"ManifestParsing",category:R.PARSER,message:"Failed to parse MPD manifest",thrown:n})}if(!r)return null;const a=({kind:n,mime:o,codecs:u})=>{var d,l,c,h;return!!(!((l=(d=this.element)===null||d===void 0?void 0:d.canPlayType)===null||l===void 0)&&l.call(d,o)&&(!((h=(c=window.MediaSource)===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0)&&h.call(c,`${o}; codecs="${u}"`))||n===Ce.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:Ei(Object.entries(r.representations).map(([n,o])=>[n,o.filter(a)]))}}.bind(this)),this.initRepresentations=ce(this.destroyController.signal,async function*(t,i){P(this.manifest),P(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(at.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 fo(Ce.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],D(i)&&(this.audioBufferManager=new fo(Ce.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,r),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Ti(Ua).subscribe(o=>{var u;if(!((u=this.element)===null||u===void 0)&&u.paused){const d=er(this.manifestUrlString,Se.DASH_CMAF_OFFSET_P);this.manifestUrlString=Ve(this.manifestUrlString,d+1e3,Se.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(H(...bo.map(o=>U(this.element,o))).pipe(nu(Ua),_(o=>this.element?We(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 S,b;return(b=(S=m.getLiveSegmentsToLoadState(this.manifest))===null||S===void 0?void 0:S.to)!==null&&b!==void 0?b: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=er(this.manifestUrlString,Se.DASH_CMAF_OFFSET_P),c=og*d,h=ug*d,f=dg*d;o=u>o?u:o;const m=l===0&&u<f,S=l!==0&&u<c+f&&u>=c,b=l!==0&&u<c;if(b||S){const g=o-(c+h),y=Math.trunc(l+g/d);let v;u?y>0?v=y:v=0:v=l,this.manifestUrlString=Ve(this.manifestUrlString,v,Se.DASH_CMAF_OFFSET_P)}(m||b||S)&&(await this.updateLive(),o=0)}))}const a=H(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(_(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=H(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(_(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.representationSubscription.add(H(this.forceEnded$,Le({allBuffersFull:a,someBufferEnded:n}).pipe(ae(({allBuffersFull:o,someBufferEnded:u})=>o&&u))).subscribe(()=>{var o;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(u=>!u.updating))try{(o=this.source)===null||o===void 0||o.endOfStream()}catch(u){this.error$.next({id:"EndOfStream",category:R.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:u})}})),this.representationSubscription.add(H(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield new Promise(o=>{var u;return(u=this.source)===null||u===void 0?void 0:u.addEventListener("sourceopen",o)})),D(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&D(i)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)]):yield this.videoBufferManager.startWith(t),this.state$.setState(at.REPRESENTATIOS_READY)}.bind(this)),this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((i=this.audioBufferManager)===null||i===void 0)&&i.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=Ti(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:R.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new pg({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}async seekLive(e){var t,i,r,a;P(this.element),this.manifestUrlString=Ve(this.manifestUrlString,e,Se.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(at.RUNNING),this.subscription.add(H(...bo.map(e=>U(this.element,e)),U(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:R.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(U(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(U(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Yi(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){const i={[Ce.VIDEO]:this.videoBufferManager,[Ce.AUDIO]:this.audioBufferManager,[Ce.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)}seek(e,t){var i,r,a,n,o;P(this.element),P(this.videoBufferManager);let u;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?u=e:u=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!==null&&i!==void 0?i:e,(a=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&a!==void 0?a:e),Yi(this.element.buffered,u)||(this.videoBufferManager.abort(),(n=this.audioBufferManager)===null||n===void 0||n.abort()),this.videoBufferManager.maintain(u),(o=this.audioBufferManager)===null||o===void 0||o.maintain(u),this.element.currentTime=u/1e3}stop(){var e,t;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(e=this.videoBufferManager)===null||e===void 0||e.destroy(),this.videoBufferManager=null,(t=this.audioBufferManager)===null||t===void 0||t.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(at.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 sv{constructor(e,t){this.fov=e,this.orientation=t}}class rv{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 av=`#define GLSLIFY 1
|
|
38
|
-
attribute vec2 a_vertex;attribute vec2 a_texel;varying vec2 v_texel;void main(void){gl_Position=vec4(a_vertex,0.0,1.0);v_texel=a_texel;}`,
|
|
34
|
+
[selected track] ${M==null?void 0:M.quality}
|
|
35
|
+
`});const K=M&&d&&d.history[M.id]&&le()-d.history[M.id]<=i.trackCooldown&&(!d.last||M.id!==d.last.id);if(M!=null&&M.id&&d&&!K&&d.recordSelection(M),K&&(d!=null&&d.last)){const O=d.last;return d==null||d.recordSwitch(O),c({message:`
|
|
36
|
+
[last selected] ${O==null?void 0:O.quality}
|
|
37
|
+
`}),O}return d==null||d.recordSwitch(M),M};var Ye=s=>new URL(s).hostname;const nm=300,ys=(s,e=nm)=>new fr(t=>{const{width:i,height:r}=s.getBoundingClientRect();if(t.next({width:i,height:r}),!window.ResizeObserver)return;const a=new ResizeObserver(ou(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),D(u)&&D(d)&&t.next({width:u,height:d})},e));return a.observe(s),()=>a.disconnect()});class ks{constructor(){this.onDroopedVideoFramesLimit$=new C,this.subscription=new ue,this.playing=!1,this.tracks=[],this.forceChecker$=new C,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&&!yi(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&&Vi(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(U(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=Ti(this.droppedFramesChecker.checkTime).pipe(ae(()=>this.playing),ae(()=>{const r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(st(this.droppedFramesChecker.checkTime)),i=H(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])=>qs(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 ds={};var re;(function(s){s.DOWNLOADING_LIB="downloading_lib",s.STOPPED="stopped",s.STREAM_INITIALIZED="stream_initialized",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(re||(re={}));const _e=(s,e)=>new fr(t=>{const i=r=>t.next(r);return s.on(e,i),()=>s.off(e,i)});class lo{constructor(e){this.subscription=new ue,this.videoState=new he(re.DOWNLOADING_LIB),this.textTracksManager=new yt,this.droppedFramesManager=new ks,this.videoTracks$=new T([]),this.frameRatesByFrameHeight={},this.isLive$=new T(void 0),this.maxSeekBackTime$=new T(1/0),this.availableFrom$=new T(void 0),this.elementSize$=new T(void 0),this.liveOffset=new ws,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===re.DOWNLOADING_LIB||t===re.STREAM_INITIALIZED))switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===ee.Requested&&t!==re.STOPPED&&i!==p.STOPPED&&(n?this.seek(a.position-this.liveOffset.getTotalPausedTime()):this.seek(a.position)),i){case p.STOPPED:{switch(t){case re.STOPPED:break;case re.PLAYING:case re.PAUSED:case re.READY:this.stop();break;default:z(t)}break}case p.READY:{switch(t){case re.STOPPED:this.prepare();break;case re.PLAYING:case re.PAUSED:case re.READY:break;default:z(t)}break}case p.PLAYING:{switch(t){case re.PLAYING:break;case re.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 re.READY:this.play();break;case re.STOPPED:this.prepare();break;default:z(t)}break}case p.PAUSED:{switch(t){case re.PLAYING:this.pause(),this.liveOffset.pause();break;case re.PAUSED:break;case re.READY:this.videoState.setState(re.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED);break;case re.STOPPED:this.prepare();break;default:z(t)}break}default:z(i)}},this.video=Rt(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ye(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=r=>{var a;e||this.params.output.error$.next({id:r==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:R.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||(ds.MediaPlayer=r.MediaPlayer,ds.Debug=r.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){P(ds.MediaPlayer,"dashjs not loaded"),P(ds.Debug,"dashjs not loaded"),this.player=ds.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?Er(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&Mp(this.player),xp(this.player),this.params.tuning.requestQuick&&Bp(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(re.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=g=>{e.error$.next({id:"DashIFProvider",category:R.WTF,message:"DashIFProvider internal logic error",thrown:g})},r=(g,E)=>this.subscription.add(g.subscribe(E,i));r(ys(this.video),this.elementSize$),r(_e(this.player,"error").pipe(_(g=>{const E=typeof g.error=="object"?g.error.code:g.error,$=typeof g.error=="object"?g.error.message:void 0;return{id:`DashJS#${E}`,message:$}})),e.error$),r(_e(this.player,"playbackError").pipe(_(g=>({id:"DashJSPlayback",message:g.error}))),e.error$);const a=_e(this.player,"qualityChangeRendered").pipe(ae(({mediaType:g})=>g==="video"),_(({newQuality:g})=>{var E;return(E=this.videoTracks$.getValue().find(({bitrateInfo:$})=>$.qualityIndex===g))===null||E===void 0?void 0:E.track}));a.pipe(ae(D)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(ae(({to:g})=>g===re.STREAM_INITIALIZED),Ae()).subscribe(()=>{this.subscription.add(vt(t.videoTrack,()=>{var g;const E=this.player.getQualityFor("video");return(g=this.videoTracks$.getValue().find(({bitrateInfo:$})=>$.qualityIndex===E))===null||g===void 0?void 0:g.track},g=>{var E;if(j(g))return;const $=(E=this.videoTracks$.getValue().find(({track:L})=>L.id===g.id))===null||E===void 0?void 0:E.bitrateInfo;$&&this.player.setQualityFor("video",$.qualityIndex)},{changed$:a,onError:i}))},i)),this.subscription.add(vt(t.autoVideoTrackSwitching,()=>{var g,E,$;return($=(E=(g=this.player.getSettings().streaming)===null||g===void 0?void 0:g.abr)===null||E===void 0?void 0:E.autoSwitchBitrate)===null||$===void 0?void 0:$.video},g=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:g}}}}),{onError:i})),r(_e(this.player,"bufferStateChanged").pipe(ae(({mediaType:g})=>g==="video"),_(({state:g})=>g==="bufferStalled")),e.isBuffering$),r(_e(this.player,"fragmentLoadingStarted"),({mediaType:g,request:{url:E}})=>{var $,L;const G=this.player.getDashMetrics(),Q=G.getLatestFragmentRequestHeaderValueByID(g,"X-Reused"),V=($=G.getLatestFragmentRequestHeaderValueByID(g,"X-Delivery-Type"))!==null&&$!==void 0?$:Ss.HTTP1,q=(L={1:!0,0:!1}[Q])!==null&&L!==void 0?L:void 0;this.params.output.httpConnectionType$.next(V),this.params.output.httpConnectionReused$.next(q),e.hostname$.next(Ye(E))}),r(_e(this.player,"streamInitialized"),({streamInfo:{duration:g,manifestInfo:{isDynamic:E,availableFrom:$}}})=>{this.isLive$.next(E),this.availableFrom$.next($.getTime()),E||e.duration$.next(g);const L=[],G=this.player.getQualityFor("video");let Q;for(const V of this.player.getBitrateInfoListFor("video")){const q=V.qualityIndex.toString(10),W=si(V),B=V.bitrate/1e3,M={width:V.width,height:V.height},K=this.frameRatesByFrameHeight[V.height];if(W){const O={id:q,quality:W,bitrate:B,size:M,fps:K};L.push({track:O,bitrateInfo:V}),V.qualityIndex===G&&(Q=O)}}this.videoTracks$.next(L),e.availableVideoTracks$.next(L.map(({track:V})=>V)),Q&&e.currentVideoTrack$.next(Q),this.videoState.setState(re.STREAM_INITIALIZED),this.videoState.startTransitionTo(re.READY)}),r(_e(this.player,"fragmentLoadingCompleted"),({request:g})=>{if(!g.requestEndDate||!g.firstByteDate||!g.bytesLoaded)return;const E=g.requestEndDate.getTime()-g.firstByteDate.getTime(),$=g.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed($,E)}),r(H(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeStarted$,this.droppedFramesManager.onDroopedVideoFramesLimit$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks$.getValue().length)return;const g=this.params.dependencies.throughputEstimator.throughput$.getValue(),E=_i(this.videoTracks$.getValue().map(({track:G})=>G),{container:this.elementSize$.getValue(),throughput:g,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 L=this.videoTracks$.getValue().find(({track:G})=>G===E);L!=null&&L.bitrateInfo&&this.player.setQualityFor("video",L==null?void 0:L.bitrateInfo.qualityIndex,!1)}),r(Le({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(ae(D))}).pipe(ae(({isLive:g})=>g),_(({maxSeekBackTime:g})=>-g/1e3)),this.params.output.duration$);const n=_e(this.player,"playbackTimeUpdated").pipe(_(({time:g})=>g!=null?g:0));r(Le({availableFrom:this.availableFrom$.pipe(ae(D)),currentTime:n}),({availableFrom:g,currentTime:E})=>this.params.output.liveTime$.next(g+E*1e3)),r(n.pipe(ae(()=>this.isLive$.getValue()===!1)),e.position$),r(_e(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),r(_e(this.player,"playbackEnded"),e.endedEvent$),r(_e(this.player,"playbackProgress").pipe(_(()=>Dd(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(_e(this.player,"playbackPlaying"),()=>{this.videoState.setState(re.PLAYING),I(t.playbackState,p.PLAYING)}),r(_e(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(re.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(_e(this.player,"playbackPaused"),()=>{this.videoState.setState(re.PAUSED),I(t.playbackState,p.PAUSED)}),r(_e(this.player,"canPlay"),()=>{var g;((g=this.videoState.getTransition())===null||g===void 0?void 0:g.to)===re.READY&&this.videoState.setState(re.READY)}),r(this.isLive$,e.isLive$),r(ys(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=H(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ge(["init"])).pipe(st(0));r(o,this.syncPlayback);const{playbackDuration$:u,ping$:d,connectionType$:l,connectionReused$:c}=Cp(this.player);r(l,this.params.output.httpConnectionType$),r(c,this.params.output.httpConnectionReused$),r(u,this.maxSeekBackTime$),r(d.pipe(Ae()),e.firstBytesEvent$),r(_e(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(Le({isLive:this.isLive$,isShort:e.duration$.pipe(_(g=>g<60))}),({isLive:g,isShort:E})=>{const $=!g&&E;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:$}}})}),r(n.pipe(ae(g=>g>this.params.tuning.insufficientBufferRuleMargin),Ae()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(_e(this.player,"manifestLoaded").pipe(Ae()).subscribe(()=>{this.subscription.add(_e(this.player,"playbackPlaying").pipe(Ae(),Hi(void 0)).subscribe(e.firstFrameEvent$,i))},i)),r(_e(this.player,"manifestLoaded"),g=>{var E,$,L,G,Q,V,q;if(!(($=(E=g.data)===null||E===void 0?void 0:E.Period)===null||$===void 0)&&$.AdaptationSet){const W=[];for(const B of(G=(L=g.data)===null||L===void 0?void 0:L.Period)===null||G===void 0?void 0:G.AdaptationSet)if(B.contentType==="text"){const M=(Q=B.Representation)===null||Q===void 0?void 0:Q.id,K=new URL((V=B.Representation)===null||V===void 0?void 0:V.BaseURL,(q=g.data)===null||q===void 0?void 0:q.baseUri).toString(),O="internal",x=B.lang;W.push({id:M,url:K,type:O,language:x})}t.internalTextTracks.startTransitionTo(W)}}),this.subscription.add(ri(this.video,t.isLooped,i));const{volumeState$:h,looped$:f,playbackRateState$:m,inPiP$:S,inFullscreen$:b,pause$:v,playing$:y}=Lt(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:y,pause$:v,tracks$:this.videoTracks$.pipe(_(g=>g.map(({track:E})=>E)))}),this.subscription.add(Dt(this.video,t.volume,h,i)),this.subscription.add(h.subscribe(e.volume$,i)),this.subscription.add(f.subscribe(e.loopedEvent$)),this.subscription.add(Qt(this.video,t.playbackRate,m,i)),this.subscription.add(S.subscribe(e.inPiP$)),this.subscription.add(b.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(re.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(re.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,Se.PLAYBACK_SHIFT);this.player.attachSource(r)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(re.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(re.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){}It(this.video),this.params.output.element$.next(void 0)}}var Ki=s=>{switch(s){case"mobile":return at.Q_144P;case"lowest":return at.Q_240P;case"low":return at.Q_360P;case"sd":case"medium":return at.Q_480P;case"hd":case"high":return at.Q_720P;case"fullhd":case"full":return at.Q_1080P;case"quadhd":case"quad":return at.Q_1440P;case"ultrahd":case"ultra":return at.Q_2160P}};const co=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 Kt=async s=>{const e=s.muted;try{await s.play()}catch(t){if(!co(t))return!1;if(e)return console.warn(t),!1;s.muted=!0;try{await s.play()}catch(i){return co(i)&&(s.muted=!1,console.warn(i)),!1}}return!0};function Ve(){return le()}function Ld(s){return Ve()-s}function ho(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 om(s,e,t){const i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Ks(s,e,t,i){const r=window.XMLHttpRequest;let a,n,o,u=!1,d=0,l,c,h=!1,f="arraybuffer",m=7e3,S=2e3,b=()=>{if(u)return;P(l);const B=Ld(l);let M;if(B<S){M=S-B,setTimeout(b,M);return}S*=2,S>m&&(S=m),n&&n.abort(),n=new r,L()};const v=B=>(a=B,W),y=B=>(c=B,W),g=()=>(f="json",W),E=()=>{if(!u){if(--d>=0){b(),i&&i();return}u=!0,c&&c(),t&&t()}},$=B=>(h=B,W),L=()=>{l=Ve(),n=new r,n.open("get",s);let B=0,M,K=0;const O=()=>(P(l),Math.max(l,Math.max(M||0,K||0)));if(a&&n.addEventListener("progress",x=>{const Y=Ve();a.updateChunk&&x.loaded>B&&(a.updateChunk(O(),x.loaded-B),B=x.loaded,M=Y)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(u)return;P(n);const x=n.status;if(x>=200&&x<300){if(n.response.byteLength&&a){const Y=n.response.byteLength-B;Y&&a.updateChunk&&a.updateChunk(O(),Y)}c&&c(),n&&e(n.response)}else E()}),n.addEventListener("error",()=>{E()}),h){const x=()=>{P(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(K=Ve(),n.removeEventListener("readystatechange",x))};n.addEventListener("readystatechange",x)}return n.responseType=f,n.send(),W},W={withBitrateReporting:v,withParallel:$,withJSONResponse:g,withRetryCount:B=>(d=B,W),withRetryInterval:(B,M)=>(D(B)&&(S=B),D(M)&&(m=M),W),withTimeout:B=>(o=B,W),withFinally:y,send:L,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return W}const dm=100,um=2e3,lm=500;let cm=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-lm;if(t-e>um){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>dm&&(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 hm{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=Ve(),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=Ve()-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=Ks(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=Ve()}_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=Ve();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 Os=1e4,Ns=3,fm=300,pm=2e3,mm=6e4,gm=10,vm=1,Sm=500;class bm{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 cm(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ho(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=ho(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||D(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=()=>{om(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 hm(Ns,Os,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 E=a&&(!l||l===this.rep);return E||t("Not running!"),E},h=(E,$,L)=>{u&&u.abort(),u=Ks(this.urlResolver.resolve(E,!1),$,L,()=>this._retryCallback()).withTimeout(Os).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ns).withFinally(()=>{u=null}).send()},f=(E,$,L)=>{P(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),$,L,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=E=>{const $=i.playbackRate;i.playbackRate!==E&&(t(`Playback rate switch: ${$}=>${E}`),i.playbackRate=E)},S=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}const L=Ve()-1e4;let G=0;for(let V=0;V<this.bufferStates.length;V++){const q=this.bufferStates[V];E=Math.min(E,q.buf),q.ts<L&&G++}this.bufferStates.splice(0,G),t(`update playback rate; minBuffer=${E} drop=${G} jitter=${this.sourceJitter}`);let Q=E-vm;this.sourceJitter>=0?Q-=this.sourceJitter/2:this.sourceJitter-=1,Q>3?m(1.15):Q>1?m(1.1):Q>.3?m(1.05):m(1)}},v=E=>{let $;const L=()=>$&&$.start?$.start.length:0,G=x=>$.start[x]/1e3,Q=x=>$.dur[x]/1e3,V=x=>$.fragIndex+x,q=(x,Y)=>({chunkIdx:V(x),startTS:G(x),dur:Q(x),discontinuity:Y}),W=()=>{let x=0;if($&&$.dur){let Y=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,te=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,fe=Y;this.sourceJitter>1&&(fe+=this.sourceJitter-1);let be=$.dur.length-1;for(;be>=0&&(fe-=$.dur[be],!(fe<=0));--be);x=Math.min(be,$.dur.length-1-te),x=Math.max(x,0)}return q(x,!0)},B=x=>{const Y=L();if(!(Y<=0)){if(D(x)){for(let te=0;te<Y;te++)if(G(te)>x)return q(te)}return W()}},M=x=>{const Y=L(),te=x?x.chunkIdx+1:0,fe=te-$.fragIndex;if(!(Y<=0)){if(!x||fe<0||fe-Y>gm)return t(`Resync: offset=${fe} bChunks=${Y} chunk=`+JSON.stringify(x)),W();if(!(fe>=Y))return q(te-$.fragIndex,!1)}},K=(x,Y,te)=>{d&&d.abort(),d=Ks(this.urlResolver.resolve(x,!0,this.lowLatency),Y,te,()=>this._retryCallback()).withTimeout(Os).withRetryCount(Ns).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(x,Y)=>{K(E,te=>{if(!c())return;$=te;const fe=!!$.lowLatency;fe!==this.lowLatency&&S(fe);let be=0;for(let Pe=0;Pe<$.dur.length;++Pe)be+=$.dur[Pe];be>0&&(P(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(be/$.dur.length)),r({name:"index",zeroTime:$.zeroTime,shiftDuration:$.shiftDuration}),this.sourceJitter=$.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,$.jitter/1e3)):1,x(B(Y))},()=>this._handleNetworkError())},nextChunk:M}},y=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),P(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:E=>{const{videoElement:$,logger:L}=this.params;let G=v(e.jidxUrl),Q,V,q,W,B=0,M,K,O;const x=()=>{M&&(clearTimeout(M),M=void 0);const ie=Math.max(Sm,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Oe=B+ie,qe=Ve(),De=Math.min(1e4,Oe-qe);B=qe;const we=()=>{d||c()&&G.seek(()=>{c()&&(B=Ve(),Y(),x())})};De>0?M=window.setTimeout(()=>{this.paused?x():we()},De):we()},Y=()=>{let ie;for(;ie=G.nextChunk(W);)W=ie,ze(ie);const Oe=G.nextChunk(q);if(Oe){if(q&&Oe.discontinuity){L("Detected discontinuity; restarting playback"),this.paused?x():(y(),this._initPlayerWith(e));return}Pe(Oe)}else x()},te=(ie,Oe)=>{if(!c()||!this.sourceBuffer)return;let qe,De,we;const Ct=Bt=>{window.setTimeout(()=>{c()&&te(ie,Oe)},Bt)};if(this.sourceBuffer.updating)L("Source buffer is updating; delaying appendBuffer"),Ct(100);else{const Bt=Ve(),Xt=$.currentTime;!this.paused&&$.buffered.length>1&&K===Xt&&Bt-O>500&&(L("Stall suspected; trying to fix"),this._fixupStall()),K!==Xt&&(K=Xt,O=Bt);const Mt=this._getBufferSizeSec();if(Mt>30)L(`Buffered ${Mt} seconds; delaying appendBuffer`),Ct(2e3);else try{this.sourceBuffer.appendBuffer(ie),this.videoPlayStarted?(this.bufferStates.push({ts:Bt,buf:Mt}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Oe&&Oe()}catch(Pi){if(Pi.name==="QuotaExceededError")L("QuotaExceededError; delaying appendBuffer"),we=this.sourceBuffer.buffered.length,we!==0&&(qe=this.sourceBuffer.buffered.start(0),De=Xt,De-qe>4&&this.sourceBuffer.remove(qe,De-3)),Ct(1e3);else throw Pi}}},fe=()=>{V&&Q&&(L([`Appending chunk, sz=${V.byteLength}:`,JSON.stringify(q)]),te(V,function(){V=null,Y()}))},be=ie=>e.fragUrlTemplate.replace("%%id%%",ie.chunkIdx),Pe=ie=>{c()&&f(be(ie),(Oe,qe)=>{if(c()){if(qe/=1e3,V=Oe,q=ie,n=ie.startTS,qe){const De=Math.min(10,ie.dur/qe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*De:De}fe()}},()=>this._handleNetworkError())},ze=ie=>{c()&&(P(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(be(ie),!1)))},rt=ie=>{c()&&(e.cachedHeader=ie,te(ie,()=>{Q=!0,fe()}))};a=!0,G.seek(ie=>{if(c()){if(B=Ve(),!ie){x();return}W=ie,!j(E)||ie.startTS>E?Pe(ie):(q=ie,Y())}},E),e.cachedHeader?rt(e.cachedHeader):h(e.headerUrl,rt,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>n},l}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),D(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,P(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return D(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=Ve();if(this.chunkRateEstimator.addInterval(h,m,f)){const b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:m-h,speed:b}),!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&&Ld(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=Ve();c<o&&(n=h),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Ks(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Os).withRetryCount(Ns).withRetryInterval(fm,pm).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;Kt(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):(i({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))},mm))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var se;(function(s){s.STOPPED="stopped",s.MANIFEST_READY="manifest_ready",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(se||(se={}));const ym=[se.PAUSED,se.PLAYING,se.READY],Tm=[se.PAUSED,se.PLAYING,se.READY];class Em{constructor(e){this.subscription=new ue,this.videoState=new he(se.STOPPED),this.representations$=new T([]),this.textTracksManager=new yt,this.droppedFramesManager=new ks,this.maxSeekBackTime$=new T(1/0),this.zeroTime$=new T(void 0),this.liveOffset=new ws,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:R.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=Ki(c.name))!==null&&n!==void 0?n:si(c.video),m=c.bitrate/1e3,S={...c.video};if(!f)continue;const b={id:h,quality:f,bitrate:m,size:S};l.push({track:b,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)===se.MANIFEST_READY&&this.videoState.setState(se.MANIFEST_READY);break}case"qualitySwitch":{const d=r.quality,l=(u=this.representations$.getValue().find(({representation:c})=>c===d))===null||u===void 0?void 0:u.track;this.params.output.hostname$.next(new URL(d.headerUrl,this.params.source.url).hostname),D(l)&&this.params.output.currentVideoTrack$.next(l);break}case"bandwidth":{const{size:d,duration:l}=r;this.params.dependencies.throughputEstimator.addRawSpeed(d,l);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration||0),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{const r=this.videoState.getState(),a=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${r}; videoTransition: ${JSON.stringify(a)}; desiredPlaybackState: ${n}; seekState: ${JSON.stringify(u)};`}),n===p.STOPPED){r!==se.STOPPED&&(this.videoState.startTransitionTo(se.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(se.STOPPED));return}if(a)return;const d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Tm.includes(r)&&(d||l)){this.prepare();return}if((o==null?void 0:o.to)!==p.PAUSED&&u.state===ee.Requested&&ym.includes(r)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(r){case se.STOPPED:this.videoState.startTransitionTo(se.MANIFEST_READY),this.dash.attachSource(He(this.params.source.url));return;case se.MANIFEST_READY:this.videoState.startTransitionTo(se.READY),this.prepare();break;case se.READY:if(n===p.PAUSED)this.videoState.setState(se.PAUSED);else if(n===p.PLAYING){this.videoState.startTransitionTo(se.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(se.PAUSED)})}return;case se.PLAYING:n===p.PAUSED&&(this.videoState.startTransitionTo(se.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case se.PAUSED:if(n===p.PLAYING)if(this.videoState.startTransitionTo(se.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(se.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 z(r)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:R.WTF,message:"DashLiveProvider internal logic error",thrown:r})};H(this.videoState.stateChangeStarted$.pipe(_(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(_(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=Rt(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Ye(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=Lt(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(_(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)===se.READY&&this.videoState.setState(se.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(se.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===ee.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(se.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(ve(),_(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Le({zeroTime:this.zeroTime$.pipe(ae(D)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(ri(this.video,this.params.desiredState.isLooped,t)).add(Dt(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Qt(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&&du(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case se.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(p.STOPPED);break;case se.MANIFEST_READY:case se.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 se.PAUSED:this.params.desiredState.playbackState.setState(p.PAUSED);break;case se.PLAYING:this.params.desiredState.playbackState.setState(p.PLAYING);break;default:return z(r.to)}},t)).add(H(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Ge(["init"])).pipe(st(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),It(this.video)}createLiveDashPlayer(){const e=new bm({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&&D(u)?u:_i(o.map(({track:S})=>S),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),c=l==null?void 0:l.id,h=this.params.desiredState.videoTrack.getTransition(),f=(a=this.params.desiredState.videoTrack.getState())===null||a===void 0?void 0:a.id,m=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(h||c!==f)&&this.setVideoTrack(l),m&&this.setAutoQuality(d),h||m||c!==f){const S=(n=o.find(({track:b})=>b.id===c))===null||n===void 0?void 0:n.representation;P(S,"Representations missing"),this.dash.startPlay(S,d)}}setVideoTrack(e){var t;const i=(t=this.representations$.getValue().find(({track:r})=>r.id===e.id))===null||t===void 0?void 0:t.representation;P(i,`No such representation ${e.id}`),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===se.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 cn=s=>{var e,t;const i=s.get("X-Delivery-Type"),r=s.get("X-Reused"),a=i===null?Ss.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}},Qe=(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 $m=s=>{const e=document.createElement("a");return e.href=s,e.origin},Am=s=>{const e=document.createElement("a");return e.href=s,e.host};class xd{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=Ei(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(Am(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 tr{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=S=>{r(tr._str2ua(S.substr(u))),u=S.length};let m=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(m=ii(m)),this._lastXhr=new xd(m,e.failoverHosts,S=>{this._lastXhr=void 0,f(S);const b=Date.now()-d;this._params.onBandwidthChange({size:S.length,duration:b,speed:8*S.length/(b/1e3)}),this._onDashCallback("loading",{size:S.length,done:!0}),a==null||a()},S=>{if(S.length-u>o&&f(S),c===0){c=Date.now();return}h=S.length-l;const b=Date.now()-c;h>=100*1024&&b>=1e3&&(this._params.onBandwidthChange({size:h,duration:b,speed:8*h/(b/1e3)}),h=0,l=S.length,c=Date.now()),this._onDashCallback("loading",{size:S.length,done:!1})},n,(S,b,v)=>this._params.onError(S,b,v))})}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=tr._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 wm{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=ii(i)),new xd(i,t,r=>{this.attachManifest(r,t,$m(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,S,b,v,y,g,E,$,L,G,Q,V,q,W,B;const M=d.getElementsByTagName("SegmentBase")[0],K=M&&n(M,"indexRange").split("-"),O=M&&M.getElementsByTagName("Initialization")[0],x=O&&n(O,"range").split("-");if(!x||!K){const ze=d.parentElement;if((ze==null?void 0:ze.getAttribute("contentType"))==="text"){const rt=(l=d.getAttribute("id"))!==null&&l!==void 0?l:void 0,ie=(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),Oe=(S=ze.getAttribute("lang"))!==null&&S!==void 0?S:void 0;ie&&u.push({id:rt,url:ie,language:Oe})}return}const Y=.1,te=Number((b=d.attributes.getNamedItem("bandwidth"))===null||b===void 0?void 0:b.value),fe=(i?i+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let be;const Pe=(y=(v=d.attributes.getNamedItem("frameRate"))===null||v===void 0?void 0:v.value)!==null&&y!==void 0?y:void 0;be=Pe?Er(Pe):void 0,o.push({width:Number((g=d.attributes.getNamedItem("width"))===null||g===void 0?void 0:g.value),height:Number((E=d.attributes.getNamedItem("height"))===null||E===void 0?void 0:E.value),bandwidth:te,baseURL:fe,failoverHosts:t,indexFrom:Number(K[0]),indexTo:Number(K[1]),initFrom:Number(x[0]),initTo:Number(x[1]),codecs:(L=($=d.attributes.getNamedItem("codecs"))===null||$===void 0?void 0:$.value)!==null&&L!==void 0?L:void 0,mimeType:(Q=(G=d.attributes.getNamedItem("mimeType"))===null||G===void 0?void 0:G.value)!==null&&Q!==void 0?Q:void 0,fps:be,bufferSize:Y*te/8,bufferLength:Y,name:(q=(V=d.attributes.getNamedItem("okQuality"))===null||V===void 0?void 0:V.value)!==null&&q!==void 0?q:void 0,id:(B=(W=d.attributes.getNamedItem("id"))===null||W===void 0?void 0:W.value)!==null&&B!==void 0?B: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 tr({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||j(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 ne;(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"})(ne||(ne={}));const km=[ne.PAUSED,ne.PLAYING];class _m{constructor(e){this.videoState=new he(ne.STOPPED),this.subscription=new ue,this.representations$=new T([]),this.currentRepresentation$=new T(void 0),this.textTracksManager=new yt,this.droppedFramesManager=new ks,this.elementSize$=new T(void 0),this.dashLiteEvents={idxRequestPing$:new C,responseHeaders$:new C,manifestReady$:new C,representationPlay$:new C,error$:new C},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&&Ki(u.name))!==null&&n!==void 0?n:si(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(ne.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))},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!==ne.STOPPED&&(this.videoState.startTransitionTo(ne.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(ne.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(!i)switch((a==null?void 0:a.to)!==p.PAUSED&&n.state===ee.Requested&&km.includes(t)&&this.seek(n.position,n.forcePrecise),t){case ne.STOPPED:this.videoState.startTransitionTo(ne.MANIFEST_LOADED),this.prepare();return;case ne.MANIFEST_LOADED:this.videoState.startTransitionTo(ne.INITIAL_REPRESENTATION_SELECTED);return;case ne.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(ne.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case ne.METADATA_LOADED:this.videoState.startTransitionTo(ne.READY),this.dash.updateRefsForCurrentTime();return;case ne.READY:r===p.READY?I(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(ne.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(ne.PLAYING),this.playIfAllowed());return;case ne.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(ne.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case ne.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(ne.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return z(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),H(this.videoState.stateChangeStarted$.pipe(_(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(_(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=Rt(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(Ye(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Hp(this.video),this.dash=new wm({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:R.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:R.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=Lt(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(()=>{j(this.params.desiredState.seekState.getState().state!==ee.Applying)&&(this.videoState.getState()===ne.PLAYING||this.videoState.getState()===ne.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(ri(this.video,t.isLooped,i)),this.subscription.add(Dt(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Qt(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(_(o=>o.map(({track:u})=>u)))}),n(ys(this.video),this.elementSize$),this.subscription.add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ne.READY&&this.videoState.setState(ne.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(ne.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)})).add(a.playing$.subscribe(()=>{this.videoState.setState(ne.PLAYING),I(this.params.desiredState.playbackState,p.PLAYING)},i)).add(a.loadedMetadata$.subscribe(()=>{this.videoState.setState(ne.METADATA_LOADED)},i)).add(a.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},i)).add(this.dashLiteEvents.error$.pipe(_(({id:o,message:u,thrown:d})=>({id:`DashLite_${o}`,category:R.WTF,message:u,thrown:d}))).subscribe(this.params.output.error$)).add(H(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$,this.params.output.element$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,U(this.video,"progress")).pipe(_(()=>{var o,u,d,l;const c=this.currentRepresentation$.getValue(),h=this.representations$.getValue(),f=this.params.desiredState.autoVideoTrackSwitching.getTransition(),m=(o=this.params.desiredState.videoTrack.getState())===null||o===void 0?void 0:o.id,S=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),b=this.elementSize$.getValue(),v=r();f&&this.params.desiredState.autoVideoTrackSwitching.setState(f.to);let y;if(!v&&D(m))y=m;else{const g=Qe(this.video.buffered,this.video.currentTime*1e3),E=v?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,$=Math.min(g/E,1);y=(d=_i(h.map(({track:G})=>G),{container:b,throughput:S,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:$,playbackRate:this.video.playbackRate,current:(u=h.find(({representation:G})=>G===c))===null||u===void 0?void 0:u.track,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}))===null||d===void 0?void 0:d.id;const L=t.autoVideoTrackLimits.getTransition();L&&e.autoVideoTrackLimits$.next(L.to)}return D(y)?(l=h.find(({track:g})=>g.id===y))===null||l===void 0?void 0:l.representation:void 0}),ve()).subscribe(this.currentRepresentation$,i)).add(Le({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(ae(o=>o.to===ne.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(ae(D))}).pipe(Ae()).subscribe(()=>this.videoState.setState(ne.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(ae(D),ve((o,u)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?o.height<=u.height:o===u)).subscribe(o=>{const u=Qe(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(Ye(o.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:u,reused:d}=cn(o);this.params.output.httpConnectionType$.next(u),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(Ae(),Hi(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(ae(D)).subscribe(this.handleRepresentationPlay,i)).add(H(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ge(["init"])).pipe(st(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),It(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 z(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){Kt(this.video).then(e=>{e||(this.videoState.setState(ne.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}}var Be;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(Be||(Be={}));var ir;(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"})(ir||(ir={}));var dt;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(dt||(dt={}));var oe;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(oe||(oe={}));var Gi;(function(s){s.MP4="mp4",s.WEBM="webm"})(Gi||(Gi={}));var sr;(function(s){s[s.RECTANGULAR=0]="RECTANGULAR",s[s.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",s[s.CUBEMAP=2]="CUBEMAP",s[s.MESH=3]="MESH"})(sr||(sr={}));var Te;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Te||(Te={}));class fo{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 Cd extends fo{constructor(){super(),this.listeners||fo.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 Bd=class{constructor(){Object.defineProperty(this,"signal",{value:new Cd,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&&(Bd.prototype[Symbol.toStringTag]="AbortController",Cd.prototype[Symbol.toStringTag]="AbortSignal");function Md(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 Pm(s){typeof s=="function"&&(s={fetch:s});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!Md({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 $r=Md({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Od=$r?Pm({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,$i=$r?Od.fetch:window.fetch;$r?Od.Request:window.Request;const lt=$r?Bd:window.AbortController;var Yi=(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 Dm=(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)},Rm=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",rr=Rm?Dm:window.requestIdleCallback;var da,ua;const Im=16;let Nd=!1;try{Nd=hr().browser===ja.Safari&&parseInt((ua=(da=navigator.userAgent.match(/Version\/(\d+)/))===null||da===void 0?void 0:da[1])!==null&&ua!==void 0?ua:"",10)<=Im}catch(s){console.error(s)}let Lm=class{constructor(e){this.bufferFull$=new C,this.error$=new C,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const i=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!i),this.currentTask=null}this.queue.length&&this.pull()}catch(i){this.error$.next({id:"BufferTaskQueueUnknown",category:R.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i;Nd&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:i}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&i==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${i}`,category:R.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:z(t)}}};var ar=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};let xt=class{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}},Fd=class extends xt{},xm=class extends xt{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}}},Cm=class extends xt{parseChildrenBoxes(){return Ji(this.content)}},Bm=class extends xt{constructor(e){super(e),this.data=this.content}},_s=class extends xt{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}},Mm=class extends _s{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})}}},Om=class extends xt{parseChildrenBoxes(){return Ji(this.content)}},Nm=class extends xt{parseChildrenBoxes(){return Ji(this.content)}};var Si;(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"})(Si||(Si={}));let Fm=class extends _s{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=Si.MONOSCOPIC;break;case 1:this.stereoMode=Si.TOP_BOTTOM;break;case 2:this.stereoMode=Si.LEFT_RIGHT;break;case 3:this.stereoMode=Si.STEREO_CUSTOM;break;case 4:this.stereoMode=Si.RIGHT_LEFT;break}this.cursor+=1}},Um=class extends _s{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}},Vm=class extends _s{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}},Hm=class extends xt{parseChildrenBoxes(){return Ji(this.content)}},Gm=class extends _s{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()}},Ym=class extends xt{parseChildrenBoxes(){return Ji(this.content)}},zm=class extends xt{parseChildrenBoxes(){return Ji(this.content)}};const qm={ftyp:xm,moov:Cm,mdat:Bm,sidx:Mm,trak:Om,mdia:Hm,tkhd:Gm,minf:Ym,sv3d:Nm,st3d:Fm,prhd:Um,proj:zm,equi:Vm,unknown:Fd};let jm=class{createBox(e,t){const i=qm[e];return i?new i(t):new Fd(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Ar.createBox(i,new DataView(e.buffer,e.byteOffset))}};const Ar=new jm;function fs(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:Ar.createBox(e,new DataView(s.buffer,i-7))}i++}return null}function Wm(s,e){const t=[];let i=0;for(;i<s.byteLength;){const r=fs(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 Ji(s){const e=[];let t=0;for(;t<s.byteLength;){const i=Ar.createFromView(new DataView(s.buffer,s.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const Qm=new TextDecoder("ascii"),Km=s=>Qm.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",Jm=s=>{const e=Ar.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:oe.NONE,time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},Xm=s=>{const e=Wm(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},Zm=s=>{const e={is3dVideo:!1,stereoMode:0,projectionType:sr.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(fs(s,"sv3d")){e.is3dVideo=!0;const i=fs(s,"st3d");i&&(e.stereoMode=i.stereoMode);const r=fs(s,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const a=fs(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},eg={validateData:Km,parseInit:Zm,getIndexRange:()=>{},parseSegments:Jm,parseFeedableSegmentChunk:Xm};var w;(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"})(w||(w={}));var N;(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"})(N||(N={}));const po={[w.EBML]:{type:N.Master},[w.EBMLVersion]:{type:N.UnsignedInteger},[w.EBMLReadVersion]:{type:N.UnsignedInteger},[w.EBMLMaxIDLength]:{type:N.UnsignedInteger},[w.EBMLMaxSizeLength]:{type:N.UnsignedInteger},[w.DocType]:{type:N.String},[w.DocTypeVersion]:{type:N.UnsignedInteger},[w.DocTypeReadVersion]:{type:N.UnsignedInteger},[w.Void]:{type:N.Binary},[w.Segment]:{type:N.Master},[w.SeekHead]:{type:N.Master},[w.Seek]:{type:N.Master},[w.SeekID]:{type:N.Binary},[w.SeekPosition]:{type:N.UnsignedInteger},[w.Info]:{type:N.Master},[w.TimestampScale]:{type:N.UnsignedInteger},[w.Duration]:{type:N.Float},[w.Tracks]:{type:N.Master},[w.TrackEntry]:{type:N.Master},[w.Video]:{type:N.Master},[w.Projection]:{type:N.Master},[w.ProjectionType]:{type:N.UnsignedInteger},[w.ProjectionPrivate]:{type:N.Master},[w.Chapters]:{type:N.Master},[w.Cluster]:{type:N.Master},[w.Timestamp]:{type:N.UnsignedInteger},[w.SilentTracks]:{type:N.Master},[w.SilentTrackNumber]:{type:N.UnsignedInteger},[w.Position]:{type:N.UnsignedInteger},[w.PrevSize]:{type:N.UnsignedInteger},[w.SimpleBlock]:{type:N.Binary},[w.BlockGroup]:{type:N.Master},[w.EncryptedBlock]:{type:N.Binary},[w.Attachments]:{type:N.Master},[w.Tags]:{type:N.Master},[w.Cues]:{type:N.Master},[w.CuePoint]:{type:N.Master},[w.CueTime]:{type:N.UnsignedInteger},[w.CueTrackPositions]:{type:N.Master},[w.CueTrack]:{type:N.UnsignedInteger},[w.CueClusterPosition]:{type:N.UnsignedInteger},[w.CueRelativePosition]:{type:N.UnsignedInteger},[w.CueDuration]:{type:N.UnsignedInteger},[w.CueBlockNumber]:{type:N.UnsignedInteger},[w.CueCodecState]:{type:N.UnsignedInteger},[w.CueReference]:{type:N.Master},[w.CueRefTime]:{type:N.UnsignedInteger}},Ud=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=nr(s,t),r=i in po,a=r?po[i].type:N.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=nr(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}},nr=(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},kt=(s,e)=>{switch(e){case N.SignedInteger:return s.getInt8(0);case N.UnsignedInteger:return nr(s);case N.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case N.String:return new TextDecoder("ascii").decode(s);case N.UTF8:return new TextDecoder("utf-8").decode(s);case N.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case N.Master:return s;case N.Binary:return s;default:z(e)}},zi=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=Ud(i);if(!e(r))return;r.type===N.Master&&zi(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},tg=s=>{if(s.getUint32(0)!==w.EBML)return!1;let e,t,i;const r=Ud(s);return zi(r.value,({tag:a,type:n,value:o})=>(a===w.EBMLReadVersion?e=kt(o,n):a===w.DocType?t=kt(o,n):a===w.DocTypeReadVersion&&(i=kt(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Vd=[w.Info,w.SeekHead,w.Tracks,w.TrackEntry,w.Video,w.Projection,w.ProjectionType,w.ProjectionPrivate,w.Chapters,w.Cluster,w.Cues,w.Attachments,w.Tags],ig=[w.Timestamp,w.SilentTracks,w.SilentTrackNumber,w.Position,w.PrevSize,w.SimpleBlock,w.BlockGroup,w.EncryptedBlock],sg=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,d,l=!1;const c=0;return zi(s,({tag:h,type:f,value:m,valueSize:S})=>{if(h===w.SeekID){const b=kt(m,f);d=nr(b)}else h!==w.SeekPosition&&(d=void 0);return h===w.Segment?(e=m.byteOffset,t=m.byteOffset+S):h===w.Info?a=!0:h===w.SeekHead?n=!0:h===w.TimestampScale?i=kt(m,f):h===w.Duration?r=kt(m,f):h===w.SeekPosition&&d===w.Cues?u=kt(m,f):h===w.Tracks?zi(m,({tag:b,type:v,value:y})=>b===w.ProjectionType?(l=kt(y,v)===1,!1):!0):a&&n&&Vd.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:sr.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},rg=s=>{if(j(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},ag=(s,e)=>{let t=!1,i=!1;const r=o=>D(o.time)&&D(o.position),a=[];let n;return zi(s,({tag:o,type:u,value:d})=>{switch(o){case w.Cues:t=!0;break;case w.CuePoint:n&&r(n)&&a.push(n),n={};break;case w.CueTime:n&&(n.time=kt(d,u));break;case w.CueTrackPositions:break;case w.CueClusterPosition:n&&(n.position=kt(d,u));break;default:t&&Vd.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:oe.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}}})},ng=s=>{let e=0,t=!1;try{zi(s,i=>i.tag===w.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):ig.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[w.SimpleBlock,w.BlockGroup,w.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},og={validateData:tg,parseInit:sg,getIndexRange:rg,parseSegments:ag,parseFeedableSegmentChunk:ng},Hd=1e4,dg=3e4,ug=5e3,lg=Hd,cg=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a})=>{var n;const o=(n=a?Ki(a):void 0)!==null&&n!==void 0?n:si({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r}},hg=({id:s,bitrate:e})=>({id:s,bitrate:e}),fg=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=Ie(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:Ie(s,-1)},pg=({id:s,lang:e,url:t,isAuto:i})=>({id:s,url:t,isAuto:i,type:"internal",language:e}),Fs=s=>{const e=[];let t=0,i=s.length-1;for(;t<Hd&&i>=0;)e.unshift(s[i]),t+=s[i].time.to-s[i].time.from,i--;return e};let mo=class{constructor(e,t,i,r,{fetcher:a,tuning:n,getCurrentPosition:o,compatibilityMode:u=!1,manifest:d}){switch(this.onLastSegment$=new T(!1),this.fullyBuffered$=new T(!1),this.playingRepresentation$=new T(void 0),this.playingRepresentationInit$=new T(void 0),this.error$=new C,this.gaps=[],this.isSeekingLive=!1,this.subscription=new ue,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new lt,this.destroyAbortController=new lt,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.startWith=ce(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 Lm(this.sourceBuffer),this.subscription.add(U(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},S=>this.error$.next({id:"SegmentEjection",category:R.WTF,message:"Error when trying to clear segments ejected by browser",thrown:S}))),this.subscription.add(U(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:R.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(S=>{if(!this.sourceBuffer)return;const b=Math.min(this.bufferLimit,ar(this.sourceBuffer.buffered)*.8);this.bufferLimit=b,this.pruneBuffer(this.getCurrentPosition(),S)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(S=>this.error$.next(S))),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=ce(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(j(f)||j(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();D(m)&&(this.searchGaps(h,c),this.maintain(m))}.bind(this)),this.seekLive=ce(this.destroyAbortController.signal,async function*(l){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!l)return;for(const b of this.representations.keys()){const v=l.find(E=>E.id===b);v&&this.representations.set(b,v);const y=this.representations.get(b);if(!y)return;const g=Fs(y.segmentReference.segments);this.segments.set(y.id,g)}const c=this.switchingToRepresentationId?this.switchingToRepresentationId:this.downloadingRepresentationId,h=this.representations.get(c);P(h);const f=Fs(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 S=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),S&&(yield this.sourceBufferTaskQueue.remove(S.from*1e3,S.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 Gi.MP4:this.containerParser=eg;break;case Gi.WEBM:this.containerParser=og;break;default:z(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 lt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(j(e)||j(this.downloadingRepresentationId)||j(this.playingRepresentationId)||j(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(P(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const r=i.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const l=Qe(this.sourceBuffer.buffered,e),c=r?r.time.to+100:-1/0;r&&l>=r.time.to-e+100&&(a=c)}if(isFinite(this.bufferLimit)&&ar(this.sourceBuffer.buffered)>=this.bufferLimit){const d=Qe(this.sourceBuffer.buffered,e),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<l);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{const l=Ie(o,0);l&&l.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}!this.isLive&&!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===oe.FED&&!o.length&&Qe(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const u=Ie(i,-1);u&&u.status===oe.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;D(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:oe.NONE,size:void 0})),u=(i=this.segments.get(n.id))!==null&&i!==void 0?i:[],d=(a=(r=Ie(u,-1))===null||r===void 0?void 0:r.time.to)!==null&&a!==void 0?a:0,l=o==null?void 0:o.findIndex(c=>Math.round(d)>=Math.round(c.time.from)&&Math.round(d)<=Math.round(c.time.to));if(l===-1){this.liveUpdateSegmentIndex=0;const c=Fs(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 S=h<=i&&f>=i,b=h>i||S||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&h<=i+v||f<=i+v;return(c===oe.NONE||c===oe.PARTIALLY_EJECTED&&b&&y&&this.sourceBuffer&&!Yi(this.sourceBuffer.buffered,i))&&b&&y});if(r===-1)return[];if(t!==dt.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===oe.NONE||h.status===oe.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 dt.BYTE_RANGE:{r=t.segmentReference.url,a={from:Ie(e,0).byte.from,to:Ie(e,-1).byte.to};break}case dt.TEMPLATE:{const d=Ie(e,0);r=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:z(o)}for(const d of n)d.status=oe.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:u}=this.downloadAbortController;if(this.failedDownloads&&(await ce(u,async function*(){const d=ms(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:R.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&&D(r)&&(i=Qe((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,i||this.error$.next({id:"SegmentDownload",category:R.NETWORK,message:"Error when fetching segments",thrown:e})}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=oe.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===oe.FED&&m.time.from===c.segment.time.from&&m.time.to===c.segment.time.to&&(m.status=oe.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===dt.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 b=f?h.byte.from-i:0,v=f?h.byte.to-i:e.byteLength,y=b<r,g=v<=r;if(h.status===oe.DOWNLOADING&&y&&g){h.status=oe.DOWNLOADED,this.activeSegments.delete(c);const E=new DataView(e.buffer,e.byteOffset+b,m);this.sourceBufferTaskQueue.append(E,a).then($=>$&&!a.aborted?o(c):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&y&&(c.loadedBytes=Math.min(m,r-b),c.loadedBytes>c.feedingBytes)){const E=new DataView(e.buffer,e.byteOffset+b+c.feedingBytes,c.loadedBytes-c.feedingBytes),$=c.loadedBytes===m?E:this.containerParser.parseFeedableSegmentChunk(E);$!=null&&$.byteLength&&(h.status=oe.PARTIALLY_FED,c.feedingBytes+=$.byteLength,this.sourceBufferTaskQueue.append($,a).then(L=>{if(a.aborted)n();else if(L)c.fedBytes+=$.byteLength,c.fedBytes===m&&o(c);else{if(c.feedingBytes<m)return;n()}}))}}}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===oe.PARTIALLY_FED||e.status===oe.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=oe.NONE),e.status=oe.PARTIALLY_EJECTED):e.status=oe.NONE;for(const i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,a]of this.initData.entries()){const n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=rr(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?ce(this.destroyAbortController.signal,async function*(){const o=ms(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(async o=>{if(!o)return;const{init:u,dataView:d,segments:l}=o,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c),this.segments.set(e.id,this.isLive?Fs(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:R.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||j(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,n=-1/0,o=!1;const u=d=>{var l;a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const c="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===oe.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===oe.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===oe.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===oe.FED&&u(c)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=rr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:R.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(j(this.sourceBuffer)||j(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}const t=1;for(const i of this.segments.values())for(const r of i){const{status:a}=r;if(a!==oe.FED&&a!==oe.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=oe.PARTIALLY_EJECTED:r.status=oe.NONE)}}};var Fi;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(Fi||(Fi={}));let mg=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new T(void 0),this.lastConnectionReused$=new T(void 0),this.lastRequestFirstBytes$=new T(void 0),this.abortAllController=new lt,this.subscription=new ue,this.fetchManifest=ce(this.abortAllController.signal,async function*(r){let a=r;this.requestQuic&&(a=ii(a));const n=yield $i(a,{signal:this.abortAllController.signal}).catch(us);return n?(this.onHeadersReceived(n.headers),n.text()):null}.bind(this)),this.fetch=ce(this.abortAllController.signal,async function*(r,{rangeMethod:a=this.compatibilityMode?Fi.HEADER:Fi.PARAM,range:n,onProgress:o,priority:u="auto",signal:d,measureThroughput:l=!0}={}){var c,h,f,m;let S=r;const b=new Headers;if(n)switch(a){case Fi.HEADER:{b.append("Range",`bytes=${n.from}-${n.to}`);break}case Fi.PARAM:{const Y=new URL(S,location.href);Y.searchParams.append("bytes",`${n.from}-${n.to}`),S=Y.toString();break}default:z(a)}this.requestQuic&&(S=ii(S));let v=this.abortAllController.signal,y;if(d){const Y=new lt;if(y=H(U(this.abortAllController.signal,"abort"),U(d,"abort")).subscribe(()=>{try{Y.abort()}catch(te){us(te)}}),this.abortAllController.signal.aborted||d.aborted)try{Y.abort()}catch(te){us(te)}v=Y.signal}const g=le(),E=yield $i(S,{priority:u,headers:b,signal:v}).catch(us),$=le();if((c=this.throughputEstimator)===null||c===void 0||c.addRawRtt($-g),!E)return y==null||y.unsubscribe(),null;if(!E.ok||!E.body)return y==null||y.unsubscribe(),Promise.reject(new Error(`Fetch error ${E.status}: ${E.statusText}`));this.onHeadersReceived(E.headers);const L=parseInt((h=E.headers.get("Content-Length"))!==null&&h!==void 0?h:"",10)||n&&n.to-n.from+1||NaN;if(!L){const Y=yield E.arrayBuffer();return(f=this.throughputEstimator)===null||f===void 0||f.addRawSpeed(Y.byteLength,le()-$),o==null||o(new DataView(Y),Y.byteLength),y==null||y.unsubscribe(),Y}if(!o&&!l)return y==null||y.unsubscribe(),E.arrayBuffer();const[G,Q]=E.body.tee(),V=G.getReader();l&&((m=this.throughputEstimator)===null||m===void 0||m.trackStream(Q));let q=0;const W=new ArrayBuffer(L),B=new Uint8Array(W),M=new DataView(W);let K=!1;const O=Y=>{y==null||y.unsubscribe(),K=!0,us(Y)},x=ce(v,async function*({done:Y,value:te}){if(q===0&&this.lastRequestFirstBytes$.next(le()-g),v.aborted){y==null||y.unsubscribe();return}!Y&&te&&(B.set(te,q),q+=te.byteLength,o==null||o(M,q),yield V==null?void 0:V.read().then(x,O))}.bind(this));return yield V==null?void 0:V.read().then(x,O),y==null||y.unsubscribe(),K?null:W}.bind(this)),this.fetchByteRangeRepresentation=ce(this.abortAllController.signal,async function*(r,a,n){var o;if(r.type!==dt.BYTE_RANGE)return null;const{from:u,to:d}=r.initRange;let l=u,c=d,h=!1,f,m;r.indexRange&&(f=r.indexRange.from,m=r.indexRange.to,h=d+1===f,h&&(l=Math.min(f,u),c=Math.max(m,d))),l=Math.min(l,0);const S=yield this.fetch(r.url,{range:{from:l,to:c},priority:n,measureThroughput:!1});if(!S)return null;const b=new DataView(S,u-l,d-l+1);if(!a.validateData(b))throw new Error("Invalid media file");const v=a.parseInit(b),y=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(v);if(!y)throw new ReferenceError("No way to load representation index");let g;if(h)g=new DataView(S,y.from-l,y.to-y.from+1);else{const $=yield this.fetch(r.url,{range:y,priority:n,measureThroughput:!1});if(!$)return null;g=new DataView($)}const E=a.parseSegments(g,v,y);return{init:v,dataView:new DataView(S),segments:E}}.bind(this)),this.fetchTemplateRepresentation=ce(this.abortAllController.signal,async function*(r,a){if(r.type!==dt.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:oe.NONE,size:void 0})),dataView:new DataView(o)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=cn(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var r,a;const{type:n}=e;switch(n){case dt.BYTE_RANGE:return(r=await this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case dt.TEMPLATE:return(a=await this.fetchTemplateRepresentation(e,i))!==null&&a!==void 0?a:null;default:z(n)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}};const us=s=>{if(!(s instanceof DOMException)||!(s.name==="AbortError"||s.code===20))throw s};var gg=Ai,vg=mr,Sg=bt,bg=Sg("match"),yg=function(s){var e;return gg(s)&&((e=s[bg])!==void 0?!!e:vg(s)=="RegExp")},Tg=Tr,Eg=String,$g=function(s){if(Tg(s)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return Eg(s)},Ag=ki,wg=function(){var s=Ag(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},kg=jt,_g=Wt,Pg=Xa,Dg=wg,go=RegExp.prototype,Rg=function(s){var e=s.flags;return e===void 0&&!("flags"in go)&&!_g(s,"flags")&&Pg(go,s)?kg(Dg,s):e},hn=qt,Ig=Sr,Lg=Math.floor,la=hn("".charAt),xg=hn("".replace),ca=hn("".slice),Cg=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Bg=/\$([$&'`]|\d{1,2})/g,Mg=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=Bg;return r!==void 0&&(r=Ig(r),u=Cg),xg(a,u,function(d,l){var c;switch(la(l,0)){case"$":return"$";case"&":return s;case"`":return ca(e,0,t);case"'":return ca(e,n);case"<":c=r[ca(l,1,-1)];break;default:var h=+l;if(h===0)return d;if(h>o){var f=Lg(h/10);return f===0?d:f<=o?i[f-1]===void 0?la(l,1):i[f-1]+la(l,1):d}c=i[h-1]}return c===void 0?"":c})},Og=yr,Ng=jt,fn=qt,vo=Qa,Fg=ct,Ug=gr,Vg=yg,Ci=$g,Hg=vr,Gg=Rg,Yg=Mg,zg=bt,qg=zg("replace"),jg=TypeError,Gd=fn("".indexOf),Wg=fn("".replace),So=fn("".slice),Qg=Math.max,bo=function(s,e,t){return t>s.length?-1:e===""?t:Gd(s,e,t)};Og({target:"String",proto:!0},{replaceAll:function(e,t){var i=vo(this),r,a,n,o,u,d,l,c,h,f=0,m=0,S="";if(!Ug(e)){if(r=Vg(e),r&&(a=Ci(vo(Gg(e))),!~Gd(a,"g")))throw jg("`.replaceAll` does not allow non-global regexes");if(n=Hg(e,qg),n)return Ng(n,e,i,t);if(r)return Wg(Ci(i),e,t)}for(o=Ci(i),u=Ci(e),d=Fg(t),d||(t=Ci(t)),l=u.length,c=Qg(1,l),f=bo(o,u,0);f!==-1;)h=d?Ci(t(u,f,o)):Yg(u,o,f,[],void 0,t),S+=So(o,m,f)+h,m=f+l,f=bo(o,u,f+c);return m<o.length&&(S+=So(o,m)),S}});var Kg=Rd,Jg=Kg("String","replaceAll"),Xg=Jg,Zg=Xg,ev=Zg,tv=ev,or=Wa(tv);const yo=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},ha=(s,e)=>{let t=s;t=or(t,"$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,a]of Object.entries(i)){const n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=or(t,n,(o,u)=>j(a)?o:j(u)?a:a.padStart(parseInt(u,10),"0"))}return t},iv=(s,e)=>{var t,i,r,a,n,o,u,d,l,c,h,f,m,S,b,v,y,g,E,$,L,G,Q,V,q,W,B,M,K,O,x,Y,te,fe,be,Pe,ze,rt,ie;const qe=new DOMParser().parseFromString(s,"application/xml"),De={video:[],audio:[],text:[]},we=qe.children[0],Ct=we.getElementsByTagName("Period")[0],Bt=Ct.children,Xt=we.getAttribute("type")==="dynamic",Mt=we.getAttribute("availabilityStartTime"),Pi=Mt?new Date(Mt).getTime():void 0;let Ne;const Xi=we.getAttribute("mediaPresentationDuration"),Zi=Ct.getAttribute("duration"),ni=we.getElementsByTagName("vk:Attrs")[0],es=ni==null?void 0:ni.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(Xi)Ne=yo(Xi);else if(Zi){const ye=yo(Zi);D(ye)&&(Ne=ye)}else es&&(Ne=parseInt(es,10));let kr=0;const oi=(i=(t=we.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],_r=oi.includes(ir.WEBM_AS_IN_FFMPEG)||oi.includes(ir.WEBM_AS_IN_SPEC)?Gi.WEBM:Gi.MP4;for(const ye of Bt){const Ot=ye.getAttribute("mimeType"),Pr=ye.getAttribute("codecs"),ts=(r=ye.getAttribute("contentType"))!==null&&r!==void 0?r:Ot==null?void 0:Ot.split("/")[0],Dr=(n=(a=ye.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],is=ye.querySelectorAll("Representation"),Rr=ye.querySelector("SegmentTemplate");if(ts===Be.TEXT){for(const J of is){const Re=J.getAttribute("id")||"",Nt=ye.getAttribute("lang"),Ke=(d=(u=(o=J.querySelector("BaseURL"))===null||o===void 0?void 0:o.textContent)===null||u===void 0?void 0:u.trim())!==null&&d!==void 0?d:"",di=new URL(Ke,e).toString(),ui=Re.includes("_auto");De[Be.TEXT].push({id:Re,lang:Nt,isAuto:ui,kind:Be.TEXT,url:di})}continue}for(const J of is){const Re=(l=J.getAttribute("mimeType"))!==null&&l!==void 0?l:Ot,Nt=(h=(c=J.getAttribute("codecs"))!==null&&c!==void 0?c:Pr)!==null&&h!==void 0?h:"",Ke=(m=(f=J.getAttribute("contentType"))!==null&&f!==void 0?f:Re==null?void 0:Re.split("/")[0])!==null&&m!==void 0?m:ts,di=(b=(S=ye.getAttribute("profiles"))===null||S===void 0?void 0:S.split(","))!==null&&b!==void 0?b:[],ui=parseInt((v=J.getAttribute("width"))!==null&&v!==void 0?v:"",10),ss=parseInt((y=J.getAttribute("height"))!==null&&y!==void 0?y:"",10),rs=parseInt((g=J.getAttribute("bandwidth"))!==null&&g!==void 0?g:"",10)/1e3,as=(E=J.getAttribute("frameRate"))!==null&&E!==void 0?E:"",Ir=($=J.getAttribute("quality"))!==null&&$!==void 0?$:void 0,Lr=as?Er(as):void 0,xr=(L=J.getAttribute("id"))!==null&&L!==void 0?L:(kr++).toString(10),Cr=Ke==="video"?`${ss}p`:Ke==="audio"?`${rs}Kbps`:Nt,Br=`${xr}@${Cr}`,Mr=(V=(Q=(G=J.querySelector("BaseURL"))===null||G===void 0?void 0:G.textContent)===null||Q===void 0?void 0:Q.trim())!==null&&V!==void 0?V:"",ns=new URL(Mr,e).toString(),Or=[...oi,...Dr,...di];let li;const Nr=J.querySelector("SegmentBase"),Fe=(q=J.querySelector("SegmentTemplate"))!==null&&q!==void 0?q:Rr;if(Nr){const Je=(B=(W=J.querySelector("SegmentBase Initialization"))===null||W===void 0?void 0:W.getAttribute("range"))!==null&&B!==void 0?B:"",[Xe,hi]=Je.split("-").map(Ze=>parseInt(Ze,10)),je={from:Xe,to:hi},ft=(M=J.querySelector("SegmentBase"))===null||M===void 0?void 0:M.getAttribute("indexRange"),[fi,Ft]=ft?ft.split("-").map(Ze=>parseInt(Ze,10)):[],pt=ft?{from:fi,to:Ft}:void 0;li={type:dt.BYTE_RANGE,url:ns,initRange:je,indexRange:pt}}else if(Fe){const Je={representationId:(K=J.getAttribute("id"))!==null&&K!==void 0?K:void 0,bandwidth:(O=J.getAttribute("bandwidth"))!==null&&O!==void 0?O:void 0},Xe=parseInt((x=Fe.getAttribute("timescale"))!==null&&x!==void 0?x:"",10),hi=(Y=Fe.getAttribute("initialization"))!==null&&Y!==void 0?Y:"",je=Fe.getAttribute("media"),ft=(fe=parseInt((te=Fe.getAttribute("startNumber"))!==null&&te!==void 0?te:"",10))!==null&&fe!==void 0?fe:1,fi=ha(hi,Je);if(!je)throw new ReferenceError("No media attribute in SegmentTemplate");const Ft=(be=Fe.querySelectorAll("SegmentTimeline S"))!==null&&be!==void 0?be:[],pt=[];let Ze=0;if(Ft.length){let pi=ft,et=0;for(const mi of Ft){const tt=parseInt((Pe=mi.getAttribute("d"))!==null&&Pe!==void 0?Pe:"",10),ke=parseInt((ze=mi.getAttribute("r"))!==null&&ze!==void 0?ze:"",10)||0,mt=parseInt((rt=mi.getAttribute("t"))!==null&&rt!==void 0?rt:"",10);et=Number.isFinite(mt)?mt:et;const We=tt/Xe*1e3,Tt=et/Xe*1e3;for(let Ut=0;Ut<ke+1;Ut++){const os=ha(je,{...Je,segmentNumber:pi.toString(10),segmentTime:(et+Ut*tt).toString(10)}),Di=(Tt||0)+Ut*We,Ri=Di+We;pi++,pt.push({time:{from:Di,to:Ri},url:os})}et+=(ke+1)*tt,Ze+=(ke+1)*We}}else if(D(Ne)){const et=parseInt((ie=Fe.getAttribute("duration"))!==null&&ie!==void 0?ie:"",10)/Xe*1e3,mi=Math.ceil(Ne/et);let tt=0;for(let ke=1;ke<mi;ke++){const mt=ha(je,{...Je,segmentNumber:ke.toString(10),segmentTime:tt.toString(10)});pt.push({time:{from:tt,to:tt+et},url:mt}),tt+=et}}li={type:dt.TEMPLATE,baseUrl:ns,initUrl:fi,totalSegmentsDurationMs:Ze,segments:pt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ke||!Re)continue;const ci={video:Be.VIDEO,audio:Be.AUDIO,text:Be.TEXT}[Ke];ci&&De[ci].push({id:Br,kind:ci,segmentReference:li,profiles:Or,duration:Ne,bitrate:rs,mime:Re,codecs:Nt,width:ui,height:ss,fps:Lr,quality:Ir})}}return{dynamic:Xt,liveAvailabilityStartTime:Pi,duration:Ne,container:_r,representations:De}},Ha=1e3,To=["timeupdate","progress","play","seeked","stalled","waiting"];var nt;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(nt||(nt={}));let sv=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new ue,this.representationSubscription=new ue,this.state$=new he(nt.NONE),this.currentVideoRepresentation$=new T(void 0),this.currentVideoRepresentationInit$=new T(void 0),this.error$=new C,this.lastConnectionType$=new T(void 0),this.lastConnectionReused$=new T(void 0),this.lastRequestFirstBytes$=new T(void 0),this.isLive$=new T(!1),this.liveDuration$=new T(0),this.liveAvailabilityStartTime$=new T(void 0),this.bufferLength$=new T(0),this.liveLoadBufferLength$=new T(0),this.forceEnded$=new C,this.gapWatchdogStarted=!1,this.destroyController=new lt,this.initManifest=ce(this.destroyController.signal,async function*(t,i,r){var a;this.element=t,this.manifestUrlString=He(i,r,Se.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(nt.MANIFEST_READY),this.manifest=yield this.updateManifest(),!((a=this.manifest)===null||a===void 0)&&a.representations.video.length?this.state$.setState(nt.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:R.PARSER,message:"No playable video representations"})}.bind(this)),this.updateManifest=ce(this.destroyController.signal,async function*(){var t;const i=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:R.NETWORK,message:"Failed to load manifest",thrown:n})});if(!i)return this.manifest;let r;try{r=iv(i!=null?i:"",this.manifestUrlString)}catch(n){this.error$.next({id:"ManifestParsing",category:R.PARSER,message:"Failed to parse MPD manifest",thrown:n})}if(!r)return null;const a=({kind:n,mime:o,codecs:u})=>{var d,l,c,h;return!!(!((l=(d=this.element)===null||d===void 0?void 0:d.canPlayType)===null||l===void 0)&&l.call(d,o)&&(!((h=(c=window.MediaSource)===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0)&&h.call(c,`${o}; codecs="${u}"`))||n===Be.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:Ei(Object.entries(r.representations).map(([n,o])=>[n,o.filter(a)]))}}.bind(this)),this.initRepresentations=ce(this.destroyController.signal,async function*(t,i){P(this.manifest),P(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(nt.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 mo(Be.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],D(i)&&(this.audioBufferManager=new mo(Be.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,r),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Ti(Ha).subscribe(o=>{var u;if(!((u=this.element)===null||u===void 0)&&u.paused){const d=er(this.manifestUrlString,Se.DASH_CMAF_OFFSET_P);this.manifestUrlString=He(this.manifestUrlString,d+1e3,Se.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(H(...To.map(o=>U(this.element,o))).pipe(uu(Ha),_(o=>this.element?Qe(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 S,b;return(b=(S=m.getLiveSegmentsToLoadState(this.manifest))===null||S===void 0?void 0:S.to)!==null&&b!==void 0?b: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=er(this.manifestUrlString,Se.DASH_CMAF_OFFSET_P),c=dg*d,h=lg*d,f=ug*d;o=u>o?u:o;const m=l===0&&u<f,S=l!==0&&u<c+f&&u>=c,b=l!==0&&u<c;if(b||S){const v=o-(c+h),y=Math.trunc(l+v/d);let g;u?y>0?g=y:g=0:g=l,this.manifestUrlString=He(this.manifestUrlString,g,Se.DASH_CMAF_OFFSET_P)}(m||b||S)&&(await this.updateLive(),o=0)}))}const a=H(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(_(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=H(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(_(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.representationSubscription.add(H(this.forceEnded$,Le({allBuffersFull:a,someBufferEnded:n}).pipe(ae(({allBuffersFull:o,someBufferEnded:u})=>o&&u))).subscribe(()=>{var o;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(u=>!u.updating))try{(o=this.source)===null||o===void 0||o.endOfStream()}catch(u){this.error$.next({id:"EndOfStream",category:R.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:u})}})),this.representationSubscription.add(H(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield new Promise(o=>{var u;return(u=this.source)===null||u===void 0?void 0:u.addEventListener("sourceopen",o)})),D(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&D(i)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)]):yield this.videoBufferManager.startWith(t),this.state$.setState(nt.REPRESENTATIOS_READY)}.bind(this)),this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((i=this.audioBufferManager)===null||i===void 0)&&i.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=Ti(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:R.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new mg({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,Se.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(nt.RUNNING),this.subscription.add(H(...To.map(e=>U(this.element,e)),U(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:R.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(U(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(U(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Yi(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){const i={[Be.VIDEO]:this.videoBufferManager,[Be.AUDIO]:this.audioBufferManager,[Be.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)}seek(e,t){var i,r,a,n,o;P(this.element),P(this.videoBufferManager);let u;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?u=e:u=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!==null&&i!==void 0?i:e,(a=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&a!==void 0?a:e),Yi(this.element.buffered,u)||(this.videoBufferManager.abort(),(n=this.audioBufferManager)===null||n===void 0||n.abort()),this.videoBufferManager.maintain(u),(o=this.audioBufferManager)===null||o===void 0||o.maintain(u),this.element.currentTime=u/1e3}stop(){var e,t;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(e=this.videoBufferManager)===null||e===void 0||e.destroy(),this.videoBufferManager=null,(t=this.audioBufferManager)===null||t===void 0||t.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(nt.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 rv{constructor(e,t){this.fov=e,this.orientation=t}}class av{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 nv=`#define GLSLIFY 1
|
|
38
|
+
attribute vec2 a_vertex;attribute vec2 a_texel;varying vec2 v_texel;void main(void){gl_Position=vec4(a_vertex,0.0,1.0);v_texel=a_texel;}`,ov=`#ifdef GL_ES
|
|
39
39
|
precision highp float;precision highp int;
|
|
40
40
|
#else
|
|
41
41
|
precision highp float;
|
|
42
42
|
#define GLSLIFY 1
|
|
43
43
|
#endif
|
|
44
44
|
#define PI 3.14159265358979323846264
|
|
45
|
-
varying vec2 v_texel;uniform sampler2D u_texture;uniform vec2 u_focus;void main(void){float lambda0=u_focus.x/360.0;float phi0=u_focus.y/180.0;float lambda=PI*2.0*(v_texel.x-0.5-lambda0);float phi=PI*(v_texel.y-0.5-phi0);float p=sqrt(lambda*lambda+phi*phi);float c=atan(p);float cos_c=cos(c);float sin_c=sin(c);float x=lambda0+atan(lambda*sin_c,p*cos(phi0)*cos_c-phi*sin(phi0)*sin_c);float y=asin(cos_c*sin(phi0)+(phi*sin_c*cos(phi0))/p);vec2 tc=vec2(mod(x/(PI*2.0)-0.5,1.0),mod(y/PI-0.5,1.0));gl_FragColor=texture2D(u_texture,tc);}`;class Hd{constructor(e,t,i){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();const r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new sv(this.params.fov,this.params.orientation),this.cameraRotationManager=new rv(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(av,this.gl.VERTEX_SHADER),i=this.createShader(nv,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1;const r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,n=t-r,o=e+i,u=t-r,d=e+i,l=t+r,c=e-i,h=t+r;return[a,n,o,u,d,l,c,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){const e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}}let Gd=class{constructor(e){this.subscription=new ue,this.videoState=new he(Te.STOPPED),this.elementSize$=new T(void 0),this.textTracksManager=new yt,this.droppedFramesManager=new ks,this.videoTracks$=new T([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Dd,this.textTracks=[],this.syncPlayback=()=>{var t,i,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(u.state===ee.Requested&&(o==null?void 0:o.to)!==p.PAUSED&&a!==Te.STOPPED&&n!==p.STOPPED){const l=(i=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&i!==void 0?i:0;this.seek(u.position-l,u.forcePrecise)}if(n===p.STOPPED){a!==Te.STOPPED&&(this.videoState.startTransitionTo(Te.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Te.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}switch(a){case Te.STOPPED:this.videoState.startTransitionTo(Te.READY),this.prepare();return;case Te.READY:n===p.PAUSED?(this.videoState.setState(Te.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING?(this.videoState.startTransitionTo(Te.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.READY&&I(this.params.desiredState.playbackState,p.READY);return;case Te.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(Te.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case Te.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(Te.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return q(a)}}},this.init3DScene=t=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Hd(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=t.projectionData)===null||i===void 0?void 0:i.pose.yaw)||0,y:((r=t.projectionData)===null||r===void 0?void 0:r.pose.pitch)||0,z:((a=t.projectionData)===null||a===void 0?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const n=this.elementSize$.getValue();n&&this.scene3D.setViewportSize(n.width,n.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=Rt(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ge(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new iv({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=Lt(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:R.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(_(d=>d.map(({track:l})=>l)))}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(ae(D),Ae()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ri(this.video,t.isLooped,r)),this.subscription.add(Dt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Qt(this.video,t.playbackRate,i.playbackRateState$,r)),a(bs(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(Te.PLAYING),I(t.playbackState,p.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(Te.PAUSED),I(t.playbackState,p.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===Te.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d===at.MANIFEST_READY){const c=[];this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();P(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((g,y)=>y.bitrate-g.bitrate),m=Array.from(h.video).sort((g,y)=>y.bitrate-g.bitrate),S=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const g of f){const y=cg(g);y&&this.audioTracks.push({track:y,representation:g})}for(const g of m){const y=lg(g);if(y){c.push({track:y,representation:g});const v=!this.params.tuning.isAudioDisabled&&hg(f,m,g);v&&this.audioRepresentations.set(g.id,v)}}this.videoTracks$.next(c);for(const g of S){const y=fg(g);y&&this.textTracks.push({track:y,representation:g})}this.params.output.availableVideoTracks$.next(c.map(({track:g})=>g)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:g})=>g)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:g})=>g));const b=this.selectVideoRepresentation();P(b),this.player.initRepresentations(b.id,(l=this.audioRepresentations.get(b.id))===null||l===void 0?void 0:l.id)}else d===at.REPRESENTATIOS_READY&&(this.videoState.setState(Te.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:R.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(H(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,U(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!==at.RUNNING||l||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation(),h=this.params.desiredState.autoVideoTrackLimits.getTransition();if(h&&this.params.output.autoVideoTrackLimits$.next(h.to),c){this.player.switchRepresentation(Ce.VIDEO,c.id).catch(n);const f=this.audioRepresentations.get(c.id);f&&this.player.switchRepresentation(Ce.AUDIO,f.id).catch(n)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ve(),_(d=>{var l;return d&&((l=this.videoTracks$.getValue().find(({representation:{id:c}})=>c===d))===null||l===void 0?void 0:l.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var l,c;if(d!=null&&d.is3dVideo&&(!((l=this.params.tuning.spherical)===null||l===void 0)&&l.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe(_(({to:d})=>d===p.READY),ve());this.subscription.add(H(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===p.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(H(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===p.READY)));const u=H(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,He(["init"])).pipe(it(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,i,r,a,n,o;const u=this.params.desiredState.autoVideoTrackSwitching.getState(),d=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id,l=(t=this.videoTracks$.getValue().find(({track:{id:y}})=>y===d))===null||t===void 0?void 0:t.track,c=this.params.output.currentVideoTrack$.getValue(),h=We(this.video.buffered,this.video.currentTime*1e3),f=u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=Math.min(h/Math.min(f,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),S=Math.max(l&&!u&&(r=(i=this.audioRepresentations.get(l.id))===null||i===void 0?void 0:i.bitrate)!==null&&r!==void 0?r:0,c&&(n=(a=this.audioRepresentations.get(c.id))===null||a===void 0?void 0:a.bitrate)!==null&&n!==void 0?n:0),b=_i(this.videoTracks$.getValue().map(({track:y})=>y),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:m,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),g=u?b!=null?b:l:l!=null?l:b;return g&&((o=this.videoTracks$.getValue().find(({track:y})=>y===g))===null||o===void 0?void 0:o.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Kt(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(Te.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),It(this.video)}},ov=class extends Gd{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var Be;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(Be||(Be={}));var At;(function(s){s[s.ActiveLowLatency=0]="ActiveLowLatency",s[s.LiveWithTargetOffset=1]="LiveWithTargetOffset",s[s.LiveForwardBuffering=2]="LiveForwardBuffering",s[s.None=3]="None"})(At||(At={}));var dr;(function(s){s.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",s.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(dr||(dr={}));var dt;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(dt||(dt={}));var Z;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(Z||(Z={}));var zi;(function(s){s.MP4="mp4",s.WEBM="webm"})(zi||(zi={}));var ur;(function(s){s[s.RECTANGULAR=0]="RECTANGULAR",s[s.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",s[s.CUBEMAP=2]="CUBEMAP",s[s.MESH=3]="MESH"})(ur||(ur={}));var Ee;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Ee||(Ee={}));var fa,pa;let Yd=!1;try{Yd=hr().browser===qa.Safari&&parseInt((pa=(fa=navigator.userAgent.match(/Version\/(\d+)/))===null||fa===void 0?void 0:fa[1])!==null&&pa!==void 0?pa:"",10)<16}catch(s){console.error(s)}class dv{constructor(e){this.bufferFull$=new C,this.error$=new C,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const i=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!i),this.currentTask=null}this.queue.length&&this.pull()}catch(i){this.error$.next({id:"BufferTaskQueueUnknown",category:R.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i;Yd&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:i}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&i==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${i}`,category:R.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:q(t)}}}class ct{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 qd extends ct{}class uv extends ct{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 lv extends ct{parseChildrenBoxes(){return ai(this.content)}}class cv extends ct{parseChildrenBoxes(){return ai(this.content)}}class hv extends ct{constructor(e){super(e),this.data=this.content}}class Jt extends ct{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class fv extends Jt{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let i=this.readUint32();const r=i>>>31,a=i<<1>>>1,n=this.readUint32();i=this.readUint32();const o=i>>>28,u=i<<3>>>3;this.segments.push({referenceType:r,referencedSize:a,subsegmentDuration:n,SAPType:o,SAPDeltaTime:u})}}}class pv extends ct{parseChildrenBoxes(){return ai(this.content)}}class mv extends ct{parseChildrenBoxes(){return ai(this.content)}}var bi;(function(s){s[s.MONOSCOPIC=0]="MONOSCOPIC",s[s.TOP_BOTTOM=1]="TOP_BOTTOM",s[s.LEFT_RIGHT=2]="LEFT_RIGHT",s[s.STEREO_CUSTOM=3]="STEREO_CUSTOM",s[s.RIGHT_LEFT=4]="RIGHT_LEFT"})(bi||(bi={}));class gv extends Jt{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=bi.MONOSCOPIC;break;case 1:this.stereoMode=bi.TOP_BOTTOM;break;case 2:this.stereoMode=bi.LEFT_RIGHT;break;case 3:this.stereoMode=bi.STEREO_CUSTOM;break;case 4:this.stereoMode=bi.RIGHT_LEFT;break}this.cursor+=1}}class vv extends Jt{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class Sv extends Jt{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class bv extends ct{parseChildrenBoxes(){return ai(this.content)}}class yv extends Jt{constructor(e){super(e),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}}class Tv extends ct{parseChildrenBoxes(){return ai(this.content)}}class Ev extends ct{parseChildrenBoxes(){return ai(this.content)}}class $v extends Jt{constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class Av extends ct{parseChildrenBoxes(){return ai(this.content)}}class kv extends Jt{constructor(e){super(e),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}}class wv extends Jt{get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e){super(e),this.baseMediaDecodeTime32=0,this.baseMediaDecodeTime64=BigInt(0),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class _v extends Jt{constructor(e){super(e),this.sampleDuration=[],this.sampleSize=[],this.sampleFlags=[],this.sampleCompositionTimeOffset=[],this.optionalFields=0,this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let t=0;t<this.sampleCount;t++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}}const Pv={ftyp:uv,moov:lv,moof:cv,mdat:hv,sidx:fv,trak:pv,mdia:bv,mfhd:$v,tkhd:yv,traf:Av,tfhd:kv,tfdt:wv,trun:_v,minf:Tv,sv3d:mv,st3d:gv,prhd:vv,proj:Ev,equi:Sv,unknown:qd};class Dv{createBox(e,t){const i=Pv[e];return i?new i(t):new qd(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return kr.createBox(i,new DataView(e.buffer,e.byteOffset))}}const kr=new Dv;function ps(s,e){const t=new Uint8Array(s.buffer),i=e.split("").map(n=>n.charCodeAt(0));let r=s.byteOffset,a=[];for(;r<t.byteLength;){if(t[r]===i[a.length]?a.push(t[r]):a=[],a.length===4){const o=new DataView(s.buffer,r-7,4).getUint32(0);return r-7+o>s.buffer.byteLength?null:kr.createBox(e,new DataView(s.buffer,r-7))}r++}return null}function Va(s,e){const t=[];let i=s.byteOffset;for(;i<s.buffer.byteLength;){const r=ps(new DataView(s.buffer,i,s.buffer.byteLength-i),e);if(r)t.push(r),i=r.source.byteOffset+r.size;else break}return t}function ai(s){const e=[];let t=0;for(;t<s.byteLength;){const i=kr.createFromView(new DataView(s.buffer,s.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const Rv=new TextDecoder("ascii"),Iv=s=>Rv.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",Lv=s=>{const e=kr.createFromView(s);let t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=a.subsegmentDuration/e.timescale*1e3,o={status:Z.NONE,time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},xv=s=>{const e=Va(s,"mdat"),t=Va(s,"moof");if(!(e.length&&t.length))return null;const i=t[0],r=e[e.length-1],a=i.source.byteOffset,o=r.source.byteOffset-i.source.byteOffset+r.size;return new DataView(s.buffer,a,o)},Cv=(s,e)=>{const t=Va(s,"traf"),i=t[t.length-1].children.find(u=>u.type==="tfhd"),r=t[t.length-1].children.find(u=>u.type==="tfdt"),a=t[t.length-1].children.find(u=>u.type==="trun");let n=0;return a.sampleDuration.length?n=a.sampleDuration.reduce((u,d)=>u+d,0):n=i.defaultSampleDuration*a.sampleCount,(Number(r.baseMediaDecodeTime)+n)/e*1e3},Bv=s=>{const e={is3dVideo:!1,stereoMode:0,projectionType:ur.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(ps(s,"sv3d")){e.is3dVideo=!0;const i=ps(s,"st3d");i&&(e.stereoMode=i.stereoMode);const r=ps(s,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const a=ps(s,"equi");a&&(e.projectionData.bounds.top=a.projectionBoundsTop,e.projectionData.bounds.right=a.projectionBoundsRight,e.projectionData.bounds.bottom=a.projectionBoundsBottom,e.projectionData.bounds.left=a.projectionBoundsLeft)}return e},Ov={validateData:Iv,parseInit:Bv,getIndexRange:()=>{},parseSegments:Lv,parseFeedableSegmentChunk:xv,getSegmentEndTime:Cv};var w;(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"})(w||(w={}));var F;(function(s){s.SignedInteger="int",s.UnsignedInteger="uint",s.Float="float",s.String="string",s.UTF8="utf8",s.Date="date",s.Master="master",s.Binary="binary"})(F||(F={}));const yo={[w.EBML]:{type:F.Master},[w.EBMLVersion]:{type:F.UnsignedInteger},[w.EBMLReadVersion]:{type:F.UnsignedInteger},[w.EBMLMaxIDLength]:{type:F.UnsignedInteger},[w.EBMLMaxSizeLength]:{type:F.UnsignedInteger},[w.DocType]:{type:F.String},[w.DocTypeVersion]:{type:F.UnsignedInteger},[w.DocTypeReadVersion]:{type:F.UnsignedInteger},[w.Void]:{type:F.Binary},[w.Segment]:{type:F.Master},[w.SeekHead]:{type:F.Master},[w.Seek]:{type:F.Master},[w.SeekID]:{type:F.Binary},[w.SeekPosition]:{type:F.UnsignedInteger},[w.Info]:{type:F.Master},[w.TimestampScale]:{type:F.UnsignedInteger},[w.Duration]:{type:F.Float},[w.Tracks]:{type:F.Master},[w.TrackEntry]:{type:F.Master},[w.Video]:{type:F.Master},[w.Projection]:{type:F.Master},[w.ProjectionType]:{type:F.UnsignedInteger},[w.ProjectionPrivate]:{type:F.Master},[w.Chapters]:{type:F.Master},[w.Cluster]:{type:F.Master},[w.Timestamp]:{type:F.UnsignedInteger},[w.SilentTracks]:{type:F.Master},[w.SilentTrackNumber]:{type:F.UnsignedInteger},[w.Position]:{type:F.UnsignedInteger},[w.PrevSize]:{type:F.UnsignedInteger},[w.SimpleBlock]:{type:F.Binary},[w.BlockGroup]:{type:F.Master},[w.EncryptedBlock]:{type:F.Binary},[w.Attachments]:{type:F.Master},[w.Tags]:{type:F.Master},[w.Cues]:{type:F.Master},[w.CuePoint]:{type:F.Master},[w.CueTime]:{type:F.UnsignedInteger},[w.CueTrackPositions]:{type:F.Master},[w.CueTrack]:{type:F.UnsignedInteger},[w.CueClusterPosition]:{type:F.UnsignedInteger},[w.CueRelativePosition]:{type:F.UnsignedInteger},[w.CueDuration]:{type:F.UnsignedInteger},[w.CueBlockNumber]:{type:F.UnsignedInteger},[w.CueCodecState]:{type:F.UnsignedInteger},[w.CueReference]:{type:F.Master},[w.CueRefTime]:{type:F.UnsignedInteger}},zd=s=>{const e=s.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=lr(s,t),r=i in yo,a=r?yo[i].type:F.Binary,n=s.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const u=new DataView(s.buffer,s.byteOffset+t+1,o-1),d=n&255>>o,l=lr(u),c=d*2**((o-1)*8)+l,h=t+o;let f;return h+c>s.byteLength?f=new DataView(s.buffer,s.byteOffset+h):f=new DataView(s.buffer,s.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:f,valueSize:c}},lr=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{const t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},_t=(s,e)=>{switch(e){case F.SignedInteger:return s.getInt8(0);case F.UnsignedInteger:return lr(s);case F.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case F.String:return new TextDecoder("ascii").decode(s);case F.UTF8:return new TextDecoder("utf-8").decode(s);case F.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case F.Master:return s;case F.Binary:return s;default:q(e)}},ji=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=zd(i);if(!e(r))return;r.type===F.Master&&ji(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},Mv=s=>{if(s.getUint32(0)!==w.EBML)return!1;let e,t,i;const r=zd(s);return ji(r.value,({tag:a,type:n,value:o})=>(a===w.EBMLReadVersion?e=_t(o,n):a===w.DocType?t=_t(o,n):a===w.DocTypeReadVersion&&(i=_t(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},jd=[w.Info,w.SeekHead,w.Tracks,w.TrackEntry,w.Video,w.Projection,w.ProjectionType,w.ProjectionPrivate,w.Chapters,w.Cluster,w.Cues,w.Attachments,w.Tags],Nv=[w.Timestamp,w.SilentTracks,w.SilentTrackNumber,w.Position,w.PrevSize,w.SimpleBlock,w.BlockGroup,w.EncryptedBlock],Fv=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,d,l=!1;const c=0;return ji(s,({tag:h,type:f,value:m,valueSize:S})=>{if(h===w.SeekID){const b=_t(m,f);d=lr(b)}else h!==w.SeekPosition&&(d=void 0);return h===w.Segment?(e=m.byteOffset,t=m.byteOffset+S):h===w.Info?a=!0:h===w.SeekHead?n=!0:h===w.TimestampScale?i=_t(m,f):h===w.Duration?r=_t(m,f):h===w.SeekPosition&&d===w.Cues?u=_t(m,f):h===w.Tracks?ji(m,({tag:b,type:g,value:y})=>b===w.ProjectionType?(l=_t(y,g)===1,!1):!0):a&&n&&jd.includes(h)&&(o=!0),!o}),P(e,"Failed to parse webm Segment start"),P(t,"Failed to parse webm Segment end"),P(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:l,stereoMode:c,projectionType:ur.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Uv=s=>{if(j(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Vv=(s,e)=>{let t=!1,i=!1;const r=o=>D(o.time)&&D(o.position),a=[];let n;return ji(s,({tag:o,type:u,value:d})=>{switch(o){case w.Cues:t=!0;break;case w.CuePoint:n&&r(n)&&a.push(n),n={};break;case w.CueTime:n&&(n.time=_t(d,u));break;case w.CueTrackPositions:break;case w.CueClusterPosition:n&&(n.position=_t(d,u));break;default:t&&jd.includes(o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{const{time:d,position:l}=o,c=a[u+1];return{status:Z.NONE,time:{from:d,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},Hv=s=>{let e=0,t=!1;try{ji(s,i=>i.tag===w.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Nv.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[w.SimpleBlock,w.BlockGroup,w.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},Gv={validateData:Mv,parseInit:Fv,getIndexRange:Uv,parseSegments:Vv,parseFeedableSegmentChunk:Hv},To=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},Mi=(s,e)=>{let t=s;t=or(t,"$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,a]of Object.entries(i)){const n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=or(t,n,(o,u)=>j(a)?o:j(u)?a:a.padStart(parseInt(u,10),"0"))}return t},Yv=(s,e)=>{var t,i,r,a,n,o,u,d,l,c,h,f,m,S,b,g,y,v,E,$,L,G,Q,V,z,W,B,O,K,M,x,Y,te,fe,be,Pe,Ye,st,ie;const qe=new DOMParser().parseFromString(s,"application/xml"),De={video:[],audio:[],text:[]},ke=qe.children[0],Ct=ke.getElementsByTagName("Period")[0],Bt=Ct.children,Xt=ke.getAttribute("type")==="dynamic",Ot=ke.getAttribute("availabilityStartTime"),Pi=Ot?new Date(Ot).getTime():void 0;let Me;const Xi=ke.getAttribute("mediaPresentationDuration"),Zi=Ct.getAttribute("duration"),ni=ke.getElementsByTagName("vk:Attrs")[0],es=ni==null?void 0:ni.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(Xi)Me=To(Xi);else if(Zi){const ye=To(Zi);D(ye)&&(Me=ye)}else es&&(Me=parseInt(es,10));let wr=0;const oi=(i=(t=ke.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],_r=oi.includes(dr.WEBM_AS_IN_FFMPEG)||oi.includes(dr.WEBM_AS_IN_SPEC)?zi.WEBM:zi.MP4;for(const ye of Bt){const Mt=ye.getAttribute("mimeType"),Pr=ye.getAttribute("codecs"),ts=(r=ye.getAttribute("contentType"))!==null&&r!==void 0?r:Mt==null?void 0:Mt.split("/")[0],Dr=(n=(a=ye.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],is=ye.querySelectorAll("Representation"),Rr=ye.querySelector("SegmentTemplate");if(ts===Be.TEXT){for(const J of is){const Re=J.getAttribute("id")||"",Nt=ye.getAttribute("lang"),Qe=(d=(u=(o=J.querySelector("BaseURL"))===null||o===void 0?void 0:o.textContent)===null||u===void 0?void 0:u.trim())!==null&&d!==void 0?d:"",di=new URL(Qe,e).toString(),ui=Re.includes("_auto");De[Be.TEXT].push({id:Re,lang:Nt,isAuto:ui,kind:Be.TEXT,url:di})}continue}for(const J of is){const Re=(l=J.getAttribute("mimeType"))!==null&&l!==void 0?l:Mt,Nt=(h=(c=J.getAttribute("codecs"))!==null&&c!==void 0?c:Pr)!==null&&h!==void 0?h:"",Qe=(m=(f=J.getAttribute("contentType"))!==null&&f!==void 0?f:Re==null?void 0:Re.split("/")[0])!==null&&m!==void 0?m:ts,di=(b=(S=ye.getAttribute("profiles"))===null||S===void 0?void 0:S.split(","))!==null&&b!==void 0?b:[],ui=parseInt((g=J.getAttribute("width"))!==null&&g!==void 0?g:"",10),ss=parseInt((y=J.getAttribute("height"))!==null&&y!==void 0?y:"",10),rs=parseInt((v=J.getAttribute("bandwidth"))!==null&&v!==void 0?v:"",10)/1e3,as=(E=J.getAttribute("frameRate"))!==null&&E!==void 0?E:"",Ir=($=J.getAttribute("quality"))!==null&&$!==void 0?$:void 0,Lr=as?Er(as):void 0,xr=(L=J.getAttribute("id"))!==null&&L!==void 0?L:(wr++).toString(10),Cr=Qe==="video"?`${ss}p`:Qe==="audio"?`${rs}Kbps`:Nt,Br=`${xr}@${Cr}`,Or=(V=(Q=(G=J.querySelector("BaseURL"))===null||G===void 0?void 0:G.textContent)===null||Q===void 0?void 0:Q.trim())!==null&&V!==void 0?V:"",ns=new URL(Or,e).toString(),Mr=[...oi,...Dr,...di];let li;const Nr=J.querySelector("SegmentBase"),Ne=(z=J.querySelector("SegmentTemplate"))!==null&&z!==void 0?z:Rr;if(Nr){const Ke=(B=(W=J.querySelector("SegmentBase Initialization"))===null||W===void 0?void 0:W.getAttribute("range"))!==null&&B!==void 0?B:"",[Je,hi]=Ke.split("-").map(Xe=>parseInt(Xe,10)),ze={from:Je,to:hi},ht=(O=J.querySelector("SegmentBase"))===null||O===void 0?void 0:O.getAttribute("indexRange"),[fi,Ft]=ht?ht.split("-").map(Xe=>parseInt(Xe,10)):[],ft=ht?{from:fi,to:Ft}:void 0;li={type:dt.BYTE_RANGE,url:ns,initRange:ze,indexRange:ft}}else if(Ne){const Ke={representationId:(K=J.getAttribute("id"))!==null&&K!==void 0?K:void 0,bandwidth:(M=J.getAttribute("bandwidth"))!==null&&M!==void 0?M:void 0},Je=parseInt((x=Ne.getAttribute("timescale"))!==null&&x!==void 0?x:"",10),hi=(Y=Ne.getAttribute("initialization"))!==null&&Y!==void 0?Y:"",ze=Ne.getAttribute("media"),ht=(fe=parseInt((te=Ne.getAttribute("startNumber"))!==null&&te!==void 0?te:"",10))!==null&&fe!==void 0?fe:1,fi=Mi(hi,Ke);if(!ze)throw new ReferenceError("No media attribute in SegmentTemplate");const Ft=(be=Ne.querySelectorAll("SegmentTimeline S"))!==null&&be!==void 0?be:[],ft=[];let Xe=0,pi="",Ze=0;if(Ft.length){let et=ht,we=0;for(const pt of Ft){const je=parseInt((Pe=pt.getAttribute("d"))!==null&&Pe!==void 0?Pe:"",10),Tt=parseInt((Ye=pt.getAttribute("r"))!==null&&Ye!==void 0?Ye:"",10)||0,Ut=parseInt((st=pt.getAttribute("t"))!==null&&st!==void 0?st:"",10);we=Number.isFinite(Ut)?Ut:we;const os=je/Je*1e3,Di=we/Je*1e3;for(let Ri=0;Ri<Tt+1;Ri++){const eu=Mi(ze,{...Ke,segmentNumber:et.toString(10),segmentTime:(we+Ri*je).toString(10)}),fn=(Di!=null?Di:0)+Ri*os,tu=fn+os;et++,ft.push({time:{from:fn,to:tu},url:eu})}we+=(Tt+1)*je,Xe+=(Tt+1)*os}Ze=we/Je*1e3,pi=Mi(ze,{...Ke,segmentNumber:et.toString(10),segmentTime:we.toString(10)})}else if(D(Me)){const we=parseInt((ie=Ne.getAttribute("duration"))!==null&&ie!==void 0?ie:"",10)/Je*1e3,pt=Math.ceil(Me/we);let je=0;for(let Tt=1;Tt<pt;Tt++){const Ut=Mi(ze,{...Ke,segmentNumber:Tt.toString(10),segmentTime:je.toString(10)});ft.push({time:{from:je,to:je+we},url:Ut}),je+=we}Ze=je,pi=Mi(ze,{...Ke,segmentNumber:pt.toString(10),segmentTime:je.toString(10)})}const mi={time:{from:Ze,to:1/0},url:pi};li={type:dt.TEMPLATE,baseUrl:ns,segmentTemplateUrl:ze,initUrl:fi,totalSegmentsDurationMs:Xe,segments:ft,nextSegmentBeyondManifest:mi,timescale:Je}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Qe||!Re)continue;const ci={video:Be.VIDEO,audio:Be.AUDIO,text:Be.TEXT}[Qe];ci&&De[ci].push({id:Br,kind:ci,segmentReference:li,profiles:Mr,duration:Me,bitrate:rs,mime:Re,codecs:Nt,width:ui,height:ss,fps:Lr,quality:Ir})}}return{dynamic:Xt,liveAvailabilityStartTime:Pi,duration:Me,container:_r,representations:De}},qv=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a})=>{var n;const o=(n=a?Ki(a):void 0)!==null&&n!==void 0?n:si({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r}},zv=({id:s,bitrate:e})=>({id:s,bitrate:e}),jv=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=Ie(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:Ie(s,-1)},Wv=({id:s,lang:e,url:t,isAuto:i})=>({id:s,url:t,isAuto:i,type:"internal",language:e}),Eo=s=>"size"in s,Bi=s=>s.type===dt.TEMPLATE,Ha=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);class $o{constructor(e,t,i,r,{fetcher:a,tuning:n,getCurrentPosition:o,isActiveLowLatency:u,compatibilityMode:d=!1,manifest:l}){switch(this.onLastSegment$=new T(!1),this.fullyBuffered$=new T(!1),this.playingRepresentation$=new T(void 0),this.playingRepresentationInit$=new T(void 0),this.error$=new C,this.gaps=[],this.subscription=new ue,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new ut,this.destroyAbortController=new ut,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.liveInitialAdditionalOffset=0,this.isSeekingLive=!1,this.index=0,this.startWith=ce(this.destroyAbortController.signal,async function*(c){const h=this.representations.get(c);P(h,`Cannot find representation ${c}`),this.playingRepresentationId=c,this.downloadingRepresentationId=c,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${h.mime}; codecs="${h.codecs}"`),this.sourceBufferTaskQueue=new dv(this.sourceBuffer),this.subscription.add(U(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},b=>this.error$.next({id:"SegmentEjection",category:R.WTF,message:"Error when trying to clear segments ejected by browser",thrown:b}))),this.subscription.add(U(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:R.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(b=>{if(!this.sourceBuffer)return;const g=Math.min(this.bufferLimit,ar(this.sourceBuffer.buffered)*.8);this.bufferLimit=g,this.pruneBuffer(this.getCurrentPosition(),b)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(b=>this.error$.next(b))),yield this.loadInit(h,"high",!0);const f=this.initData.get(h.id),m=this.segments.get(h.id),S=this.parsedInitData.get(h.id);P(f,"No init buffer for starting representation"),P(m,"No segments for starting representation"),f instanceof ArrayBuffer&&(this.searchGaps(m,h),yield this.sourceBufferTaskQueue.append(f,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(S))}.bind(this)),this.switchTo=ce(this.destroyAbortController.signal,async function*(c){if(c===this.downloadingRepresentationId||c===this.switchingToRepresentationId)return;this.switchingToRepresentationId=c;const h=this.representations.get(c);P(h,`No such representation ${c}`);let f=this.segments.get(c),m=this.initData.get(c);if(j(m)||j(f)?yield this.loadInit(h,"high",!1):m instanceof Promise&&(yield m),f=this.segments.get(c),P(f,"No segments for starting representation"),m=this.initData.get(c),!m||!(m instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=c,this.abort(),yield this.sourceBufferTaskQueue.append(m,this.downloadAbortController.signal);const S=this.getCurrentPosition();D(S)&&(this.isLive||(f.forEach(b=>b.status=Z.NONE),this.pruneBuffer(S,1/0,!0)),this.maintain(S))}.bind(this)),this.seekLive=ce(this.destroyAbortController.signal,async function*(c){var h;if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!c)return;for(const y of this.representations.keys()){const v=c.find(L=>L.id===y);v&&this.representations.set(y,v);const E=this.representations.get(y);if(!E||!Bi(E.segmentReference))return;const $=this.getActualLiveStartingSegments(E.segmentReference);this.segments.set(E.id,$)}const f=(h=this.switchingToRepresentationId)!==null&&h!==void 0?h:this.downloadingRepresentationId,m=this.representations.get(f);P(m);const S=this.segments.get(f);P(S,"No segments for starting representation");const b=this.initData.get(f);if(P(b,"No init buffer for starting representation"),!(b instanceof ArrayBuffer))return;const g=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),g&&(yield this.sourceBufferTaskQueue.remove(g.from*1e3,g.to*1e3,this.destroyAbortController.signal)),this.searchGaps(S,m),yield this.sourceBufferTaskQueue.append(b,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this)),this.fetcher=a,this.tuning=n,this.compatibilityMode=d,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=u,this.isLive=!!(l!=null&&l.dynamic),this.container=i,i){case zi.MP4:this.containerParser=Ov;break;case zi.WEBM:this.containerParser=Gv;break;default:q(i)}this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ut,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(j(e)||j(this.downloadingRepresentationId)||j(this.playingRepresentationId)||j(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(P(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const r=i.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const l=We(this.sourceBuffer.buffered,e),c=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&l>=r.time.to-e+100&&(a=c)}if(isFinite(this.bufferLimit)&&ar(this.sourceBuffer.buffered)>=this.bufferLimit){const d=We(this.sourceBuffer.buffered,e),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<l);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{const l=Ie(o,0);l&&l.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===Z.FED&&!o.length&&We(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const u=Ie(i,-1);u&&u.status===Z.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===u))}searchGaps(e,t){this.gaps=[];let i=0;const r=this.isLive?this.liveInitialAdditionalOffset:0;for(const a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r}),i=a.time.to;D(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[];let a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(r=>r.id===this.downloadingRepresentationId);if(!t)return;const i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var t,i,r,a;for(const n of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!n||!Bi(n.segmentReference))return;const o=n.segmentReference.segments.map(c=>({...c,status:Z.NONE,size:void 0})),u=(i=this.segments.get(n.id))!==null&&i!==void 0?i:[],d=(a=(r=Ie(u,-1))===null||r===void 0?void 0:r.time.to)!==null&&a!==void 0?a:0,l=o==null?void 0:o.findIndex(c=>Math.floor(d)>=Math.floor(c.time.from)&&Math.floor(d)<=Math.floor(c.time.to));if(l===-1){this.liveUpdateSegmentIndex=0;const c=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,c)}else{const c=o.slice(l+1);this.segments.set(n.id,[...u,...c])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(const i of this.representations.values()){const r=i.segmentReference;if(!Bi(r))return;const a=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),n=Mi(r.segmentTemplateUrl,{segmentTime:a}),o=(t=this.segments.get(i.id))!==null&&t!==void 0?t:[],u=o.find(l=>Math.floor(l.time.from)===Math.floor(e.segment.time.from));u&&(u.time.to=e.segment.time.to),!!o.find(l=>Math.floor(l.time.from)===Math.floor(e.segment.time.to))||o.push({status:Z.NONE,time:{from:e.segment.time.to,to:1/0},url:n})}}findSegmentStartTime(e){var t,i,r;const a=(i=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&i!==void 0?i:this.playingRepresentationId;if(!a)return;const n=this.segments.get(a);if(!n)return;const o=n.find(u=>u.time.from<=e&&u.time.to>=e);return(r=o==null?void 0:o.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){const i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const r=e.findIndex(({status:c,time:{from:h,to:f}},m)=>{const S=h<=i&&f>=i,b=h>i||S||m===0&&i===0,g=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&h<=i+g||f<=i+g;return(c===Z.NONE||c===Z.PARTIALLY_EJECTED&&b&&y&&this.sourceBuffer&&!Yi(this.sourceBuffer.buffered,i))&&b&&y});if(r===-1)return[];if(t!==dt.BYTE_RANGE)return e.slice(r,r+1);const a=e;let n=0,o=0;const u=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=d||o<=l);c++){const h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status===Z.NONE||h.status===Z.PARTIALLY_EJECTED)u.push(h);else break}return u}async loadSegments(e,t,i="auto"){t.segmentReference.type===dt.TEMPLATE?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status=Z.DOWNLOADING;const r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);const{range:a,url:n,signal:o,onProgress:u,onProgressTasks:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await ce(o,async function*(){const l=ms(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,l))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{const l=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(!l)return;const c=new DataView(l);if(this.isActiveLowLatency()){const h=t.segmentReference.timescale;r.segment.time.to=this.containerParser.getSegmentEndTime(c,h)}u&&r.feedingBytes&&d?await Promise.all(d):await this.sourceBufferTaskQueue.append(c,o),r.segment.status=Z.DOWNLOADED,this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(l){if(!Ha(l))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(l)}}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(const u of e)u.status=Z.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await ce(n,async function*(){const u=ms(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,u))}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.failedDownloads=0}catch(u){if(!Ha(u))return;this.abortActiveSegments(e),this.onSegmentDownloadError(u)}}prepareByteRangeFetchSegmentParams(e,t){if(Bi(t.segmentReference))throw new Error("Representation is not byte range type");const i=t.segmentReference.url,r={from:Ie(e,0).byte.from,to:Ie(e,-1).byte.to},{signal:a}=this.downloadAbortController,n=()=>{this.abort()};return{url:i,range:r,signal:a,onProgress:(u,d)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:u,loaded:d,signal:a,onSegmentAppendFailed:n,globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:R.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Bi(t.segmentReference))throw new Error("Representation is not template type");const i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");const r=i.toString(),{signal:a}=this.downloadAbortController,n=()=>{this.abort()},o=[],d=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!a.aborted)try{const h=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:a,onSegmentAppendFailed:n,representationId:t.id});o.push(h)}catch(h){this.error$.next({id:"SegmentFeeding",category:R.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}}:void 0;return{url:r,signal:a,onProgress:d,onProgressTasks:o}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSegmentDownloadError(e){var t;let i=!1;const r=this.getCurrentPosition();this.sourceBuffer&&D(r)&&(i=We((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,i||this.error$.next({id:"SegmentDownload",category:R.NETWORK,message:"Error when fetching segments",thrown:e})}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const o of this.activeSegments){const{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){const d=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),l=this.containerParser.parseFeedableSegmentChunk(d);l!=null&&l.byteLength&&(u.status=Z.PARTIALLY_FED,o.feedingBytes+=l.byteLength,await this.sourceBufferTaskQueue.append(l),o.fedBytes+=l.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;const o=this.representations.get(t);if(!o)return;const u=o.segmentReference.type,d=e.byteLength;for(const l of this.activeSegments){const{segment:c}=l,h=u===dt.BYTE_RANGE,f=h?c.byte.to-c.byte.from+1:d;if(l.representationId!==t||!(!h||c.byte.from>=i&&c.byte.to<i+e.byteLength))continue;if(a.aborted){n();continue}const S=h?c.byte.from-i:0,b=h?c.byte.to-i:e.byteLength,g=S<r,y=b<=r;if(c.status===Z.DOWNLOADING&&g&&y){c.status=Z.DOWNLOADED;const v=new DataView(e.buffer,e.byteOffset+S,f);this.sourceBufferTaskQueue.append(v,a).then(E=>E&&!a.aborted?this.onSegmentFullyAppended(l,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&g&&(l.loadedBytes=Math.min(f,r-S),l.loadedBytes>l.feedingBytes)){const v=new DataView(e.buffer,e.byteOffset+S+l.feedingBytes,l.loadedBytes-l.feedingBytes),E=l.loadedBytes===f?v:this.containerParser.parseFeedableSegmentChunk(v);E!=null&&E.byteLength&&(c.status=Z.PARTIALLY_FED,l.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,a).then($=>{if(a.aborted)n();else if($)l.fedBytes+=E.byteLength,l.fedBytes===f&&this.onSegmentFullyAppended(l,t);else{if(l.feedingBytes<f)return;n()}}))}}}onSegmentFullyAppended(e,t){var i;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=Z.FED,Eo(e.segment)&&(e.segment.size=e.fedBytes);for(const r of this.representations.values())if(r.id!==t)for(const a of(i=this.segments.get(r.id))!==null&&i!==void 0?i:[])a.status===Z.FED&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status=Z.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===Z.PARTIALLY_FED||e.status===Z.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=Z.NONE),e.status=Z.PARTIALLY_EJECTED):e.status=Z.NONE;for(const i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,a]of this.initData.entries()){const n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=rr(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?ce(this.destroyAbortController.signal,async function*(){const o=ms(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(async o=>{if(!o)return;const{init:u,dataView:d,segments:l}=o,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c);let h=l;this.isLive&&Bi(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:R.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||j(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,n=-1/0,o=!1;const u=d=>{var l;a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const c=Eo(d)?(l=d.size)!==null&&l!==void 0?l:0:d.byte.to-d.byte.from;r+=c};for(const d of this.segments.values())for(const l of d){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;l.status===Z.FED&&u(l)}if(o=isFinite(a)&&isFinite(n),!o){r=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const l of d){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;l.status===Z.FED&&u(l)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const l=this.sourceBuffer.buffered.start(d)*1e3,c=this.sourceBuffer.buffered.end(d)*1e3;for(const h of this.segments.values())for(const f of h)if(f.status===Z.NONE&&Math.round(f.time.from)<=Math.round(l)&&Math.round(f.time.to)>=Math.round(c)){a=l,n=c;break}}if(o=isFinite(a)&&isFinite(n),!o&&i){r=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const l of this.segments.values())for(const c of l)c.time.from>e+d&&c.status===Z.FED&&u(c)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=rr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:R.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(j(this.sourceBuffer)||j(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}const t=1;for(const i of this.segments.values())for(const r of i){const{status:a}=r;if(a!==Z.FED&&a!==Z.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(l=>l.from-t<=n&&l.to+t>=o),d=e.filter(l=>n>=l.from-t&&n<=l.to+t||o>=l.from-t&&o<=l.to+t);u||(d.length===1?r.status=Z.PARTIALLY_EJECTED:r.status=Z.NONE)}}}var Ui;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(Ui||(Ui={}));class Qv{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new T(void 0),this.lastConnectionReused$=new T(void 0),this.lastRequestFirstBytes$=new T(void 0),this.abortAllController=new ut,this.subscription=new ue,this.fetchManifest=ce(this.abortAllController.signal,async function*(r){let a=r;this.requestQuic&&(a=ii(a));const n=yield $i(a,{signal:this.abortAllController.signal}).catch(ls);return n?(this.onHeadersReceived(n.headers),n.text()):null}.bind(this)),this.fetch=ce(this.abortAllController.signal,async function*(r,{rangeMethod:a=this.compatibilityMode?Ui.HEADER:Ui.PARAM,range:n,onProgress:o,priority:u="auto",signal:d,measureThroughput:l=!0,isLowLatency:c=!1}={}){var h,f;let m=r;const S=new Headers;if(n)switch(a){case Ui.HEADER:{S.append("Range",`bytes=${n.from}-${n.to}`);break}case Ui.PARAM:{const O=new URL(m,location.href);O.searchParams.append("bytes",`${n.from}-${n.to}`),m=O.toString();break}default:q(a)}this.requestQuic&&(m=ii(m));let b=this.abortAllController.signal,g;if(d){const O=new ut;if(g=H(U(this.abortAllController.signal,"abort"),U(d,"abort")).subscribe(()=>{try{O.abort()}catch(K){ls(K)}}),this.abortAllController.signal.aborted||d.aborted)try{O.abort()}catch(K){ls(K)}b=O.signal}const y=le(),v=yield $i(m,{priority:u,headers:S,signal:b}).catch(ls),E=le();if(!v)return g==null||g.unsubscribe(),null;if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(E-y),!v.ok||!v.body)return g==null||g.unsubscribe(),Promise.reject(new Error(`Fetch error ${v.status}: ${v.statusText}`));if(this.onHeadersReceived(v.headers),!o&&!l)return g==null||g.unsubscribe(),v.arrayBuffer();const[$,L]=v.body.tee(),G=$.getReader();l&&((f=this.throughputEstimator)===null||f===void 0||f.trackStream(L,c));let Q=0,V=new Uint8Array(0),z=!1;const W=O=>{g==null||g.unsubscribe(),z=!0,ls(O)},B=ce(b,async function*({done:O,value:K}){if(Q===0&&this.lastRequestFirstBytes$.next(le()-y),b.aborted){g==null||g.unsubscribe();return}if(!O&&K){const M=new Uint8Array(V.length+K.length);M.set(V),M.set(K,V.length),V=M,Q+=K.byteLength,o==null||o(new DataView(V.buffer),Q),yield G==null?void 0:G.read().then(B,W)}}.bind(this));return yield G==null?void 0:G.read().then(B,W),g==null||g.unsubscribe(),z?null:V.buffer}.bind(this)),this.fetchByteRangeRepresentation=ce(this.abortAllController.signal,async function*(r,a,n){var o;if(r.type!==dt.BYTE_RANGE)return null;const{from:u,to:d}=r.initRange;let l=u,c=d,h=!1,f,m;r.indexRange&&(f=r.indexRange.from,m=r.indexRange.to,h=d+1===f,h&&(l=Math.min(f,u),c=Math.max(m,d))),l=Math.min(l,0);const S=yield this.fetch(r.url,{range:{from:l,to:c},priority:n,measureThroughput:!1});if(!S)return null;const b=new DataView(S,u-l,d-l+1);if(!a.validateData(b))throw new Error("Invalid media file");const g=a.parseInit(b),y=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(g);if(!y)throw new ReferenceError("No way to load representation index");let v;if(h)v=new DataView(S,y.from-l,y.to-y.from+1);else{const $=yield this.fetch(r.url,{range:y,priority:n,measureThroughput:!1});if(!$)return null;v=new DataView($)}const E=a.parseSegments(v,g,y);return{init:g,dataView:new DataView(S),segments:E}}.bind(this)),this.fetchTemplateRepresentation=ce(this.abortAllController.signal,async function*(r,a){if(r.type!==dt.TEMPLATE)return null;const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield this.fetch(n,{priority:a,measureThroughput:!1});return o?{init:null,segments:r.segments.map(d=>({...d,status:Z.NONE,size:void 0})),dataView:new DataView(o)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=un(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 dt.BYTE_RANGE:return(r=await this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case dt.TEMPLATE:return(a=await this.fetchTemplateRepresentation(e,i))!==null&&a!==void 0?a:null;default:q(n)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const ls=s=>{if(!Ha(s))throw s},Ga=1e3,cr=(s,e,t)=>t*e+(1-t)*s,Wd=(s,e)=>s.reduce((t,i)=>t+i,0)/e,Kv=(s,e,t,i)=>{let r=0,a=t;const n=Wd(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};class hn{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new T(e.initial),this.debounced$=new T(e.initial);const i=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new kt(`raw_${i}`),this.smoothedSeries$=new kt(`smoothed_${i}`),this.reportedSeries$=new kt(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(j(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class Jv extends hn{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=cr(this.slow,e,this.params.emaAlphaSlow),this.fast=cr(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Xv extends hn{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Wd(this.pastMeasures,this.takenMeasures);this.emaSmoothed=cr(this.emaSmoothed,e,this.params.emaAlpha);const i=Kv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class Zv extends hn{constructor(e){super(e),this.furtherValues=[],this.currentTopExtremumValue=0,this.extremumInterval=e.extremumInterval}next(e){this.currentTopExtremumValue<=e?(this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.push(e)}updateSmoothedValue(e){this.smoothed=this.smoothed?cr(this.smoothed,e,this.params.emaAlpha):e}}class Ya{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Jv({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Xv({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new Zv({initial:e,label:"liveEdgeDelay",...t})}}const eS=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)},Ao=["timeupdate","progress","play","seeked","stalled","waiting"];var nt;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(nt||(nt={}));let tS=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new ue,this.representationSubscription=new ue,this.state$=new he(nt.NONE),this.currentVideoRepresentation$=new T(void 0),this.currentVideoRepresentationInit$=new T(void 0),this.error$=new C,this.lastConnectionType$=new T(void 0),this.lastConnectionReused$=new T(void 0),this.lastRequestFirstBytes$=new T(void 0),this.isLive$=new T(!1),this.liveDuration$=new T(0),this.liveAvailabilityStartTime$=new T(void 0),this.bufferLength$=new T(0),this.liveLoadBufferLength$=new T(0),this.livePositionFromPlayer$=new T(0),this.isActiveLowLatency=!1,this.isUpdatingLive=!1,this.isJumpGapAfterSeekLive=!1,this.liveLastSeekOffset=0,this.forceEnded$=new C,this.gapWatchdogStarted=!1,this.destroyController=new ut,this.initManifest=ce(this.destroyController.signal,async function*(t,i,r){var a;this.element=t,this.manifestUrlString=Ve(i,r,Se.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(nt.MANIFEST_READY),this.manifest=yield this.updateManifest(),!((a=this.manifest)===null||a===void 0)&&a.representations.video.length?this.state$.setState(nt.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:R.PARSER,message:"No playable video representations"})}.bind(this)),this.updateManifest=ce(this.destroyController.signal,async function*(){var t;const i=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:R.NETWORK,message:"Failed to load manifest",thrown:n})});if(!i)return this.manifest;let r;try{r=Yv(i!=null?i:"",this.manifestUrlString)}catch(n){this.error$.next({id:"ManifestParsing",category:R.PARSER,message:"Failed to parse MPD manifest",thrown:n})}if(!r)return null;const a=({kind:n,mime:o,codecs:u})=>{var d,l,c,h;return!!(!((l=(d=this.element)===null||d===void 0?void 0:d.canPlayType)===null||l===void 0)&&l.call(d,o)&&(!((h=(c=window.MediaSource)===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0)&&h.call(c,`${o}; codecs="${u}"`))||n===Be.TEXT)};return r.dynamic&&this.isLive$.getValue()!==r.dynamic&&(this.isLive$.next(r.dynamic),this.liveDuration$.getValue()!==r.duration&&this.liveDuration$.next(-1*((t=r.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==r.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(r.liveAvailabilityStartTime)),{...r,representations:Ei(Object.entries(r.representations).map(([n,o])=>[n,o.filter(a)]))}}.bind(this)),this.initRepresentations=ce(this.destroyController.signal,async function*(t,i){P(this.manifest),P(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(nt.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source),this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency,manifest:this.manifest};if(this.videoBufferManager=new $o(Be.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],D(i)&&(this.audioBufferManager=new $o(Be.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,r),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Ti(Ga).subscribe(o=>{var u;if(!((u=this.element)===null||u===void 0)&&u.paused){const d=er(this.manifestUrlString,Se.DASH_CMAF_OFFSET_P);this.manifestUrlString=Ve(this.manifestUrlString,d+Ga,Se.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(H(...Ao.map(o=>U(this.element,o))).pipe(_(o=>this.element?We(this.element.buffered,this.element.currentTime*1e3):0),ve(),ae(o=>!!o)).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(ae(u=>this.isActiveLowLatency&&!!u)).subscribe(u=>this.liveEstimatedDelay.next(u))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(u=>{if(!this.isActiveLowLatency)return;const d=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,l=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,c=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,h=u-d;let f=1+Math.sign(h)*c;Math.abs(h)<l?f=1:Math.abs(h)>l*2&&(f=1+Math.sign(h)*c*2),eS(this.element,f)})),this.representationSubscription.add(this.bufferLength$.subscribe(u=>{var d,l;let c=0;if(u){const h=((l=(d=this.element)===null||d===void 0?void 0:d.currentTime)!==null&&l!==void 0?l:0)*1e3;c=Math.min(...this.bufferManagers.map(m=>{var S,b;return(b=(S=m.getLiveSegmentsToLoadState(this.manifest))===null||S===void 0?void 0:S.to)!==null&&b!==void 0?b:0}))-h}c&&this.liveLoadBufferLength$.getValue()!==c&&this.liveLoadBufferLength$.next(c)}));let o=0;this.representationSubscription.add(Le({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).subscribe(async({liveLoadBufferLength:u,bufferLength:d})=>{if(P(this.element),this.liveWaitingEventCallback.cancel(),this.isUpdatingLive)return;const l=this.element.playbackRate,c=er(this.manifestUrlString,Se.DASH_CMAF_OFFSET_P),h=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,f=Math.min(h,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*l),m=this.tuning.dashCmafLive.normalizedActualBufferOffset*l,S=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*l,b=this.isActiveLowLatency?d:u;let g=At.None;if(this.isActiveLowLatency?g=At.ActiveLowLatency:b<f+S&&b>=f?g=At.LiveWithTargetOffset:c!==0&&b<f&&(g=At.LiveForwardBuffering),isFinite(u)&&(o=u>o?u:o),g===At.LiveForwardBuffering||g===At.LiveWithTargetOffset){const y=o-(f+m),v=Math.trunc(c+y/l);let E;u?v>0?E=v:E=0:E=c,this.manifestUrlString=Ve(this.manifestUrlString,E,Se.DASH_CMAF_OFFSET_P)}g!==At.None&&g!==At.ActiveLowLatency&&(o=0,this.updateLive())}))}const a=H(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(_(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=H(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(_(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.representationSubscription.add(H(this.forceEnded$,Le({allBuffersFull:a,someBufferEnded:n}).pipe(ae(({allBuffersFull:o,someBufferEnded:u})=>o&&u))).subscribe(()=>{var o;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(u=>!u.updating))try{(o=this.source)===null||o===void 0||o.endOfStream()}catch(u){this.error$.next({id:"EndOfStream",category:R.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:u})}})),this.representationSubscription.add(H(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield new Promise(o=>{var u;return(u=this.source)===null||u===void 0?void 0:u.addEventListener("sourceopen",o)})),D(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&D(i)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)]):yield this.videoBufferManager.startWith(t),this.state$.setState(nt.REPRESENTATIOS_READY)}.bind(this)),this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((i=this.audioBufferManager)===null||i===void 0)&&i.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=Ti(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:R.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Qv({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Ya.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.liveWaitingEventCallback=hu(this._liveWaitingEventCallback,this.tuning.dashCmafLive.maxWaitingDuration)}async seekLive(e){var t,i,r,a;P(this.element),this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&e===0,this.liveLastSeekOffset=e,this.isJumpGapAfterSeekLive=!0,this.manifestUrlString=Ve(this.manifestUrlString,e,Se.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(nt.RUNNING),this.subscription.add(H(...Ao.map(e=>U(this.element,e)),U(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:R.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(U(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(U(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Yi(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime),this.isLive$.getValue()&&this.liveWaitingEventCallback()})),this.tick()}async switchRepresentation(e,t){const i={[Be.VIDEO]:this.videoBufferManager,[Be.AUDIO]:this.audioBufferManager,[Be.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)}seek(e,t){var i,r,a,n,o;P(this.element),P(this.videoBufferManager);let u;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?u=e:u=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!==null&&i!==void 0?i:e,(a=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&a!==void 0?a:e),Yi(this.element.buffered,u)||(this.videoBufferManager.abort(),(n=this.audioBufferManager)===null||n===void 0||n.abort()),this.videoBufferManager.maintain(u),(o=this.audioBufferManager)===null||o===void 0||o.maintain(u),this.element.currentTime=u/1e3}stop(){var e,t;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(e=this.videoBufferManager)===null||e===void 0||e.destroy(),this.videoBufferManager=null,(t=this.audioBufferManager)===null||t===void 0||t.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(nt.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 _liveWaitingEventCallback(){try{await this.seekLive(this.liveLastSeekOffset)}catch(e){this.error$.next({id:"LiveWaitingEventCallback",category:R.WTF,message:"Error in seeking live in live waiting event callback",thrown:e})}}async updateLive(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),(e=this.bufferManagers)===null||e===void 0||e.forEach(t=>t.updateLive(this.manifest)),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);const t=this.element.currentTime*1e3,i=[];for(const r of this.bufferManagers)for(const a of r.gaps)r.playingRepresentation$.getValue()===a.representation&&a.from<=t&&a.to>t&&(this.element.duration*1e3-a.to<this.tuning.endGapTolerance?i.push(1/0):i.push(a.to));if(i.length){const r=Math.max(...i);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):Math.trunc(this.element.currentTime*1e3)!==Math.trunc(r)&&(this.element.currentTime=r/1e3)}}};class Qd{constructor(e){this.subscription=new ue,this.videoState=new he(Ee.STOPPED),this.elementSize$=new T(void 0),this.textTracksManager=new yt,this.droppedFramesManager=new ks,this.videoTracks$=new T([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Dd,this.textTracks=[],this.syncPlayback=()=>{var t,i,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(u.state===ee.Requested&&(o==null?void 0:o.to)!==p.PAUSED&&a!==Ee.STOPPED&&n!==p.STOPPED){const l=(i=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&i!==void 0?i:0;this.seek(u.position-l,u.forcePrecise)}if(n===p.STOPPED){a!==Ee.STOPPED&&(this.videoState.startTransitionTo(Ee.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Ee.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}switch(a){case Ee.STOPPED:this.videoState.startTransitionTo(Ee.READY),this.prepare();return;case Ee.READY:n===p.PAUSED?(this.videoState.setState(Ee.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING?(this.videoState.startTransitionTo(Ee.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.READY&&I(this.params.desiredState.playbackState,p.READY);return;case Ee.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(Ee.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case Ee.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(Ee.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return q(a)}}},this.init3DScene=t=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Hd(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=t.projectionData)===null||i===void 0?void 0:i.pose.yaw)||0,y:((r=t.projectionData)===null||r===void 0?void 0:r.pose.pitch)||0,z:((a=t.projectionData)===null||a===void 0?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const n=this.elementSize$.getValue();n&&this.scene3D.setViewportSize(n.width,n.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=Rt(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ge(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new tS({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=Lt(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:R.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(_(d=>d.map(({track:l})=>l)))}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(ae(D),Ae()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ri(this.video,t.isLooped,r)),this.subscription.add(Dt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Qt(this.video,t.playbackRate,i.playbackRateState$,r)),a(bs(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(Ee.PLAYING),I(t.playbackState,p.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(Ee.PAUSED),I(t.playbackState,p.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===Ee.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d===nt.MANIFEST_READY){const c=[];this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();P(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((g,y)=>y.bitrate-g.bitrate),m=Array.from(h.video).sort((g,y)=>y.bitrate-g.bitrate),S=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const g of f){const y=zv(g);y&&this.audioTracks.push({track:y,representation:g})}for(const g of m){const y=qv(g);if(y){c.push({track:y,representation:g});const v=!this.params.tuning.isAudioDisabled&&jv(f,m,g);v&&this.audioRepresentations.set(g.id,v)}}this.videoTracks$.next(c);for(const g of S){const y=Wv(g);y&&this.textTracks.push({track:y,representation:g})}this.params.output.availableVideoTracks$.next(c.map(({track:g})=>g)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:g})=>g)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:g})=>g));const b=this.selectVideoRepresentation();P(b),this.player.initRepresentations(b.id,(l=this.audioRepresentations.get(b.id))===null||l===void 0?void 0:l.id)}else d===nt.REPRESENTATIOS_READY&&(this.videoState.setState(Ee.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:R.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(H(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,U(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!==nt.RUNNING||l||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation(),h=this.params.desiredState.autoVideoTrackLimits.getTransition();if(h&&this.params.output.autoVideoTrackLimits$.next(h.to),c){this.player.switchRepresentation(Be.VIDEO,c.id).catch(n);const f=this.audioRepresentations.get(c.id);f&&this.player.switchRepresentation(Be.AUDIO,f.id).catch(n)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ve(),_(d=>{var l;return d&&((l=this.videoTracks$.getValue().find(({representation:{id:c}})=>c===d))===null||l===void 0?void 0:l.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var l,c;if(d!=null&&d.is3dVideo&&(!((l=this.params.tuning.spherical)===null||l===void 0)&&l.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe(_(({to:d})=>d===p.READY),ve());this.subscription.add(H(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===p.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(H(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===p.READY)));const u=H(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,He(["init"])).pipe(it(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,i,r,a,n,o;const u=this.params.desiredState.autoVideoTrackSwitching.getState(),d=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id,l=(t=this.videoTracks$.getValue().find(({track:{id:y}})=>y===d))===null||t===void 0?void 0:t.track,c=this.params.output.currentVideoTrack$.getValue(),h=We(this.video.buffered,this.video.currentTime*1e3),f=u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=Math.min(h/Math.min(f,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),S=Math.max(l&&!u&&(r=(i=this.audioRepresentations.get(l.id))===null||i===void 0?void 0:i.bitrate)!==null&&r!==void 0?r:0,c&&(n=(a=this.audioRepresentations.get(c.id))===null||a===void 0?void 0:a.bitrate)!==null&&n!==void 0?n:0),b=_i(this.videoTracks$.getValue().map(({track:y})=>y),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:m,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),g=u?b!=null?b:l:l!=null?l:b;return g&&((o=this.videoTracks$.getValue().find(({track:y})=>y===g))===null||o===void 0?void 0:o.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Kt(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(Ee.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),It(this.video)}}class iS extends Qd{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}let sS=class extends Gd{constructor(e){super(e),this.liveOffset=new As}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(Le({interval:Ti(Ua),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()===Te.PLAYING){const n=e.position$.getValue()+(r-1);e.position$.next(n),(a=this.liveOffset)===null||a===void 0||a.resetTo(-n*1e3)}})).add(Le({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(_(({liveBufferTime:r,liveAvailabilityStartTime:a})=>r&&a?r+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t===p.PAUSED&&i===Te.PAUSED,a=-e,n=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)===null||o===void 0||o.resetTo(n,r)})}};class rS extends Qd{constructor(e){super(e),this.liveOffset=new As}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Le({interval:Ti(Ga),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()===Ee.PLAYING&&!this.player.isActiveLowLatency){const n=e.position$.getValue()+(r-1);e.position$.next(n),(a=this.liveOffset)===null||a===void 0||a.resetTo(-n*1e3)}})).add(Le({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(_(({liveBufferTime:r,liveAvailabilityStartTime:a})=>r&&a?r+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t===p.PAUSED&&i===Ee.PAUSED,a=-e,n=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)===null||o===void 0||o.resetTo(n,r)})}}const $t={};var de;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(de||(de={}));const cs=(s,e)=>new fr(t=>{const i=(r,a)=>t.next(a);return s.on(e,i),()=>s.off(e,i)});class aS{constructor(e){this.subscription=new ue,this.videoState=new he(de.INITIALIZING),this.textTracksManager=new yt,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(t!==de.INITIALIZING)switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===ee.Requested&&this.seek(a.position),i){case p.STOPPED:switch(t){case de.STOPPED:break;case de.READY:case de.PLAYING:case de.PAUSED:this.stop();break;default:q(t)}break;case p.READY:switch(t){case de.STOPPED:this.prepare();break;case de.READY:case de.PLAYING:case de.PAUSED:break;default:q(t)}break;case p.PLAYING:switch(t){case de.PLAYING:break;case de.STOPPED:this.prepare();break;case de.READY:case de.PAUSED:this.playIfAllowed();break;default:q(t)}break;case p.PAUSED:switch(t){case de.PAUSED:break;case de.STOPPED:this.prepare();break;case de.READY:this.videoState.setState(de.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED);break;case de.PLAYING:this.pause();break;default:q(t)}break;default:q(i)}},this.video=Rt(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ge(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)===null||e===void 0||e.detachMedia(),(t=this.hls)===null||t===void 0||t.destroy(),this.params.output.element$.next(void 0),It(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:R.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(r=>{e||($t.Hls=r.default,$t.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){P($t.Hls,"hls.js not loaded"),this.hls=new $t.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(de.STOPPED)}subscribe(){P($t.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:R.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=Lt(this.video),a=(d,l)=>this.subscription.add(d.subscribe(l,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(ri(this.video,e.isLooped,i)),this.subscription.add(Dt(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Qt(this.video,e.playbackRate,r.playbackRateState$,i)),this.subscription.add(cs(this.hls,$t.Events.ERROR).subscribe(d=>{var l;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:R.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${(l=d.err)===null||l===void 0?void 0:l.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(de.PLAYING),I(e.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED),I(e.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())===null||d===void 0?void 0:d.to)===de.READY&&this.videoState.setState(de.READY),this.videoState.getState()===de.PLAYING&&this.playIfAllowed()},i)),a(cs(this.hls,$t.Events.MANIFEST_PARSED).pipe(_(({levels:d})=>d.reduce((l,c)=>{var h,f;const m=c.name||c.height.toString(10),{width:S,height:b}=c,g=(f=Ki((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:si({width:S,height:b});if(!g)return l;const y=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,v={id:m.toString(),quality:g,bitrate:c.bitrate/1e3,size:{width:S,height:b},fps:y};return this.trackLevels.set(m,{track:v,level:c}),l.push(v),l},[]))),t.availableVideoTracks$),a(cs(this.hls,$t.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){const l=[];for(const c of d.subtitleTracks){const h=c.name,f=c.attrs.URI||"",m=c.lang,S="internal";l.push({id:h,url:f,language:m,type:S})}e.internalTextTracks.startTransitionTo(l)}}),a(cs(this.hls,$t.Events.LEVEL_LOADING).pipe(_(({url:d})=>Ge(d))),t.hostname$),this.subscription.add(vt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:i}));const n=d=>{var l;return(l=Array.from(this.trackLevels.values()).find(({level:c})=>c===d))===null||l===void 0?void 0:l.track},o=cs(this.hls,$t.Events.LEVEL_SWITCHED).pipe(_(({level:d})=>n(this.hls.levels[d])));o.pipe(ae(D)).subscribe(t.currentVideoTrack$,i),this.subscription.add(vt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),d=>{var l;if(j(d))return;const c=(l=this.trackLevels.get(d.id))===null||l===void 0?void 0:l.level;if(!c)return;const h=this.hls.levels.indexOf(c),f=this.hls.currentLevel,m=this.hls.levels[f];!m||c.bitrate>m.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o,onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const u=H(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,He(["init"])).pipe(it(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(de.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(de.PLAYING),await Kt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:t}))||(this.videoState.setState(de.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))}pause(){this.videoState.startTransitionTo(de.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(de.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0)}}const ko="X-Playback-Duration";var wo=async s=>{var e;const t=await $i(s),i=await t.text(),r=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(i))===null||e===void 0?void 0:e[1];return r?parseInt(r,10):t.headers.has(ko)?parseInt(t.headers.get(ko),10):void 0};const nS=s=>{let e=null;if(s.QUALITY&&(e=Ki(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=si({width:t,height:i})}return e!=null?e:null},Kd=async(s,e=s)=>{var t,i;const n=(await(await $i(s)).text()).split(`
|
|
46
|
-
`),o=[],u=[];for(let d=0;d<n.length;d++){const l=n[d],c=l.match(/^#EXT-X-STREAM-INF:(.+)/),h=l.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!c&&!h)){if(c){const f=Ei(c[1].split(",").map(E=>E.split("="))),m=(t=f.QUALITY)!==null&&t!==void 0?t:`stream-${f.BANDWIDTH}`,S=nS(f);let b;f.BANDWIDTH&&(b=parseInt(f.BANDWIDTH,10)/1e3||void 0),!b&&f["AVERAGE-BANDWIDTH"]&&(b=parseInt(f["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const g=f["FRAME-RATE"]?parseFloat(f["FRAME-RATE"]):void 0;let y;if(f.RESOLUTION){const[E,$]=f.RESOLUTION.split("x").map(L=>parseInt(L,10));E&&$&&(y={width:E,height:$})}const v=new URL(n[++d],e).toString();S&&o.push({id:m,quality:S,url:v,bandwidth:b,size:y,fps:g})}if(h){const f=Ei(h[1].split(",").map(g=>g.split("=")).map(([g,y])=>[g,y.replace(/^"|"$/g,"")])),m=(i=f.URI)===null||i===void 0?void 0:i.replace(/playlist$/,"subtitles.vtt"),S=f.LANGUAGE,b=f.NAME;m&&S&&u.push({type:"internal",id:S,label:b,language:S,url:m,isAuto:!1})}}}return{qualityManifests:o,textTracks:u}};var pe;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(pe||(pe={}));class oS{constructor(e){var t;this.subscription=new ue,this.videoState=new he(pe.STOPPED),this.textTracksManager=new yt,this.manifests$=new T([]),this.liveOffset=new As,this.manifestStartTime$=new T(void 0),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const r=this.videoState.getState(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition(),d=this.params.desiredState.autoVideoTrackLimits.getTransition();if(a===p.STOPPED){r!==pe.STOPPED&&(this.videoState.startTransitionTo(pe.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(pe.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(r===pe.STOPPED){this.videoState.startTransitionTo(pe.READY),this.prepare();return}if(o||u||d){const h=this.videoState.getState();this.videoState.setState(pe.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),d&&this.params.output.autoVideoTrackLimits$.next(d.to),c.state===ee.None&&this.params.desiredState.seekState.setState({state:ee.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==p.PAUSED&&c.state===ee.Requested){this.videoState.startTransitionTo(pe.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case pe.READY:a===p.READY?I(this.params.desiredState.playbackState,p.READY):a===p.PAUSED?(this.videoState.setState(pe.PAUSED),this.liveOffset.pause(),I(this.params.desiredState.playbackState,p.PAUSED)):a===p.PLAYING&&(this.videoState.startTransitionTo(pe.PLAYING),this.playIfAllowed());return;case pe.PLAYING:a===p.PAUSED?(this.videoState.startTransitionTo(pe.PAUSED),this.liveOffset.pause(),this.video.pause()):(n==null?void 0:n.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case pe.PAUSED:if(a===p.PLAYING)if(this.videoState.startTransitionTo(pe.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let h=this.liveOffset.getTotalOffset();h>=this.maxSeekBackTime$.getValue()&&(h=0,this.liveOffset.resetTo(h)),this.liveOffset.resume(),this.params.output.position$.next(-h/1e3),this.prepare()}else(n==null?void 0:n.to)===p.PAUSED&&(I(this.params.desiredState.playbackState,p.PAUSED),this.liveOffset.pause());return;case pe.CHANGING_MANIFEST:break;default:return q(r)}},this.params=e,this.video=Rt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:rt.INVARIANT,url:this.params.source.url},Kd(Ve(this.params.source.url),this.params.source.url).then(({qualityManifests:i})=>{this.manifests$.next([this.masterManifest,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:R.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ge(this.params.source.url)),this.maxSeekBackTime$=new T((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t,i,r;const{autoVideoTrackSwitching:a,videoTrack:n}=this.params.desiredState,o=a.getState(),u=n.getTransition(),d=(r=(t=(e=u==null?void 0:u.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(i=n.getState())===null||i===void 0?void 0:i.id)!==null&&r!==void 0?r:"master",l=this.manifests$.getValue();if(!l.length)return;const c=o?"master":d;return o&&!u&&n.startTransitionTo(this.masterManifest),l.find(h=>h.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:R.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Lt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Dt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Qt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(pe.PLAYING),I(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(pe.PAUSED),I(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===pe.READY&&this.videoState.setState(pe.READY),this.videoState.getState()===pe.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(ve(),_(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&D(d.to)){const c=d.to.id;this.params.desiredState.videoTrack.setState(d.to);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Ge(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===pe.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===ee.Requested&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var o,u,d;const l=(d=(u=(o=this.video)===null||o===void 0?void 0:o.getStartDate)===null||u===void 0?void 0:u.call(o))===null||d===void 0?void 0:d.getTime();this.manifestStartTime$.next(l||void 0)},i)),this.subscription.add(Le({startTime:this.manifestStartTime$.pipe(ae(D)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(_(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));const n=H(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,He(["init"])).pipe(it(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),It(this.video)}prepare(){var e,t;const i=this.selectManifest();if(j(i))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URLSearchParams(i.url);if((r||a)&&i.id===this.masterManifest.id){const{max:d,min:l}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:a)!==null&&t!==void 0?t:{};for(const[c,h]of[[d,"mq"],[l,"lq"]]){const f=String(parseFloat(c||""));h&&f&&n.set(h,f)}}const o=this.params.format===A.HLS_LIVE_CMAF?Se.DASH_CMAF_OFFSET_P:Se.OFFSET_P,u=Ve(n.toString(),this.liveOffset.getTotalOffset(),o);this.video.setAttribute("src",u),this.video.load(),wo(u).then(d=>{var l;if(!j(d))this.maxSeekBackTime$.next(d);else{const c=(l=this.params.source.maxSeekBackTime)!==null&&l!==void 0?l:this.maxSeekBackTime$.getValue();if(j(c)||!isFinite(c))try{$i(u).then(h=>h.text()).then(h=>{var f;const m=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))===null||f===void 0?void 0:f[1];if(m){const S=new URL(m,u).toString();wo(S).then(b=>{j(b)||this.maxSeekBackTime$.next(b)})}})}catch(h){}}})}playIfAllowed(){Kt(this.video).then(e=>{e||(this.videoState.setState(pe.PAUSED),this.liveOffset.pause(),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}var ge;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(ge||(ge={}));class dS{constructor(e){this.subscription=new ue,this.videoState=new he(ge.STOPPED),this.textTracksManager=new yt,this.manifests$=new T([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const i=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r===p.STOPPED){i!==ge.STOPPED&&(this.videoState.startTransitionTo(ge.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ge.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(i===ge.STOPPED){this.videoState.startTransitionTo(ge.READY),this.prepare();return}if(n||o||u){const c=this.videoState.getState();this.videoState.setState(ge.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state===ee.None&&this.params.desiredState.seekState.setState({state:ee.Requested,position:h*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==p.PAUSED&&l.state===ee.Requested&&this.seek(l.position),i){case ge.READY:r===p.READY?I(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(ge.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(ge.PLAYING),this.playIfAllowed());return;case ge.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(ge.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case ge.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(ge.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;case ge.CHANGING_MANIFEST:break;default:return q(i)}},this.params=e,this.video=Rt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:rt.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ge(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Kd(this.params.source.url).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:R.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var e,t,i,r;const{autoVideoTrackSwitching:a,videoTrack:n}=this.params.desiredState,o=a.getState(),u=n.getTransition(),d=(r=(t=(e=u==null?void 0:u.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(i=n.getState())===null||i===void 0?void 0:i.id)!==null&&r!==void 0?r:"master",l=this.manifests$.getValue();if(!l.length)return;const c=o?"master":d;return o&&!u&&n.startTransitionTo(this.masterManifest),l.find(h=>h.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:R.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Lt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(ri(this.video,t.isLooped,i)),this.subscription.add(Dt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Qt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ge.PLAYING),I(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ge.PAUSED),I(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ge.READY&&this.videoState.setState(ge.READY),this.videoState.getState()===ge.PLAYING&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&D(d.to)){const c=d.to.id;this.params.desiredState.videoTrack.setState(d.to);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Ge(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===ge.CHANGING_MANIFEST&&this.videoState.setState(u.to),o.state===ee.Requested&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(_(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!ou()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:o}=this.video;this.subscription.add(H(U(o,"addtrack"),U(o,"removetrack"),U(o,"change"),He(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}const n=H(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,He(["init"])).pipe(it(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),It(this.video)}prepare(){var e,t;const i=this.selectManifest();if(j(i))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URLSearchParams(i.url);if((r||a)&&i.id===this.masterManifest.id){const{max:o,min:u}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:a)!==null&&t!==void 0?t:{};for(const[d,l]of[[o,"mq"],[u,"lq"]]){const c=String(parseFloat(d||""));l&&c&&n.set(l,c)}}this.video.setAttribute("src",n.toString()),this.video.load()}playIfAllowed(){Kt(this.video).then(e=>{e||(this.videoState.setState(ge.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var $e;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})($e||($e={}));class uS{constructor(e){this.subscription=new ue,this.videoState=new he($e.STOPPED),this.trackUrls={},this.textTracksManager=new yt,this.syncPlayback=()=>{var t,i,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition();if(n===p.STOPPED){a!==$e.STOPPED&&(this.videoState.startTransitionTo($e.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState($e.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.autoVideoTrackLimits.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.seekState.getState();if(d&&a!==$e.READY&&!l){this.handleQualityLimitTransition(d.to.max);return}if(a===$e.STOPPED){this.videoState.startTransitionTo($e.READY),this.prepare();return}if(l){const{currentTime:h}=this.video;this.prepare(),c.state===ee.None&&this.params.desiredState.seekState.setState({state:ee.Requested,position:h*1e3,forcePrecise:!0}),l.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((r=(i=this.trackUrls[l.to.id])===null||i===void 0?void 0:i.track)===null||r===void 0?void 0:r.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((o==null?void 0:o.to)!==p.PAUSED&&c.state===ee.Requested&&this.seek(c.position),a){case $e.READY:n===p.READY?I(this.params.desiredState.playbackState,p.READY):n===p.PAUSED?(this.videoState.setState($e.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING&&(this.videoState.startTransitionTo($e.PLAYING),this.playIfAllowed());return;case $e.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo($e.PAUSED),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case $e.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo($e.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return q(a)}},this.params=e,this.video=Rt(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{const a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:R.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Lt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(ri(this.video,t.isLooped,i)),this.subscription.add(Dt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Qt(this.video,t.playbackRate,r.playbackRateState$,i)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState($e.PLAYING),I(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState($e.PAUSED),I(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===$e.READY&&this.videoState.setState($e.READY);const u=this.params.desiredState.videoTrack.getTransition();u&&D(u.to)&&(this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to.id].track)),this.videoState.getState()===$e.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const n=H(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,He(["init"])).pipe(it(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),It(this.video)}prepare(){var e;const t=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id;P(t,"MpegProvider: track is not selected");let{url:i}=this.trackUrls[t];P(i,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(i=ii(i)),this.video.setAttribute("src",i),this.video.load(),this.params.output.hostname$.next(Ge(i))}playIfAllowed(){Kt(this.video).then(e=>{e||(this.videoState.setState($e.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,i,r,a;let n,o=e;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const u=(i=Object.values(this.trackUrls).find(c=>!yi(c.track.quality)&&Mo(c.track.quality,e)))===null||i===void 0?void 0:i.track,d=(r=this.params.desiredState.videoTrack.getState())===null||r===void 0?void 0:r.id,l=(a=this.trackUrls[d!=null?d:"0"])===null||a===void 0?void 0:a.track;if(u&&l&&Pa(l.quality,u.quality)&&(n=u),!n){const c=Object.values(this.trackUrls).filter(f=>!yi(f.track.quality)&&Vi(f.track.quality,e)),h=c.length;h&&(n=c[h-1].track)}n&&(o=n.quality)}else if(!e){const u=Object.values(this.trackUrls).map(d=>d.track);n=_i(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}n&&(this.params.output.currentVideoTrack$.next(n),this.params.desiredState.videoTrack.startTransitionTo(n)),this.params.output.autoVideoTrackLimits$.next({max:o})}}const _o=["stun:videostun.mycdn.me:80"],lS=1e3,cS=3,ma=()=>null;class hS{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=ma,this.externalStopCallback=ma,this.externalErrorCallback=ma,this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:_o}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:R.WTF,message:e.message})}async onPeerConnectionStream(e){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),lS)}normalizeOptions(e={}){const t={stunServerList:_o,maxRetryNumber:cS,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var me;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(me||(me={}));class fS{constructor(e){this.videoState=new he(me.STOPPED),this.maxSeekBackTime$=new T(0),this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(i===p.STOPPED){t!==me.STOPPED&&(this.videoState.startTransitionTo(me.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(me.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===me.STOPPED){this.videoState.startTransitionTo(me.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case me.READY:i===p.PAUSED?(this.videoState.setState(me.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):i===p.PLAYING&&(this.videoState.startTransitionTo(me.PLAYING),this.playIfAllowed());return;case me.PLAYING:i===p.PAUSED?(this.videoState.startTransitionTo(me.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case me.PAUSED:i===p.PLAYING?(this.videoState.startTransitionTo(me.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return q(t)}},this.subscription=new ue,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Rt(e.container),this.liveStreamClient=new hS(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),It(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:R.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};H(this.videoState.stateChangeStarted$.pipe(_(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(_(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const r=Lt(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())===null||n===void 0?void 0:n.to)===me.READY&&this.videoState.setState(me.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(me.PAUSED)},i)).add(r.playing$.subscribe(()=>{this.videoState.setState(me.PLAYING)},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Dt(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case me.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(p.STOPPED);break;case me.READY:break;case me.PAUSED:t.playbackState.setState(p.PAUSED);break;case me.PLAYING:t.playbackState.setState(p.PLAYING);break;default:return q(n.to)}},i)).add(H(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,He(["init"])).pipe(it(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Ge(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:rt.INVARIANT}),this.video.srcObject=e,I(this.params.desiredState.playbackState,p.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(me.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:R.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Kt(this.video).then(e=>{e||(this.videoState.setState(me.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class Po{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}}var ga,va,Sa,ba,ya,Ta,Fs,Ea,Us,$a,Vs,Aa,Hs,ka,Gs,wa,Ys,_a;const Jd=hr().device===du.Android,ti=document.createElement("video"),pS='video/mp4; codecs="avc1.42000a,mp4a.40.2"',mS='video/mp4; codecs="hev1.1.6.L93.B0"',Xd='video/webm; codecs="vp09.00.10.08"',Zd='video/webm; codecs="av01.0.00M.08"',gS='audio/mp4; codecs="mp4a.40.2"',vS='audio/webm; codecs="opus"',mt={mse:!!(window.MediaSource&&window.MediaStreamTrack&&(!((va=(ga=window.SourceBuffer)===null||ga===void 0?void 0:ga.prototype)===null||va===void 0)&&va.appendBuffer)),hls:!!(!((Sa=ti.canPlayType)===null||Sa===void 0)&&Sa.call(ti,"application/x-mpegurl")||!((ba=ti.canPlayType)===null||ba===void 0)&&ba.call(ti,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},tt={mp4:!!(!((ya=ti.canPlayType)===null||ya===void 0)&&ya.call(ti,"video/mp4")),webm:!!(!((Ta=ti.canPlayType)===null||Ta===void 0)&&Ta.call(ti,"video/webm")),cmaf:!0},Pt={h264:!!(!((Ea=(Fs=window.MediaSource)===null||Fs===void 0?void 0:Fs.isTypeSupported)===null||Ea===void 0)&&Ea.call(Fs,pS)),h265:!!(!(($a=(Us=window.MediaSource)===null||Us===void 0?void 0:Us.isTypeSupported)===null||$a===void 0)&&$a.call(Us,mS)),vp9:!!(!((Aa=(Vs=window.MediaSource)===null||Vs===void 0?void 0:Vs.isTypeSupported)===null||Aa===void 0)&&Aa.call(Vs,Xd)),av1:!!(!((ka=(Hs=window.MediaSource)===null||Hs===void 0?void 0:Hs.isTypeSupported)===null||ka===void 0)&&ka.call(Hs,Zd)),aac:!!(!((wa=(Gs=window.MediaSource)===null||Gs===void 0?void 0:Gs.isTypeSupported)===null||wa===void 0)&&wa.call(Gs,gS)),opus:!!(!((_a=(Ys=window.MediaSource)===null||Ys===void 0?void 0:Ys.isTypeSupported)===null||_a===void 0)&&_a.call(Ys,vS))},Oi=(Pt.h264||Pt.h265)&&Pt.aac;var ei;(function(s){s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient"})(ei||(ei={}));var Gt;(function(s){s.DASH="dash",s.HLS="hls",s.MPEG="mpeg"})(Gt||(Gt={}));let gi;const SS=async()=>{if(!window.navigator.mediaCapabilities)return;const s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:Zd}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:Xd}})]);gi={[A.DASH_WEBM_AV1]:e,[A.DASH_WEBM]:t}};try{SS()}catch(s){console.error(s)}const ys=mt.hls&&tt.mp4,bS=()=>Object.keys(Pt).filter(s=>Pt[s]),yS=(s,e=!1)=>s.filter(t=>{switch(t){case A.DASH:return mt.mse&&tt.mp4&&Oi;case A.DASH_SEP:return mt.mse&&tt.mp4&&Oi;case A.DASH_WEBM:return mt.mse&&tt.webm&&Pt.vp9&&Pt.opus;case A.DASH_WEBM_AV1:return mt.mse&&tt.webm&&Pt.av1&&Pt.opus;case A.DASH_LIVE:return mt.mse&&tt.mp4&&Oi;case A.DASH_LIVE_CMAF:return mt.mse&&tt.mp4&&Oi&&tt.cmaf;case A.DASH_ONDEMAND:return mt.mse&&tt.mp4&&Oi;case A.HLS:case A.HLS_ONDEMAND:return ys||e&&mt.mse&&tt.mp4&&Oi;case A.HLS_LIVE:case A.HLS_LIVE_CMAF:return ys;case A.MPEG:return tt.mp4;case A.DASH_LIVE_WEBM:return!1;case A.WEB_RTC_LIVE:return mt.webrtc&&mt.ws&&Pt.h264&&(tt.mp4||tt.webm);default:return q(t)}}),hs=s=>{const e=A.DASH_WEBM,t=A.DASH_WEBM_AV1;switch(s){case ei.VP9:return[e,t];case ei.AV1:return[t,e];case ei.NONE:return[];case ei.SMOOTH:return gi?gi[t].smooth?[t,e]:gi[e].smooth?[e,t]:[t,e]:[e,t];case ei.POWER_EFFICIENT:return gi?gi[t].powerEfficient?[t,e]:gi[e].powerEfficient?[e,t]:[t,e]:[e,t];default:q(s)}return[e,t]},TS=({webmCodec:s,androidPreferredFormat:e})=>{if(Jd)switch(e){case Gt.MPEG:return[A.MPEG,...hs(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND];case Gt.HLS:return[A.HLS,A.HLS_ONDEMAND,...hs(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.MPEG];case Gt.DASH:return[...hs(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG]}return ys?[...hs(s),A.DASH_SEP,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG,A.DASH]:[...hs(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG]},ES=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{const i=e?[A.DASH_LIVE_CMAF,A.DASH_LIVE]:[A.DASH_LIVE,A.DASH_LIVE_CMAF],r=e?[A.HLS_LIVE_CMAF,A.HLS_LIVE]:[A.HLS_LIVE,A.HLS_LIVE_CMAF],a=[...i,...r],n=[...r,...i];let o;if(Jd)switch(s){case Gt.DASH:{o=a;break}case Gt.HLS:case Gt.MPEG:{o=n;break}}else ys?o=n:o=a;return t?[A.WEB_RTC_LIVE,...o]:[...o,A.WEB_RTC_LIVE]},Do=s=>s?[A.HLS_LIVE,A.HLS_LIVE_CMAF,A.DASH_LIVE_CMAF]:[A.DASH_WEBM,A.DASH_WEBM_AV1,A.DASH_SEP,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG];var $S=s=>new fr(e=>{const t=new ue,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(_(({from:d,to:l})=>`${d}-${l}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(_(({type:d})=>d!==void 0)),n=new C;let o=0,u="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>n.next(d),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const AS={cacheDuration:12e4},kS={chunkDuration:5e3,maxParallelRequests:5};class wS{constructor(e){this.current$=new T({type:void 0}),this.providerError$=new C,this.noAvailableProvidersError$=new C,this.providerOutput={position$:new T(0),duration$:new T(1/0),volume$:new T({muted:!1,volume:1}),currentVideoTrack$:new T(void 0),availableVideoTracks$:new T([]),availableAudioTracks$:new T([]),isAudioAvailable$:new T(!0),autoVideoTrackLimitingAvailable$:new T(!1),autoVideoTrackLimits$:new T(void 0),currentBuffer$:new T(void 0),isBuffering$:new T(!0),error$:new C,warning$:new C,willSeekEvent$:new C,seekedEvent$:new C,loopedEvent$:new C,endedEvent$:new C,firstBytesEvent$:new C,firstFrameEvent$:new C,canplay$:new C,isLive$:new T(void 0),isLowLatency$:new T(!1),canChangePlaybackSpeed$:new T(!0),liveTime$:new T(void 0),liveBufferTime$:new T(void 0),availableTextTracks$:new T([]),currentTextTrack$:new T(void 0),hostname$:new T(void 0),httpConnectionType$:new T(void 0),httpConnectionReused$:new T(void 0),inPiP$:new T(!1),inFullscreen$:new T(!1),element$:new T(void 0),availableSources$:new T(void 0),is3DVideo$:new T(!1)},this.subscription=new ue,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=yS([...ES(this.params.tuning),...TS(this.params.tuning)],this.params.tuning.useHlsJs).filter(o=>D(e.sources[o])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning;let a=[];i?a=[i]:r.length?a=[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new Po(a);const n=[...Do(!0),...Do(!1)];this.chromecastFormatsIterator=new Po(n.filter(o=>D(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(j(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:R.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!==ee.None;if(this.params.desiredState.seekState.setState({state:ee.Requested,position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){const n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case Fe.SCREEN:return this.createScreenProvider(t);case Fe.CHROMECAST:return this.createChromecastProvider(t);default:return q(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:r}=this.params,a=this.providerOutput,n={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case A.DASH:{const o=this.applyFailoverHost(t[e]);return P(o),new wm({...n,source:o,config:AS})}case A.DASH_SEP:case A.DASH_WEBM:case A.DASH_WEBM_AV1:case A.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),this.params.tuning.useDashJs?new oo({...n,source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):this.params.tuning.useNewDashVkProvider?new iS({...n,source:o}):new ov({...n,source:o})}case A.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),this.params.tuning.useDashJsCMAF?new oo({...n,source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):this.params.tuning.useNewDashVkProvider?new rS({...n,source:o}):new sS({...n,source:o})}case A.HLS:case A.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),ys||!this.params.tuning.useHlsJs?new dS({...n,source:o}):new aS({...n,source:o})}case A.HLS_LIVE:case A.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new oS({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case A.MPEG:{const o=this.applyFailoverHost(t[e]);return P(o),new uS({...n,source:o})}case A.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new Tm({...n,source:o,config:{...kS,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case A.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new fS({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case A.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return q(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return P(o),new Ip({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?Fe.CHROMECAST:Fe.SCREEN}chooseFormat(e){switch(e){case Fe.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case Fe.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return q(e)}}skipFormat(e){switch(e){case Fe.SCREEN:return this.screenFormatsIterator.next();case Fe.CHROMECAST:return this.chromecastFormatsIterator.next();default:return q(e)}}handleNoFormatsError(e){switch(e){case Fe.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case Fe.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return q(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=r=>{const a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return Ei(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){const e=new ue;let t=!1,i=0;return e.add(H(this.providerOutput.error$,$S({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(_(r=>({id:`ProviderHangup:${r}`,category:R.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const r=this.params.desiredState.playbackState.transitionEnded$.pipe(ae(({to:a})=>a===p.PLAYING),Ae()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{const a=this.current$.getValue().destination;if(a===Fe.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(Fe.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=r.category===R.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),u=i<this.params.tuning.providerErrorLimit;o&&(n&&t||!u)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):u?(i++,this.reinitProvider()):this.switchToNextProvider(a!=null?a:Fe.SCREEN)}})),e}}const _S=5e3,Ro="one_video_throughput",Io="one_video_rtt",Yt=window.navigator.connection,Lo=()=>{const s=Yt==null?void 0:Yt.downlink;if(D(s)&&s!==10)return s*1e3},xo=()=>{const s=Yt==null?void 0:Yt.rtt;if(D(s)&&s!==3e3)return s},Co=(s,e,t)=>{const i=t*8,r=i/s;return i/(r+e)};class gs{constructor(e){var t,i;this.subscription=new ue,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=gs.load(Ro)||(e.useBrowserEstimation?Lo():void 0)||_S,a=(i=(t=gs.load(Io))!==null&&t!==void 0?t:e.useBrowserEstimation?xo():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new T(r),this.rtt$=new T(a),this.rttAdjustedThroughput$=new T(Co(r,a,e.rttPenaltyRequestSize)),this.throughput=Ya.getSmoothedValue(r,-1,e),this.rtt=Ya.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const u=Lo();u&&this.throughput.next(u);const d=xo();D(d)&&this.rtt.next(d)};Yt&&"onchange"in Yt&&this.subscription.add(U(Yt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Fr.set(Ro,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Fr.set(Io,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Le({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(_(({throughput:n,rtt:o})=>Co(n,o,e.rttPenaltyRequestSize)),ae(n=>{const o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=le();const r=new ue;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(U(e,"progress").pipe(Ae()).subscribe(a=>{t=a.loaded,i=le()}));break;case 1:case 0:r.add(U(e,"loadstart").subscribe(()=>{t=0,i=le()}));break}r.add(U(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=le(),u=n-t,d=o-i;this.addRawSpeed(u,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){const i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=le(),n=0,o=le();const u=l=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${l}`).catch(()=>{})},d=async({done:l,value:c})=>{if(l)!t&&this.addRawSpeed(r,le()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){if(le()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=c.byteLength;else{const f=o-a;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,a=le()}o=le()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&le()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,le()-o,this.concurrentDownloads.size),n=0,o=le());await(i==null?void 0:i.read().then(d,u))}};this.concurrentDownloads.add(e),i==null||i.read().then(d,u)}addRawSpeed(e,t,i=1,r=!1){if(gs.sanityCheck(e,t,r)){const a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){const r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var t;const i=Fr.get(e);if(D(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const Bo={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:rt.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,maxWaitingDuration:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:ei.VP9,androidPreferredFormat:Gt.MPEG,preferCMAF:!0,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useDashJsCMAF:!1,useNewDashVkProvider:!0,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},PS=s=>{var e;return{...uu(s,Bo),configName:[...(e=s.configName)!==null&&e!==void 0?e:[],...Bo.configName]}};var Oo=({seekState:s,position$:e})=>H(s.stateChangeEnded$.pipe(_(({to:t})=>{var i;return t.state===ee.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),ae(D)),e.pipe(ae(()=>s.getState().state===ee.None))),DS=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return P(e,`Wrong container or containerId {${s.container}}`),e};const RS=(s,e,t,i)=>{s!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(ae(r=>r.length>0),Ae()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};class ob{constructor(e={configName:[]}){if(this.subscription=new ue,this.logger=new lu,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.desiredState={playbackState:new he(p.STOPPED),seekState:new he({state:ee.None}),volume:new he({volume:1,muted:!1}),videoTrack:new he(void 0),autoVideoTrackSwitching:new he(!0),autoVideoTrackLimits:new he({}),isLooped:new he(!1),playbackRate:new he(1),externalTextTracks:new he([]),internalTextTracks:new he([]),currentTextTrack:new he(void 0),textTrackCuesSettings:new he({}),cameraOrientation:new he({x:0,y:0})},this.info={playbackState$:new T(p.STOPPED),position$:new T(0),duration$:new T(1/0),muted$:new T(!1),volume$:new T(1),availableQualities$:new T([]),availableQualitiesFps$:new T({}),availableAudioTracks$:new T([]),isAudioAvailable$:new T(!0),currentQuality$:new T(void 0),isAutoQualityEnabled$:new T(!0),autoQualityLimitingAvailable$:new T(!1),autoQualityLimits$:new T({}),currentPlaybackRate$:new T(1),currentBuffer$:new T({start:0,end:0}),isBuffering$:new T(!0),isStalled$:new T(!1),isEnded$:new T(!1),isLooped$:new T(!1),isLive$:new T(void 0),canChangePlaybackSpeed$:new T(void 0),atLiveEdge$:new T(void 0),atLiveDurationEdge$:new T(void 0),liveTime$:new T(void 0),liveBufferTime$:new T(void 0),currentFormat$:new T(void 0),availableTextTracks$:new T([]),currentTextTrack$:new T(void 0),throughputEstimation$:new T(void 0),rttEstimation$:new T(void 0),videoBitrate$:new T(void 0),hostname$:new T(void 0),httpConnectionType$:new T(void 0),httpConnectionReused$:new T(void 0),surface$:new T(Zt.NONE),chromecastState$:new T(xe.NOT_AVAILABLE),chromecastDeviceName$:new T(void 0),intrinsicVideoSize$:new T(void 0),availableSources$:new T(void 0),is3DVideo$:new T(!1)},this.events={inited$:new C,ready$:new C,started$:new C,playing$:new C,paused$:new C,stopped$:new C,willStart$:new C,willResume$:new C,willPause$:new C,willStop$:new C,willDestruct$:new C,watchCoverageRecord$:new C,watchCoverageLive$:new C,managedError$:new C,fatalError$:new C,ended$:new C,looped$:new C,seeked$:new C,willSeek$:new C,firstBytes$:new C,firstFrame$:new C,canplay$:new C,log$:new C},this.experimental={element$:new T(void 0),tuningConfigName$:new T([]),enableDebugTelemetry$:new T(!1),dumpTelemetry:tm},this.initLogs(),this.tuning=PS(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new mu({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new gs(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{const a=Reflect.get(t,i,r);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const u=n.map(c=>JSON.stringify(c,(h,f)=>{const m=typeof f;return["number","string","boolean"].includes(m)?f:f===null?null:`<${m}>`})),d=`Player.${String(i)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:R.WTF,message:l,thrown:o}),o}}}})}initVideo(e){var t,i,r;return this.config=e,this.domContainer=DS(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new wS({sources:e.sources,meta:(i=e.meta)!==null&&i!==void 0?i:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===p.STOPPED&&e.startTransitionTo(p.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==p.PLAYING&&t.startTransitionTo(p.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?U(document,"visibilitychange").pipe(Ae()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==p.PAUSED&&e.startTransitionTo(p.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==p.STOPPED&&e.startTransitionTo(p.STOPPED),this}seekTime(e,t=!0){const i=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=i&&!r&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:ee.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===xe.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===xe.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){P(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(ae(i=>i.length>0),Ae()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var t;P(this.providerContainer);const i=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return i&&(this.desiredState.playbackRate.setState(e),i.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return RS(e,this.desiredState.currentTextTrack,(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){const i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const i=this.getScene3D();if(i){const r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){P(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(j(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===ee.None?void 0:t.position;return D(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const i=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=i==null?void 0:i.provider)===null||t===void 0)&&t.scene3D)return i.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(H(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(_(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ae(({from:e})=>e===p.STOPPED),Ae()).subscribe(()=>{this.initedAt=le(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case p.READY:this.events.ready$.next();break;case p.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case p.PAUSED:this.events.paused$.next();break;case p.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case p.PAUSED:this.events.willPause$.next();break;case p.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case p.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===ee.Requested?this.desiredState.seekState.setState({...n,state:ee.Applying}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:R.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===ee.Applying&&(this.desiredState.seekState.setState({state:ee.None}),this.events.seeked$.next())})).add(e.current$.pipe(_(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(_(n=>n.destination),ve()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(_(n=>n.map(({quality:o})=>o).sort((o,u)=>yi(o)?1:yi(u)?-1:Vi(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{const o={};for(const u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.hostname$.pipe(ve()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(ve()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(ve()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(_(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(Le({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Oo({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(_(({isLive:n,position:o,isLowLatency:u})=>{const d=u?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return n&&Math.abs(o)<d/1e3}),ve(),Ks(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(Le({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(_(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),ve(),Ks(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(_(n=>n.muted),ve()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(_(n=>n.volume),ve()).subscribe(this.info.volume$)).add(Oo({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(H(e.providerOutput.endedEvent$.pipe(Hi(!0)),e.providerOutput.seekedEvent$.pipe(Hi(!1))).pipe(ve()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(_(n=>({id:n?`No${n}`:"NoProviders",category:R.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(Ae(),_(n=>n!=null?n:le()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(Ae(),_(()=>le()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Ae(),_(()=>le()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new T(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new T(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ae(({to:n})=>n===p.PLAYING),Ae()).subscribe(()=>i.next(!1)));let r=0;const a=H(e.providerOutput.isBuffering$,t,i).pipe(_(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),ve());this.subscription.add(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(H(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var o,u;const d=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(o=n==null?void 0:n.size)===null||o===void 0?void 0:o.width,height:(u=n==null?void 0:n.size)===null||u===void 0?void 0:u.height},{width:d==null?void 0:d.videoWidth,height:d==null?void 0:d.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(H(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),d=this.chromecastInitializer.castState$.getValue();let l;d===xe.CONNECTED?l=Zt.SECOND_SCREEN:u?n?l=Zt.PIP:o?l=Zt.FULLSCREEN:l=Zt.INLINE:l=Zt.NONE,this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(_(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new ue;this.subscription.add(t),this.subscription.add(e.current$.pipe(ve((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ae(i=>i.length>0),Ae()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var t;let i;const r=(t=this.desiredState.videoTrack.getState())===null||t===void 0?void 0:t.quality;r&&(i=e.find(({quality:a})=>a===r),i||this.setAutoQuality(!0)),i||(i=_i(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(i),this.info.currentQuality$.next(i.quality),this.info.videoBitrate$.next(i.bitrate)}initLogs(){this.subscription.add(H(this.desiredState.videoTrack.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(_(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;P(this.providerContainer),P(t),em(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Zp(i)),this.providerContainer.current$.subscribe(({type:i})=>Bs("provider",i)),t.duration$.subscribe(i=>Bs("duration",i)),t.availableVideoTracks$.pipe(ae(i=>!!i.length),Ae()).subscribe(i=>Bs("tracks",i)),this.events.fatalError$.subscribe(new kt("fatalError")),this.events.managedError$.subscribe(new kt("managedError")),t.position$.subscribe(new kt("position")),t.currentVideoTrack$.pipe(_(i=>i==null?void 0:i.quality)).subscribe(new kt("quality")),this.info.currentBuffer$.subscribe(new kt("buffer")),t.isBuffering$.subscribe(new kt("isBuffering"))].forEach(i=>this.subscription.add(i)),Bs("codecs",bS())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:R.DOM,message:String(r)})})};this.subscription.add(H(U(document,"visibilitychange"),U(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===p.PLAYING,n=!!e&&!(e!=null&&e.released);r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const i=e.find(r=>r.quality===t);i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}}const db=`@vkontakte/videoplayer-core@${fu}`;export{xe as ChromecastState,vs as HttpConnectionType,cb as Observable,p as PlaybackState,ob as Player,db as SDK_VERSION,hb as Subject,fb as Subscription,Zt as Surface,fu as VERSION,pb as ValueSubject,A as VideoFormat,mb as VideoQuality};
|
|
45
|
+
varying vec2 v_texel;uniform sampler2D u_texture;uniform vec2 u_focus;void main(void){float lambda0=u_focus.x/360.0;float phi0=u_focus.y/180.0;float lambda=PI*2.0*(v_texel.x-0.5-lambda0);float phi=PI*(v_texel.y-0.5-phi0);float p=sqrt(lambda*lambda+phi*phi);float c=atan(p);float cos_c=cos(c);float sin_c=sin(c);float x=lambda0+atan(lambda*sin_c,p*cos(phi0)*cos_c-phi*sin(phi0)*sin_c);float y=asin(cos_c*sin(phi0)+(phi*sin_c*cos(phi0))/p);vec2 tc=vec2(mod(x/(PI*2.0)-0.5,1.0),mod(y/PI-0.5,1.0));gl_FragColor=texture2D(u_texture,tc);}`;class Yd{constructor(e,t,i){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();const r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new rv(this.params.fov,this.params.orientation),this.cameraRotationManager=new av(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(nv,this.gl.VERTEX_SHADER),i=this.createShader(ov,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1;const r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,n=t-r,o=e+i,u=t-r,d=e+i,l=t+r,c=e-i,h=t+r;return[a,n,o,u,d,l,c,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){const e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}}let zd=class{constructor(e){this.subscription=new ue,this.videoState=new he(Te.STOPPED),this.elementSize$=new T(void 0),this.textTracksManager=new yt,this.droppedFramesManager=new ks,this.videoTracks$=new T([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Id,this.textTracks=[],this.syncPlayback=()=>{var t,i,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(u.state===ee.Requested&&(o==null?void 0:o.to)!==p.PAUSED&&a!==Te.STOPPED&&n!==p.STOPPED){const l=(i=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&i!==void 0?i:0;this.seek(u.position-l,u.forcePrecise)}if(n===p.STOPPED){a!==Te.STOPPED&&(this.videoState.startTransitionTo(Te.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Te.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}switch(a){case Te.STOPPED:this.videoState.startTransitionTo(Te.READY),this.prepare();return;case Te.READY:n===p.PAUSED?(this.videoState.setState(Te.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING?(this.videoState.startTransitionTo(Te.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.READY&&I(this.params.desiredState.playbackState,p.READY);return;case Te.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(Te.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case Te.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(Te.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return z(a)}}},this.init3DScene=t=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Yd(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=t.projectionData)===null||i===void 0?void 0:i.pose.yaw)||0,y:((r=t.projectionData)===null||r===void 0?void 0:r.pose.pitch)||0,z:((a=t.projectionData)===null||a===void 0?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const n=this.elementSize$.getValue();n&&this.scene3D.setViewportSize(n.width,n.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=Rt(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ye(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new sv({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=Lt(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:R.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(_(d=>d.map(({track:l})=>l)))}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(ae(D),Ae()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ri(this.video,t.isLooped,r)),this.subscription.add(Dt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Qt(this.video,t.playbackRate,i.playbackRateState$,r)),a(ys(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(Te.PLAYING),I(t.playbackState,p.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(Te.PAUSED),I(t.playbackState,p.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===Te.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d===nt.MANIFEST_READY){const c=[];this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();P(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((v,y)=>y.bitrate-v.bitrate),m=Array.from(h.video).sort((v,y)=>y.bitrate-v.bitrate),S=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const v of f){const y=hg(v);y&&this.audioTracks.push({track:y,representation:v})}for(const v of m){const y=cg(v);if(y){c.push({track:y,representation:v});const g=!this.params.tuning.isAudioDisabled&&fg(f,m,v);g&&this.audioRepresentations.set(v.id,g)}}this.videoTracks$.next(c);for(const v of S){const y=pg(v);y&&this.textTracks.push({track:y,representation:v})}this.params.output.availableVideoTracks$.next(c.map(({track:v})=>v)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:v})=>v)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:v})=>v));const b=this.selectVideoRepresentation();P(b),this.player.initRepresentations(b.id,(l=this.audioRepresentations.get(b.id))===null||l===void 0?void 0:l.id)}else d===nt.REPRESENTATIOS_READY&&(this.videoState.setState(Te.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:R.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(H(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,U(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!==nt.RUNNING||l||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation(),h=this.params.desiredState.autoVideoTrackLimits.getTransition();if(h&&this.params.output.autoVideoTrackLimits$.next(h.to),c){this.player.switchRepresentation(Be.VIDEO,c.id).catch(n);const f=this.audioRepresentations.get(c.id);f&&this.player.switchRepresentation(Be.AUDIO,f.id).catch(n)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ve(),_(d=>{var l;return d&&((l=this.videoTracks$.getValue().find(({representation:{id:c}})=>c===d))===null||l===void 0?void 0:l.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var l,c;if(d!=null&&d.is3dVideo&&(!((l=this.params.tuning.spherical)===null||l===void 0)&&l.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe(_(({to:d})=>d===p.READY),ve());this.subscription.add(H(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===p.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(H(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===p.READY)));const u=H(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ge(["init"])).pipe(st(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,i,r,a,n,o;const u=this.params.desiredState.autoVideoTrackSwitching.getState(),d=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id,l=(t=this.videoTracks$.getValue().find(({track:{id:y}})=>y===d))===null||t===void 0?void 0:t.track,c=this.params.output.currentVideoTrack$.getValue(),h=Qe(this.video.buffered,this.video.currentTime*1e3),f=u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=Math.min(h/Math.min(f,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),S=Math.max(l&&!u&&(r=(i=this.audioRepresentations.get(l.id))===null||i===void 0?void 0:i.bitrate)!==null&&r!==void 0?r:0,c&&(n=(a=this.audioRepresentations.get(c.id))===null||a===void 0?void 0:a.bitrate)!==null&&n!==void 0?n:0),b=_i(this.videoTracks$.getValue().map(({track:y})=>y),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:m,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),v=u?b!=null?b:l:l!=null?l:b;return v&&((o=this.videoTracks$.getValue().find(({track:y})=>y===v))===null||o===void 0?void 0:o.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Kt(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(Te.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),It(this.video)}},dv=class extends zd{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var Me;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(Me||(Me={}));var At;(function(s){s[s.ActiveLowLatency=0]="ActiveLowLatency",s[s.LiveWithTargetOffset=1]="LiveWithTargetOffset",s[s.LiveForwardBuffering=2]="LiveForwardBuffering",s[s.None=3]="None"})(At||(At={}));var dr;(function(s){s.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",s.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(dr||(dr={}));var ut;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(ut||(ut={}));var Z;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(Z||(Z={}));var qi;(function(s){s.MP4="mp4",s.WEBM="webm"})(qi||(qi={}));var ur;(function(s){s[s.RECTANGULAR=0]="RECTANGULAR",s[s.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",s[s.CUBEMAP=2]="CUBEMAP",s[s.MESH=3]="MESH"})(ur||(ur={}));var Ee;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Ee||(Ee={}));var fa,pa;let qd=!1;try{qd=hr().browser===ja.Safari&&parseInt((pa=(fa=navigator.userAgent.match(/Version\/(\d+)/))===null||fa===void 0?void 0:fa[1])!==null&&pa!==void 0?pa:"",10)<16}catch(s){console.error(s)}class uv{constructor(e){this.bufferFull$=new C,this.error$=new C,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const i=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!i),this.currentTask=null}this.queue.length&&this.pull()}catch(i){this.error$.next({id:"BufferTaskQueueUnknown",category:R.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i;qd&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:i}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&i==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${i}`,category:R.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:z(t)}}}class ht{get id(){return this.type}get size(){return this.size32}constructor(e){this.cursor=0,this.source=e,this.children=[];const t=this.readUint32();this.size32=t<=e.buffer.byteLength?t:NaN,this.type=this.readString(4),this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,e.byteOffset+this.cursor,this.size32?this.size32-8:void 0),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}readString(e,t="ascii"){const r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){const e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){const e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){const e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){const e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}}class jd extends ht{}class lv extends ht{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const i=this.readString(4);this.compatibleBrands.push(i),t-=4}}}class cv extends ht{parseChildrenBoxes(){return ai(this.content)}}class hv extends ht{parseChildrenBoxes(){return ai(this.content)}}class fv extends ht{constructor(e){super(e),this.data=this.content}}class Jt extends ht{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class pv extends Jt{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let i=this.readUint32();const r=i>>>31,a=i<<1>>>1,n=this.readUint32();i=this.readUint32();const o=i>>>28,u=i<<3>>>3;this.segments.push({referenceType:r,referencedSize:a,subsegmentDuration:n,SAPType:o,SAPDeltaTime:u})}}}class mv extends ht{parseChildrenBoxes(){return ai(this.content)}}class gv extends ht{parseChildrenBoxes(){return ai(this.content)}}var bi;(function(s){s[s.MONOSCOPIC=0]="MONOSCOPIC",s[s.TOP_BOTTOM=1]="TOP_BOTTOM",s[s.LEFT_RIGHT=2]="LEFT_RIGHT",s[s.STEREO_CUSTOM=3]="STEREO_CUSTOM",s[s.RIGHT_LEFT=4]="RIGHT_LEFT"})(bi||(bi={}));class vv extends Jt{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=bi.MONOSCOPIC;break;case 1:this.stereoMode=bi.TOP_BOTTOM;break;case 2:this.stereoMode=bi.LEFT_RIGHT;break;case 3:this.stereoMode=bi.STEREO_CUSTOM;break;case 4:this.stereoMode=bi.RIGHT_LEFT;break}this.cursor+=1}}class Sv extends Jt{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class bv extends Jt{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class yv extends ht{parseChildrenBoxes(){return ai(this.content)}}class Tv extends Jt{constructor(e){super(e),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}}class Ev extends ht{parseChildrenBoxes(){return ai(this.content)}}class $v extends ht{parseChildrenBoxes(){return ai(this.content)}}class Av extends Jt{constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class wv extends ht{parseChildrenBoxes(){return ai(this.content)}}class kv extends Jt{constructor(e){super(e),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}}class _v extends Jt{get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e){super(e),this.baseMediaDecodeTime32=0,this.baseMediaDecodeTime64=BigInt(0),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class Pv extends Jt{constructor(e){super(e),this.sampleDuration=[],this.sampleSize=[],this.sampleFlags=[],this.sampleCompositionTimeOffset=[],this.optionalFields=0,this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let t=0;t<this.sampleCount;t++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}}const Dv={ftyp:lv,moov:cv,moof:hv,mdat:fv,sidx:pv,trak:mv,mdia:yv,mfhd:Av,tkhd:Tv,traf:wv,tfhd:kv,tfdt:_v,trun:Pv,minf:Ev,sv3d:gv,st3d:vv,prhd:Sv,proj:$v,equi:bv,unknown:jd};class Rv{createBox(e,t){const i=Dv[e];return i?new i(t):new jd(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return wr.createBox(i,new DataView(e.buffer,e.byteOffset))}}const wr=new Rv;function ps(s,e){const t=new Uint8Array(s.buffer),i=e.split("").map(n=>n.charCodeAt(0));let r=s.byteOffset,a=[];for(;r<t.byteLength;){if(t[r]===i[a.length]?a.push(t[r]):a=[],a.length===4){const o=new DataView(s.buffer,r-7,4).getUint32(0);return r-7+o>s.buffer.byteLength?null:wr.createBox(e,new DataView(s.buffer,r-7))}r++}return null}function Ga(s,e){const t=[];let i=s.byteOffset;for(;i<s.buffer.byteLength;){const r=ps(new DataView(s.buffer,i,s.buffer.byteLength-i),e);if(r)t.push(r),i=r.source.byteOffset+r.size;else break}return t}function ai(s){const e=[];let t=0;for(;t<s.byteLength;){const i=wr.createFromView(new DataView(s.buffer,s.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const Iv=new TextDecoder("ascii"),Lv=s=>Iv.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",xv=s=>{const e=wr.createFromView(s);let t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=a.subsegmentDuration/e.timescale*1e3,o={status:Z.NONE,time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},Cv=s=>{const e=Ga(s,"mdat"),t=Ga(s,"moof");if(!(e.length&&t.length))return null;const i=t[0],r=e[e.length-1],a=i.source.byteOffset,o=r.source.byteOffset-i.source.byteOffset+r.size;return new DataView(s.buffer,a,o)},Bv=(s,e)=>{const t=Ga(s,"traf"),i=t[t.length-1].children.find(u=>u.type==="tfhd"),r=t[t.length-1].children.find(u=>u.type==="tfdt"),a=t[t.length-1].children.find(u=>u.type==="trun");let n=0;return a.sampleDuration.length?n=a.sampleDuration.reduce((u,d)=>u+d,0):n=i.defaultSampleDuration*a.sampleCount,(Number(r.baseMediaDecodeTime)+n)/e*1e3},Mv=s=>{const e={is3dVideo:!1,stereoMode:0,projectionType:ur.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(ps(s,"sv3d")){e.is3dVideo=!0;const i=ps(s,"st3d");i&&(e.stereoMode=i.stereoMode);const r=ps(s,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const a=ps(s,"equi");a&&(e.projectionData.bounds.top=a.projectionBoundsTop,e.projectionData.bounds.right=a.projectionBoundsRight,e.projectionData.bounds.bottom=a.projectionBoundsBottom,e.projectionData.bounds.left=a.projectionBoundsLeft)}return e},Ov={validateData:Lv,parseInit:Mv,getIndexRange:()=>{},parseSegments:xv,parseFeedableSegmentChunk:Cv,getSegmentEndTime:Bv};var k;(function(s){s[s.EBML=440786851]="EBML",s[s.EBMLVersion=17030]="EBMLVersion",s[s.EBMLReadVersion=17143]="EBMLReadVersion",s[s.EBMLMaxIDLength=17138]="EBMLMaxIDLength",s[s.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",s[s.DocType=17026]="DocType",s[s.DocTypeVersion=17031]="DocTypeVersion",s[s.DocTypeReadVersion=17029]="DocTypeReadVersion",s[s.Void=236]="Void",s[s.Segment=408125543]="Segment",s[s.SeekHead=290298740]="SeekHead",s[s.Seek=19899]="Seek",s[s.SeekID=21419]="SeekID",s[s.SeekPosition=21420]="SeekPosition",s[s.Info=357149030]="Info",s[s.TimestampScale=2807729]="TimestampScale",s[s.Duration=17545]="Duration",s[s.Tracks=374648427]="Tracks",s[s.TrackEntry=174]="TrackEntry",s[s.Video=224]="Video",s[s.Projection=30320]="Projection",s[s.ProjectionType=30321]="ProjectionType",s[s.ProjectionPrivate=30322]="ProjectionPrivate",s[s.Chapters=272869232]="Chapters",s[s.Cluster=524531317]="Cluster",s[s.Timestamp=231]="Timestamp",s[s.SilentTracks=22612]="SilentTracks",s[s.SilentTrackNumber=22743]="SilentTrackNumber",s[s.Position=167]="Position",s[s.PrevSize=171]="PrevSize",s[s.SimpleBlock=163]="SimpleBlock",s[s.BlockGroup=160]="BlockGroup",s[s.EncryptedBlock=175]="EncryptedBlock",s[s.Attachments=423732329]="Attachments",s[s.Tags=307544935]="Tags",s[s.Cues=475249515]="Cues",s[s.CuePoint=187]="CuePoint",s[s.CueTime=179]="CueTime",s[s.CueTrackPositions=183]="CueTrackPositions",s[s.CueTrack=247]="CueTrack",s[s.CueClusterPosition=241]="CueClusterPosition",s[s.CueRelativePosition=240]="CueRelativePosition",s[s.CueDuration=178]="CueDuration",s[s.CueBlockNumber=21368]="CueBlockNumber",s[s.CueCodecState=234]="CueCodecState",s[s.CueReference=219]="CueReference",s[s.CueRefTime=150]="CueRefTime"})(k||(k={}));var F;(function(s){s.SignedInteger="int",s.UnsignedInteger="uint",s.Float="float",s.String="string",s.UTF8="utf8",s.Date="date",s.Master="master",s.Binary="binary"})(F||(F={}));const Eo={[k.EBML]:{type:F.Master},[k.EBMLVersion]:{type:F.UnsignedInteger},[k.EBMLReadVersion]:{type:F.UnsignedInteger},[k.EBMLMaxIDLength]:{type:F.UnsignedInteger},[k.EBMLMaxSizeLength]:{type:F.UnsignedInteger},[k.DocType]:{type:F.String},[k.DocTypeVersion]:{type:F.UnsignedInteger},[k.DocTypeReadVersion]:{type:F.UnsignedInteger},[k.Void]:{type:F.Binary},[k.Segment]:{type:F.Master},[k.SeekHead]:{type:F.Master},[k.Seek]:{type:F.Master},[k.SeekID]:{type:F.Binary},[k.SeekPosition]:{type:F.UnsignedInteger},[k.Info]:{type:F.Master},[k.TimestampScale]:{type:F.UnsignedInteger},[k.Duration]:{type:F.Float},[k.Tracks]:{type:F.Master},[k.TrackEntry]:{type:F.Master},[k.Video]:{type:F.Master},[k.Projection]:{type:F.Master},[k.ProjectionType]:{type:F.UnsignedInteger},[k.ProjectionPrivate]:{type:F.Master},[k.Chapters]:{type:F.Master},[k.Cluster]:{type:F.Master},[k.Timestamp]:{type:F.UnsignedInteger},[k.SilentTracks]:{type:F.Master},[k.SilentTrackNumber]:{type:F.UnsignedInteger},[k.Position]:{type:F.UnsignedInteger},[k.PrevSize]:{type:F.UnsignedInteger},[k.SimpleBlock]:{type:F.Binary},[k.BlockGroup]:{type:F.Master},[k.EncryptedBlock]:{type:F.Binary},[k.Attachments]:{type:F.Master},[k.Tags]:{type:F.Master},[k.Cues]:{type:F.Master},[k.CuePoint]:{type:F.Master},[k.CueTime]:{type:F.UnsignedInteger},[k.CueTrackPositions]:{type:F.Master},[k.CueTrack]:{type:F.UnsignedInteger},[k.CueClusterPosition]:{type:F.UnsignedInteger},[k.CueRelativePosition]:{type:F.UnsignedInteger},[k.CueDuration]:{type:F.UnsignedInteger},[k.CueBlockNumber]:{type:F.UnsignedInteger},[k.CueCodecState]:{type:F.UnsignedInteger},[k.CueReference]:{type:F.Master},[k.CueRefTime]:{type:F.UnsignedInteger}},Wd=s=>{const e=s.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=lr(s,t),r=i in Eo,a=r?Eo[i].type:F.Binary,n=s.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const u=new DataView(s.buffer,s.byteOffset+t+1,o-1),d=n&255>>o,l=lr(u),c=d*2**((o-1)*8)+l,h=t+o;let f;return h+c>s.byteLength?f=new DataView(s.buffer,s.byteOffset+h):f=new DataView(s.buffer,s.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:f,valueSize:c}},lr=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{const t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},_t=(s,e)=>{switch(e){case F.SignedInteger:return s.getInt8(0);case F.UnsignedInteger:return lr(s);case F.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case F.String:return new TextDecoder("ascii").decode(s);case F.UTF8:return new TextDecoder("utf-8").decode(s);case F.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case F.Master:return s;case F.Binary:return s;default:z(e)}},ji=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=Wd(i);if(!e(r))return;r.type===F.Master&&ji(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},Nv=s=>{if(s.getUint32(0)!==k.EBML)return!1;let e,t,i;const r=Wd(s);return ji(r.value,({tag:a,type:n,value:o})=>(a===k.EBMLReadVersion?e=_t(o,n):a===k.DocType?t=_t(o,n):a===k.DocTypeReadVersion&&(i=_t(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Qd=[k.Info,k.SeekHead,k.Tracks,k.TrackEntry,k.Video,k.Projection,k.ProjectionType,k.ProjectionPrivate,k.Chapters,k.Cluster,k.Cues,k.Attachments,k.Tags],Fv=[k.Timestamp,k.SilentTracks,k.SilentTrackNumber,k.Position,k.PrevSize,k.SimpleBlock,k.BlockGroup,k.EncryptedBlock],Uv=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,d,l=!1;const c=0;return ji(s,({tag:h,type:f,value:m,valueSize:S})=>{if(h===k.SeekID){const b=_t(m,f);d=lr(b)}else h!==k.SeekPosition&&(d=void 0);return h===k.Segment?(e=m.byteOffset,t=m.byteOffset+S):h===k.Info?a=!0:h===k.SeekHead?n=!0:h===k.TimestampScale?i=_t(m,f):h===k.Duration?r=_t(m,f):h===k.SeekPosition&&d===k.Cues?u=_t(m,f):h===k.Tracks?ji(m,({tag:b,type:v,value:y})=>b===k.ProjectionType?(l=_t(y,v)===1,!1):!0):a&&n&&Qd.includes(h)&&(o=!0),!o}),P(e,"Failed to parse webm Segment start"),P(t,"Failed to parse webm Segment end"),P(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u,is3dVideo:l,stereoMode:c,projectionType:ur.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Vv=s=>{if(j(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Hv=(s,e)=>{let t=!1,i=!1;const r=o=>D(o.time)&&D(o.position),a=[];let n;return ji(s,({tag:o,type:u,value:d})=>{switch(o){case k.Cues:t=!0;break;case k.CuePoint:n&&r(n)&&a.push(n),n={};break;case k.CueTime:n&&(n.time=_t(d,u));break;case k.CueTrackPositions:break;case k.CueClusterPosition:n&&(n.position=_t(d,u));break;default:t&&Qd.includes(o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{const{time:d,position:l}=o,c=a[u+1];return{status:Z.NONE,time:{from:d,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},Gv=s=>{let e=0,t=!1;try{ji(s,i=>i.tag===k.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Fv.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[k.SimpleBlock,k.BlockGroup,k.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},Yv={validateData:Nv,parseInit:Uv,getIndexRange:Vv,parseSegments:Hv,parseFeedableSegmentChunk:Gv},$o=s=>{if(!s.startsWith("P"))return;const e=(n,o)=>{const u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,a={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},Oi=(s,e)=>{let t=s;t=or(t,"$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,a]of Object.entries(i)){const n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=or(t,n,(o,u)=>j(a)?o:j(u)?a:a.padStart(parseInt(u,10),"0"))}return t},zv=(s,e)=>{var t,i,r,a,n,o,u,d,l,c,h,f,m,S,b,v,y,g,E,$,L,G,Q,V,q,W,B,M,K,O,x,Y,te,fe,be,Pe,ze,rt,ie;const qe=new DOMParser().parseFromString(s,"application/xml"),De={video:[],audio:[],text:[]},we=qe.children[0],Ct=we.getElementsByTagName("Period")[0],Bt=Ct.children,Xt=we.getAttribute("type")==="dynamic",Mt=we.getAttribute("availabilityStartTime"),Pi=Mt?new Date(Mt).getTime():void 0;let Ne;const Xi=we.getAttribute("mediaPresentationDuration"),Zi=Ct.getAttribute("duration"),ni=we.getElementsByTagName("vk:Attrs")[0],es=ni==null?void 0:ni.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(Xi)Ne=$o(Xi);else if(Zi){const ye=$o(Zi);D(ye)&&(Ne=ye)}else es&&(Ne=parseInt(es,10));let kr=0;const oi=(i=(t=we.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],_r=oi.includes(dr.WEBM_AS_IN_FFMPEG)||oi.includes(dr.WEBM_AS_IN_SPEC)?qi.WEBM:qi.MP4;for(const ye of Bt){const Ot=ye.getAttribute("mimeType"),Pr=ye.getAttribute("codecs"),ts=(r=ye.getAttribute("contentType"))!==null&&r!==void 0?r:Ot==null?void 0:Ot.split("/")[0],Dr=(n=(a=ye.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],is=ye.querySelectorAll("Representation"),Rr=ye.querySelector("SegmentTemplate");if(ts===Me.TEXT){for(const J of is){const Re=J.getAttribute("id")||"",Nt=ye.getAttribute("lang"),Ke=(d=(u=(o=J.querySelector("BaseURL"))===null||o===void 0?void 0:o.textContent)===null||u===void 0?void 0:u.trim())!==null&&d!==void 0?d:"",di=new URL(Ke,e).toString(),ui=Re.includes("_auto");De[Me.TEXT].push({id:Re,lang:Nt,isAuto:ui,kind:Me.TEXT,url:di})}continue}for(const J of is){const Re=(l=J.getAttribute("mimeType"))!==null&&l!==void 0?l:Ot,Nt=(h=(c=J.getAttribute("codecs"))!==null&&c!==void 0?c:Pr)!==null&&h!==void 0?h:"",Ke=(m=(f=J.getAttribute("contentType"))!==null&&f!==void 0?f:Re==null?void 0:Re.split("/")[0])!==null&&m!==void 0?m:ts,di=(b=(S=ye.getAttribute("profiles"))===null||S===void 0?void 0:S.split(","))!==null&&b!==void 0?b:[],ui=parseInt((v=J.getAttribute("width"))!==null&&v!==void 0?v:"",10),ss=parseInt((y=J.getAttribute("height"))!==null&&y!==void 0?y:"",10),rs=parseInt((g=J.getAttribute("bandwidth"))!==null&&g!==void 0?g:"",10)/1e3,as=(E=J.getAttribute("frameRate"))!==null&&E!==void 0?E:"",Ir=($=J.getAttribute("quality"))!==null&&$!==void 0?$:void 0,Lr=as?Er(as):void 0,xr=(L=J.getAttribute("id"))!==null&&L!==void 0?L:(kr++).toString(10),Cr=Ke==="video"?`${ss}p`:Ke==="audio"?`${rs}Kbps`:Nt,Br=`${xr}@${Cr}`,Mr=(V=(Q=(G=J.querySelector("BaseURL"))===null||G===void 0?void 0:G.textContent)===null||Q===void 0?void 0:Q.trim())!==null&&V!==void 0?V:"",ns=new URL(Mr,e).toString(),Or=[...oi,...Dr,...di];let li;const Nr=J.querySelector("SegmentBase"),Fe=(q=J.querySelector("SegmentTemplate"))!==null&&q!==void 0?q:Rr;if(Nr){const Je=(B=(W=J.querySelector("SegmentBase Initialization"))===null||W===void 0?void 0:W.getAttribute("range"))!==null&&B!==void 0?B:"",[Xe,hi]=Je.split("-").map(Ze=>parseInt(Ze,10)),je={from:Xe,to:hi},ft=(M=J.querySelector("SegmentBase"))===null||M===void 0?void 0:M.getAttribute("indexRange"),[fi,Ft]=ft?ft.split("-").map(Ze=>parseInt(Ze,10)):[],pt=ft?{from:fi,to:Ft}:void 0;li={type:ut.BYTE_RANGE,url:ns,initRange:je,indexRange:pt}}else if(Fe){const Je={representationId:(K=J.getAttribute("id"))!==null&&K!==void 0?K:void 0,bandwidth:(O=J.getAttribute("bandwidth"))!==null&&O!==void 0?O:void 0},Xe=parseInt((x=Fe.getAttribute("timescale"))!==null&&x!==void 0?x:"",10),hi=(Y=Fe.getAttribute("initialization"))!==null&&Y!==void 0?Y:"",je=Fe.getAttribute("media"),ft=(fe=parseInt((te=Fe.getAttribute("startNumber"))!==null&&te!==void 0?te:"",10))!==null&&fe!==void 0?fe:1,fi=Oi(hi,Je);if(!je)throw new ReferenceError("No media attribute in SegmentTemplate");const Ft=(be=Fe.querySelectorAll("SegmentTimeline S"))!==null&&be!==void 0?be:[],pt=[];let Ze=0,pi="",et=0;if(Ft.length){let tt=ft,ke=0;for(const mt of Ft){const We=parseInt((Pe=mt.getAttribute("d"))!==null&&Pe!==void 0?Pe:"",10),Tt=parseInt((ze=mt.getAttribute("r"))!==null&&ze!==void 0?ze:"",10)||0,Ut=parseInt((rt=mt.getAttribute("t"))!==null&&rt!==void 0?rt:"",10);ke=Number.isFinite(Ut)?Ut:ke;const os=We/Xe*1e3,Di=ke/Xe*1e3;for(let Ri=0;Ri<Tt+1;Ri++){const iu=Oi(je,{...Je,segmentNumber:tt.toString(10),segmentTime:(ke+Ri*We).toString(10)}),mn=(Di!=null?Di:0)+Ri*os,su=mn+os;tt++,pt.push({time:{from:mn,to:su},url:iu})}ke+=(Tt+1)*We,Ze+=(Tt+1)*os}et=ke/Xe*1e3,pi=Oi(je,{...Je,segmentNumber:tt.toString(10),segmentTime:ke.toString(10)})}else if(D(Ne)){const ke=parseInt((ie=Fe.getAttribute("duration"))!==null&&ie!==void 0?ie:"",10)/Xe*1e3,mt=Math.ceil(Ne/ke);let We=0;for(let Tt=1;Tt<mt;Tt++){const Ut=Oi(je,{...Je,segmentNumber:Tt.toString(10),segmentTime:We.toString(10)});pt.push({time:{from:We,to:We+ke},url:Ut}),We+=ke}et=We,pi=Oi(je,{...Je,segmentNumber:mt.toString(10),segmentTime:We.toString(10)})}const mi={time:{from:et,to:1/0},url:pi};li={type:ut.TEMPLATE,baseUrl:ns,segmentTemplateUrl:je,initUrl:fi,totalSegmentsDurationMs:Ze,segments:pt,nextSegmentBeyondManifest:mi,timescale:Xe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ke||!Re)continue;const ci={video:Me.VIDEO,audio:Me.AUDIO,text:Me.TEXT}[Ke];ci&&De[ci].push({id:Br,kind:ci,segmentReference:li,profiles:Or,duration:Ne,bitrate:rs,mime:Re,codecs:Nt,width:ui,height:ss,fps:Lr,quality:Ir})}}return{dynamic:Xt,liveAvailabilityStartTime:Pi,duration:Ne,container:_r,representations:De}},qv=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a})=>{var n;const o=(n=a?Ki(a):void 0)!==null&&n!==void 0?n:si({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r}},jv=({id:s,bitrate:e})=>({id:s,bitrate:e}),Wv=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=Ie(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:Ie(s,-1)},Qv=({id:s,lang:e,url:t,isAuto:i})=>({id:s,url:t,isAuto:i,type:"internal",language:e}),Ao=s=>"size"in s,Bi=s=>s.type===ut.TEMPLATE,Ya=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);class wo{constructor(e,t,i,r,{fetcher:a,tuning:n,getCurrentPosition:o,isActiveLowLatency:u,compatibilityMode:d=!1,manifest:l}){switch(this.onLastSegment$=new T(!1),this.fullyBuffered$=new T(!1),this.playingRepresentation$=new T(void 0),this.playingRepresentationInit$=new T(void 0),this.error$=new C,this.gaps=[],this.subscription=new ue,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new lt,this.destroyAbortController=new lt,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.liveInitialAdditionalOffset=0,this.isSeekingLive=!1,this.index=0,this.startWith=ce(this.destroyAbortController.signal,async function*(c){const h=this.representations.get(c);P(h,`Cannot find representation ${c}`),this.playingRepresentationId=c,this.downloadingRepresentationId=c,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${h.mime}; codecs="${h.codecs}"`),this.sourceBufferTaskQueue=new uv(this.sourceBuffer),this.subscription.add(U(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},b=>this.error$.next({id:"SegmentEjection",category:R.WTF,message:"Error when trying to clear segments ejected by browser",thrown:b}))),this.subscription.add(U(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:R.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(b=>{if(!this.sourceBuffer)return;const v=Math.min(this.bufferLimit,ar(this.sourceBuffer.buffered)*.8);this.bufferLimit=v,this.pruneBuffer(this.getCurrentPosition(),b)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(b=>this.error$.next(b))),yield this.loadInit(h,"high",!0);const f=this.initData.get(h.id),m=this.segments.get(h.id),S=this.parsedInitData.get(h.id);P(f,"No init buffer for starting representation"),P(m,"No segments for starting representation"),f instanceof ArrayBuffer&&(this.searchGaps(m,h),yield this.sourceBufferTaskQueue.append(f,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(S))}.bind(this)),this.switchTo=ce(this.destroyAbortController.signal,async function*(c){if(c===this.downloadingRepresentationId||c===this.switchingToRepresentationId)return;this.switchingToRepresentationId=c;const h=this.representations.get(c);P(h,`No such representation ${c}`);let f=this.segments.get(c),m=this.initData.get(c);if(j(m)||j(f)?yield this.loadInit(h,"high",!1):m instanceof Promise&&(yield m),f=this.segments.get(c),P(f,"No segments for starting representation"),m=this.initData.get(c),!m||!(m instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=c,this.abort(),yield this.sourceBufferTaskQueue.append(m,this.downloadAbortController.signal);const S=this.getCurrentPosition();D(S)&&(this.isLive||(f.forEach(b=>b.status=Z.NONE),this.pruneBuffer(S,1/0,!0)),this.maintain(S))}.bind(this)),this.seekLive=ce(this.destroyAbortController.signal,async function*(c){var h;if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!c)return;for(const y of this.representations.keys()){const g=c.find(L=>L.id===y);g&&this.representations.set(y,g);const E=this.representations.get(y);if(!E||!Bi(E.segmentReference))return;const $=this.getActualLiveStartingSegments(E.segmentReference);this.segments.set(E.id,$)}const f=(h=this.switchingToRepresentationId)!==null&&h!==void 0?h:this.downloadingRepresentationId,m=this.representations.get(f);P(m);const S=this.segments.get(f);P(S,"No segments for starting representation");const b=this.initData.get(f);if(P(b,"No init buffer for starting representation"),!(b instanceof ArrayBuffer))return;const v=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),v&&(yield this.sourceBufferTaskQueue.remove(v.from*1e3,v.to*1e3,this.destroyAbortController.signal)),this.searchGaps(S,m),yield this.sourceBufferTaskQueue.append(b,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this)),this.fetcher=a,this.tuning=n,this.compatibilityMode=d,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=u,this.isLive=!!(l!=null&&l.dynamic),this.container=i,i){case qi.MP4:this.containerParser=Ov;break;case qi.WEBM:this.containerParser=Yv;break;default:z(i)}this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new lt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(j(e)||j(this.downloadingRepresentationId)||j(this.playingRepresentationId)||j(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(P(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const r=i.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const l=Qe(this.sourceBuffer.buffered,e),c=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&l>=r.time.to-e+100&&(a=c)}if(isFinite(this.bufferLimit)&&ar(this.sourceBuffer.buffered)>=this.bufferLimit){const d=Qe(this.sourceBuffer.buffered,e),l=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<l);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(i,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{const l=Ie(o,0);l&&l.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===Z.FED&&!o.length&&Qe(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const u=Ie(i,-1);u&&u.status===Z.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===u))}searchGaps(e,t){this.gaps=[];let i=0;const r=this.isLive?this.liveInitialAdditionalOffset:0;for(const a of e)Math.trunc(a.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from+r}),i=a.time.to;D(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[];let a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<i&&n>=0);return this.liveInitialAdditionalOffset=a-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(r=>r.id===this.downloadingRepresentationId);if(!t)return;const i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var t,i,r,a;for(const n of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!n||!Bi(n.segmentReference))return;const o=n.segmentReference.segments.map(c=>({...c,status:Z.NONE,size:void 0})),u=(i=this.segments.get(n.id))!==null&&i!==void 0?i:[],d=(a=(r=Ie(u,-1))===null||r===void 0?void 0:r.time.to)!==null&&a!==void 0?a:0,l=o==null?void 0:o.findIndex(c=>Math.floor(d)>=Math.floor(c.time.from)&&Math.floor(d)<=Math.floor(c.time.to));if(l===-1){this.liveUpdateSegmentIndex=0;const c=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,c)}else{const c=o.slice(l+1);this.segments.set(n.id,[...u,...c])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(const i of this.representations.values()){const r=i.segmentReference;if(!Bi(r))return;const a=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),n=Oi(r.segmentTemplateUrl,{segmentTime:a}),o=(t=this.segments.get(i.id))!==null&&t!==void 0?t:[],u=o.find(l=>Math.floor(l.time.from)===Math.floor(e.segment.time.from));u&&(u.time.to=e.segment.time.to),!!o.find(l=>Math.floor(l.time.from)===Math.floor(e.segment.time.to))||o.push({status:Z.NONE,time:{from:e.segment.time.to,to:1/0},url:n})}}findSegmentStartTime(e){var t,i,r;const a=(i=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&i!==void 0?i:this.playingRepresentationId;if(!a)return;const n=this.segments.get(a);if(!n)return;const o=n.find(u=>u.time.from<=e&&u.time.to>=e);return(r=o==null?void 0:o.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){const i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const r=e.findIndex(({status:c,time:{from:h,to:f}},m)=>{const S=h<=i&&f>=i,b=h>i||S||m===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&h<=i+v||f<=i+v;return(c===Z.NONE||c===Z.PARTIALLY_EJECTED&&b&&y&&this.sourceBuffer&&!Yi(this.sourceBuffer.buffered,i))&&b&&y});if(r===-1)return[];if(t!==ut.BYTE_RANGE)return e.slice(r,r+1);const a=e;let n=0,o=0;const u=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=d||o<=l);c++){const h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status===Z.NONE||h.status===Z.PARTIALLY_EJECTED)u.push(h);else break}return u}async loadSegments(e,t,i="auto"){t.segmentReference.type===ut.TEMPLATE?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){e.status=Z.DOWNLOADING;const r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);const{range:a,url:n,signal:o,onProgress:u,onProgressTasks:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await ce(o,async function*(){const l=ms(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,l))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{const l=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(!l)return;const c=new DataView(l);if(this.isActiveLowLatency()){const h=t.segmentReference.timescale;r.segment.time.to=this.containerParser.getSegmentEndTime(c,h)}u&&r.feedingBytes&&d?await Promise.all(d):await this.sourceBufferTaskQueue.append(c,o),r.segment.status=Z.DOWNLOADED,this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(l){if(!Ya(l))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(l)}}async loadByteRangeSegments(e,t,i="auto"){if(!e.length)return;for(const u of e)u.status=Z.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await ce(n,async function*(){const u=ms(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,u))}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.failedDownloads=0}catch(u){if(!Ya(u))return;this.abortActiveSegments(e),this.onSegmentDownloadError(u)}}prepareByteRangeFetchSegmentParams(e,t){if(Bi(t.segmentReference))throw new Error("Representation is not byte range type");const i=t.segmentReference.url,r={from:Ie(e,0).byte.from,to:Ie(e,-1).byte.to},{signal:a}=this.downloadAbortController,n=()=>{this.abort()};return{url:i,range:r,signal:a,onProgress:(u,d)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:u,loaded:d,signal:a,onSegmentAppendFailed:n,globalFrom:r?r.from:0,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:R.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Bi(t.segmentReference))throw new Error("Representation is not template type");const i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");const r=i.toString(),{signal:a}=this.downloadAbortController,n=()=>{this.abort()},o=[],d=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(l,c)=>{if(!a.aborted)try{const h=this.onSomeTemplateDataLoaded({dataView:l,loaded:c,signal:a,onSegmentAppendFailed:n,representationId:t.id});o.push(h)}catch(h){this.error$.next({id:"SegmentFeeding",category:R.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}}:void 0;return{url:r,signal:a,onProgress:d,onProgressTasks:o}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSegmentDownloadError(e){var t;let i=!1;const r=this.getCurrentPosition();this.sourceBuffer&&D(r)&&(i=Qe((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,i||this.error$.next({id:"SegmentDownload",category:R.NETWORK,message:"Error when fetching segments",thrown:e})}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const o of this.activeSegments){const{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=i,o.loadedBytes>o.feedingBytes){const d=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),l=this.containerParser.parseFeedableSegmentChunk(d);l!=null&&l.byteLength&&(u.status=Z.PARTIALLY_FED,o.feedingBytes+=l.byteLength,await this.sourceBufferTaskQueue.append(l),o.fedBytes+=l.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;const o=this.representations.get(t);if(!o)return;const u=o.segmentReference.type,d=e.byteLength;for(const l of this.activeSegments){const{segment:c}=l,h=u===ut.BYTE_RANGE,f=h?c.byte.to-c.byte.from+1:d;if(l.representationId!==t||!(!h||c.byte.from>=i&&c.byte.to<i+e.byteLength))continue;if(a.aborted){n();continue}const S=h?c.byte.from-i:0,b=h?c.byte.to-i:e.byteLength,v=S<r,y=b<=r;if(c.status===Z.DOWNLOADING&&v&&y){c.status=Z.DOWNLOADED;const g=new DataView(e.buffer,e.byteOffset+S,f);this.sourceBufferTaskQueue.append(g,a).then(E=>E&&!a.aborted?this.onSegmentFullyAppended(l,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&v&&(l.loadedBytes=Math.min(f,r-S),l.loadedBytes>l.feedingBytes)){const g=new DataView(e.buffer,e.byteOffset+S+l.feedingBytes,l.loadedBytes-l.feedingBytes),E=l.loadedBytes===f?g:this.containerParser.parseFeedableSegmentChunk(g);E!=null&&E.byteLength&&(c.status=Z.PARTIALLY_FED,l.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,a).then($=>{if(a.aborted)n();else if($)l.fedBytes+=E.byteLength,l.fedBytes===f&&this.onSegmentFullyAppended(l,t);else{if(l.feedingBytes<f)return;n()}}))}}}onSegmentFullyAppended(e,t){var i;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=Z.FED,Ao(e.segment)&&(e.segment.size=e.fedBytes);for(const r of this.representations.values())if(r.id!==t)for(const a of(i=this.segments.get(r.id))!==null&&i!==void 0?i:[])a.status===Z.FED&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status=Z.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===Z.PARTIALLY_FED||e.status===Z.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=Z.NONE),e.status=Z.PARTIALLY_EJECTED):e.status=Z.NONE;for(const i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,a]of this.initData.entries()){const n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=rr(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?ce(this.destroyAbortController.signal,async function*(){const o=ms(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(async o=>{if(!o)return;const{init:u,dataView:d,segments:l}=o,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c);let h=l;this.isLive&&Bi(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),u&&this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:R.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||j(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,n=-1/0,o=!1;const u=d=>{var l;a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const c=Ao(d)?(l=d.size)!==null&&l!==void 0?l:0:d.byte.to-d.byte.from;r+=c};for(const d of this.segments.values())for(const l of d){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;l.status===Z.FED&&u(l)}if(o=isFinite(a)&&isFinite(n),!o){r=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const l of d){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;l.status===Z.FED&&u(l)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const l=this.sourceBuffer.buffered.start(d)*1e3,c=this.sourceBuffer.buffered.end(d)*1e3;for(const h of this.segments.values())for(const f of h)if(f.status===Z.NONE&&Math.round(f.time.from)<=Math.round(l)&&Math.round(f.time.to)>=Math.round(c)){a=l,n=c;break}}if(o=isFinite(a)&&isFinite(n),!o&&i){r=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const l of this.segments.values())for(const c of l)c.time.from>e+d&&c.status===Z.FED&&u(c)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=i.time.from||n>=i.time.to)){if(n<=i.time.from&&o>=i.time.to){r=void 0;break}o>i.time.from&&o<i.time.to&&(r.from=o),n<i.time.to&&n>i.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=rr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:R.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(j(this.sourceBuffer)||j(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}const t=1;for(const i of this.segments.values())for(const r of i){const{status:a}=r;if(a!==Z.FED&&a!==Z.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(l=>l.from-t<=n&&l.to+t>=o),d=e.filter(l=>n>=l.from-t&&n<=l.to+t||o>=l.from-t&&o<=l.to+t);u||(d.length===1?r.status=Z.PARTIALLY_EJECTED:r.status=Z.NONE)}}}var Ui;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(Ui||(Ui={}));class Kv{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new T(void 0),this.lastConnectionReused$=new T(void 0),this.lastRequestFirstBytes$=new T(void 0),this.abortAllController=new lt,this.subscription=new ue,this.fetchManifest=ce(this.abortAllController.signal,async function*(r){let a=r;this.requestQuic&&(a=ii(a));const n=yield $i(a,{signal:this.abortAllController.signal}).catch(ls);return n?(this.onHeadersReceived(n.headers),n.text()):null}.bind(this)),this.fetch=ce(this.abortAllController.signal,async function*(r,{rangeMethod:a=this.compatibilityMode?Ui.HEADER:Ui.PARAM,range:n,onProgress:o,priority:u="auto",signal:d,measureThroughput:l=!0,isLowLatency:c=!1}={}){var h,f;let m=r;const S=new Headers;if(n)switch(a){case Ui.HEADER:{S.append("Range",`bytes=${n.from}-${n.to}`);break}case Ui.PARAM:{const M=new URL(m,location.href);M.searchParams.append("bytes",`${n.from}-${n.to}`),m=M.toString();break}default:z(a)}this.requestQuic&&(m=ii(m));let b=this.abortAllController.signal,v;if(d){const M=new lt;if(v=H(U(this.abortAllController.signal,"abort"),U(d,"abort")).subscribe(()=>{try{M.abort()}catch(K){ls(K)}}),this.abortAllController.signal.aborted||d.aborted)try{M.abort()}catch(K){ls(K)}b=M.signal}const y=le(),g=yield $i(m,{priority:u,headers:S,signal:b}).catch(ls),E=le();if(!g)return v==null||v.unsubscribe(),null;if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(E-y),!g.ok||!g.body)return v==null||v.unsubscribe(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`));if(this.onHeadersReceived(g.headers),!o&&!l)return v==null||v.unsubscribe(),g.arrayBuffer();const[$,L]=g.body.tee(),G=$.getReader();l&&((f=this.throughputEstimator)===null||f===void 0||f.trackStream(L,c));let Q=0,V=new Uint8Array(0),q=!1;const W=M=>{v==null||v.unsubscribe(),q=!0,ls(M)},B=ce(b,async function*({done:M,value:K}){if(Q===0&&this.lastRequestFirstBytes$.next(le()-y),b.aborted){v==null||v.unsubscribe();return}if(!M&&K){const O=new Uint8Array(V.length+K.length);O.set(V),O.set(K,V.length),V=O,Q+=K.byteLength,o==null||o(new DataView(V.buffer),Q),yield G==null?void 0:G.read().then(B,W)}}.bind(this));return yield G==null?void 0:G.read().then(B,W),v==null||v.unsubscribe(),q?null:V.buffer}.bind(this)),this.fetchByteRangeRepresentation=ce(this.abortAllController.signal,async function*(r,a,n){var o;if(r.type!==ut.BYTE_RANGE)return null;const{from:u,to:d}=r.initRange;let l=u,c=d,h=!1,f,m;r.indexRange&&(f=r.indexRange.from,m=r.indexRange.to,h=d+1===f,h&&(l=Math.min(f,u),c=Math.max(m,d))),l=Math.min(l,0);const S=yield this.fetch(r.url,{range:{from:l,to:c},priority:n,measureThroughput:!1});if(!S)return null;const b=new DataView(S,u-l,d-l+1);if(!a.validateData(b))throw new Error("Invalid media file");const v=a.parseInit(b),y=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(v);if(!y)throw new ReferenceError("No way to load representation index");let g;if(h)g=new DataView(S,y.from-l,y.to-y.from+1);else{const $=yield this.fetch(r.url,{range:y,priority:n,measureThroughput:!1});if(!$)return null;g=new DataView($)}const E=a.parseSegments(g,v,y);return{init:v,dataView:new DataView(S),segments:E}}.bind(this)),this.fetchTemplateRepresentation=ce(this.abortAllController.signal,async function*(r,a){if(r.type!==ut.TEMPLATE)return null;const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield this.fetch(n,{priority:a,measureThroughput:!1});return o?{init:null,segments:r.segments.map(d=>({...d,status:Z.NONE,size:void 0})),dataView:new DataView(o)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=cn(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var r,a;const{type:n}=e;switch(n){case ut.BYTE_RANGE:return(r=await this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case ut.TEMPLATE:return(a=await this.fetchTemplateRepresentation(e,i))!==null&&a!==void 0?a:null;default:z(n)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const ls=s=>{if(!Ya(s))throw s},za=1e3,cr=(s,e,t)=>t*e+(1-t)*s,Kd=(s,e)=>s.reduce((t,i)=>t+i,0)/e,Jv=(s,e,t,i)=>{let r=0,a=t;const n=Kd(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};class pn{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new T(e.initial),this.debounced$=new T(e.initial);const i=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new wt(`raw_${i}`),this.smoothedSeries$=new wt(`smoothed_${i}`),this.reportedSeries$=new wt(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(j(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class Xv extends pn{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=cr(this.slow,e,this.params.emaAlphaSlow),this.fast=cr(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Zv extends pn{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Kd(this.pastMeasures,this.takenMeasures);this.emaSmoothed=cr(this.emaSmoothed,e,this.params.emaAlpha);const i=Jv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class eS extends pn{constructor(e){super(e),this.furtherValues=[],this.currentTopExtremumValue=0,this.extremumInterval=e.extremumInterval}next(e){this.currentTopExtremumValue<=e?(this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.push(e)}updateSmoothedValue(e){this.smoothed=this.smoothed?cr(this.smoothed,e,this.params.emaAlpha):e}}class qa{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Xv({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Zv({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new eS({initial:e,label:"liveEdgeDelay",...t})}}const tS=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)},ko=["timeupdate","progress","play","seeked","stalled","waiting"];var ot;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(ot||(ot={}));let iS=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new ue,this.representationSubscription=new ue,this.state$=new he(ot.NONE),this.currentVideoRepresentation$=new T(void 0),this.currentVideoRepresentationInit$=new T(void 0),this.error$=new C,this.lastConnectionType$=new T(void 0),this.lastConnectionReused$=new T(void 0),this.lastRequestFirstBytes$=new T(void 0),this.isLive$=new T(!1),this.liveDuration$=new T(0),this.liveAvailabilityStartTime$=new T(void 0),this.bufferLength$=new T(0),this.liveLoadBufferLength$=new T(0),this.livePositionFromPlayer$=new T(0),this.isActiveLowLatency=!1,this.isUpdatingLive=!1,this.isJumpGapAfterSeekLive=!1,this.liveLastSeekOffset=0,this.forceEnded$=new C,this.gapWatchdogStarted=!1,this.destroyController=new lt,this.initManifest=ce(this.destroyController.signal,async function*(t,i,r){var a;this.element=t,this.manifestUrlString=He(i,r,Se.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(ot.MANIFEST_READY),this.manifest=yield this.updateManifest(),!((a=this.manifest)===null||a===void 0)&&a.representations.video.length?this.state$.setState(ot.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:R.PARSER,message:"No playable video representations"})}.bind(this)),this.updateManifest=ce(this.destroyController.signal,async function*(){var t;const i=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:R.NETWORK,message:"Failed to load manifest",thrown:n})});if(!i)return null;let r;try{r=zv(i!=null?i:"",this.manifestUrlString)}catch(n){this.error$.next({id:"ManifestParsing",category:R.PARSER,message:"Failed to parse MPD manifest",thrown:n})}if(!r)return null;const a=({kind:n,mime:o,codecs:u})=>{var d,l,c,h;return!!(!((l=(d=this.element)===null||d===void 0?void 0:d.canPlayType)===null||l===void 0)&&l.call(d,o)&&(!((h=(c=window.MediaSource)===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0)&&h.call(c,`${o}; codecs="${u}"`))||n===Me.TEXT)};return r.dynamic&&this.isLive$.getValue()!==r.dynamic&&(this.isLive$.next(r.dynamic),this.liveDuration$.getValue()!==r.duration&&this.liveDuration$.next(-1*((t=r.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==r.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(r.liveAvailabilityStartTime)),{...r,representations:Ei(Object.entries(r.representations).map(([n,o])=>[n,o.filter(a)]))}}.bind(this)),this.initRepresentations=ce(this.destroyController.signal,async function*(t,i){P(this.manifest),P(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(ot.REPRESENTATIOS_READY),window.ManagedMediaSource?(this.source=new ManagedMediaSource,this.element.disableRemotePlayback=!0):this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source),this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency,manifest:this.manifest};if(this.videoBufferManager=new wo(Me.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],D(i)&&(this.audioBufferManager=new wo(Me.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,r),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Ti(za).subscribe(o=>{var u;if(!((u=this.element)===null||u===void 0)&&u.paused){const d=er(this.manifestUrlString,Se.DASH_CMAF_OFFSET_P);this.manifestUrlString=He(this.manifestUrlString,d+za,Se.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(H(...ko.map(o=>U(this.element,o))).pipe(_(o=>this.element?Qe(this.element.buffered,this.element.currentTime*1e3):0),ve(),ae(o=>!!o),vs(o=>{this.waitingEventInterval&&(window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=void 0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(ae(u=>this.isActiveLowLatency&&!!u)).subscribe(u=>this.liveEstimatedDelay.next(u))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(u=>{if(!this.isActiveLowLatency)return;const d=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,l=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,c=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,h=u-d;let f=1+Math.sign(h)*c;Math.abs(h)<l?f=1:Math.abs(h)>l*2&&(f=1+Math.sign(h)*c*2),tS(this.element,f)})),this.representationSubscription.add(this.bufferLength$.subscribe(u=>{var d,l;let c=0;if(u){const h=((l=(d=this.element)===null||d===void 0?void 0:d.currentTime)!==null&&l!==void 0?l:0)*1e3;c=Math.min(...this.bufferManagers.map(m=>{var S,b;return(b=(S=m.getLiveSegmentsToLoadState(this.manifest))===null||S===void 0?void 0:S.to)!==null&&b!==void 0?b:0}))-h}c&&this.liveLoadBufferLength$.getValue()!==c&&this.liveLoadBufferLength$.next(c)}));let o=0;this.representationSubscription.add(Le({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).subscribe(async({liveLoadBufferLength:u,bufferLength:d})=>{if(P(this.element),this.isUpdatingLive)return;const l=this.element.playbackRate,c=er(this.manifestUrlString,Se.DASH_CMAF_OFFSET_P),h=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,f=Math.min(h,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*l),m=this.tuning.dashCmafLive.normalizedActualBufferOffset*l,S=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*l,b=this.isActiveLowLatency?d:u;let v=At.None;if(this.isActiveLowLatency?v=At.ActiveLowLatency:b<f+S&&b>=f?v=At.LiveWithTargetOffset:c!==0&&b<f&&(v=At.LiveForwardBuffering),isFinite(u)&&(o=u>o?u:o),v===At.LiveForwardBuffering||v===At.LiveWithTargetOffset){const y=o-(f+m),g=this.normolizeLiveOffset(Math.trunc(c+y/l)),E=Math.abs(g-c);let $;!u||E<=this.tuning.dashCmafLive.offsetCalculationError?$=c:g>0&&E>this.tuning.dashCmafLive.offsetCalculationError?$=g:$=0,this.manifestUrlString=He(this.manifestUrlString,$,Se.DASH_CMAF_OFFSET_P)}v!==At.None&&v!==At.ActiveLowLatency&&(o=0,this.updateLive())}))}const a=H(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(_(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=H(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(_(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.representationSubscription.add(H(this.forceEnded$,Le({allBuffersFull:a,someBufferEnded:n}).pipe(ae(({allBuffersFull:o,someBufferEnded:u})=>o&&u))).subscribe(()=>{var o;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(u=>!u.updating))try{(o=this.source)===null||o===void 0||o.endOfStream()}catch(u){this.error$.next({id:"EndOfStream",category:R.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:u})}})),this.representationSubscription.add(H(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield new Promise(o=>{var u;return(u=this.source)===null||u===void 0?void 0:u.addEventListener("sourceopen",o)})),D(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&D(i)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)]):yield this.videoBufferManager.startWith(t),this.state$.setState(ot.REPRESENTATIOS_READY)}.bind(this)),this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((i=this.audioBufferManager)===null||i===void 0)&&i.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=Ti(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:R.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Kv({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=qa.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){var t,i,r,a;P(this.element);const n=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&n===0,this.liveLastSeekOffset=n,this.isJumpGapAfterSeekLive=!0,this.manifestUrlString=He(this.manifestUrlString,n,Se.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),this.manifest&&(await((t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((i=this.manifest)===null||i===void 0?void 0:i.representations.video)),await((r=this.audioBufferManager)===null||r===void 0?void 0:r.seekLive((a=this.manifest)===null||a===void 0?void 0:a.representations.audio)))}initBuffer(){P(this.element),this.state$.setState(ot.RUNNING),this.subscription.add(H(...ko.map(e=>U(this.element,e)),U(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:R.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(U(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(U(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Yi(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime),this.waitingEventInterval&&window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=window.setInterval(this.waitingEventCallback.bind(this),this.tuning.dashMaxWaitingDuration)})),this.tick()}async switchRepresentation(e,t){const i={[Me.VIDEO]:this.videoBufferManager,[Me.AUDIO]:this.audioBufferManager,[Me.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)}seek(e,t){var i,r,a,n,o;P(this.element),P(this.videoBufferManager);let u;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?u=e:u=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!==null&&i!==void 0?i:e,(a=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&a!==void 0?a:e),Yi(this.element.buffered,u)||(this.videoBufferManager.abort(),(n=this.audioBufferManager)===null||n===void 0||n.abort()),this.videoBufferManager.maintain(u),(o=this.audioBufferManager)===null||o===void 0||o.maintain(u),this.element.currentTime=u/1e3}stop(){var e,t;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(e=this.videoBufferManager)===null||e===void 0||e.destroy(),this.videoBufferManager=null,(t=this.audioBufferManager)===null||t===void 0||t.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(ot.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),window.clearInterval(this.waitingEventInterval),this.stop(),((e=this.source)===null||e===void 0?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}async waitingEventCallback(){try{if(!this.element)return;this.isLive$.getValue()?await this.seekLive(this.liveLastSeekOffset):this.seek(this.element.currentTime*1e3,!0)}catch(e){this.error$.next({id:"WaitingEventCallback",category:R.WTF,message:"Error in seeking in waiting event callback",thrown:e})}}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)===null||e===void 0||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);const t=this.element.currentTime*1e3,i=[];for(const r of this.bufferManagers)for(const a of r.gaps)r.playingRepresentation$.getValue()===a.representation&&a.from<=t&&a.to>t&&(this.element.duration*1e3-a.to<this.tuning.endGapTolerance?i.push(1/0):i.push(a.to));if(i.length){const r=Math.max(...i);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):Math.trunc(this.element.currentTime*1e3)!==Math.trunc(r)&&(this.element.currentTime=r/1e3)}}};class Jd{constructor(e){this.subscription=new ue,this.videoState=new he(Ee.STOPPED),this.elementSize$=new T(void 0),this.textTracksManager=new yt,this.droppedFramesManager=new ks,this.videoTracks$=new T([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Id,this.textTracks=[],this.syncPlayback=()=>{var t,i,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(u.state===ee.Requested&&(o==null?void 0:o.to)!==p.PAUSED&&a!==Ee.STOPPED&&n!==p.STOPPED){const l=(i=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&i!==void 0?i:0;this.seek(u.position-l,u.forcePrecise)}if(n===p.STOPPED){a!==Ee.STOPPED&&(this.videoState.startTransitionTo(Ee.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Ee.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}switch(a){case Ee.STOPPED:this.videoState.startTransitionTo(Ee.READY),this.prepare();return;case Ee.READY:n===p.PAUSED?(this.videoState.setState(Ee.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING?(this.videoState.startTransitionTo(Ee.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.READY&&I(this.params.desiredState.playbackState,p.READY);return;case Ee.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(Ee.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case Ee.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(Ee.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return z(a)}}},this.init3DScene=t=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Yd(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=t.projectionData)===null||i===void 0?void 0:i.pose.yaw)||0,y:((r=t.projectionData)===null||r===void 0?void 0:r.pose.pitch)||0,z:((a=t.projectionData)===null||a===void 0?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const n=this.elementSize$.getValue();n&&this.scene3D.setViewportSize(n.width,n.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=Rt(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ye(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new iS({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=Lt(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:R.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(_(d=>d.map(({track:l})=>l)))}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(ae(D),Ae()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(ri(this.video,t.isLooped,r)),this.subscription.add(Dt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Qt(this.video,t.playbackRate,i.playbackRateState$,r)),a(ys(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(Ee.PLAYING),I(t.playbackState,p.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(Ee.PAUSED),I(t.playbackState,p.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===Ee.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d===ot.MANIFEST_READY){const c=[];this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();P(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((v,y)=>y.bitrate-v.bitrate),m=Array.from(h.video).sort((v,y)=>y.bitrate-v.bitrate),S=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const v of f){const y=jv(v);y&&this.audioTracks.push({track:y,representation:v})}for(const v of m){const y=qv(v);if(y){c.push({track:y,representation:v});const g=!this.params.tuning.isAudioDisabled&&Wv(f,m,v);g&&this.audioRepresentations.set(v.id,g)}}this.videoTracks$.next(c);for(const v of S){const y=Qv(v);y&&this.textTracks.push({track:y,representation:v})}this.params.output.availableVideoTracks$.next(c.map(({track:v})=>v)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:v})=>v)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:v})=>v));const b=this.selectVideoRepresentation();P(b),this.player.initRepresentations(b.id,(l=this.audioRepresentations.get(b.id))===null||l===void 0?void 0:l.id)}else d===ot.REPRESENTATIOS_READY&&(this.videoState.setState(Ee.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:R.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(H(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,U(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!==ot.RUNNING||l||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation(),h=this.params.desiredState.autoVideoTrackLimits.getTransition();if(h&&this.params.output.autoVideoTrackLimits$.next(h.to),c){this.player.switchRepresentation(Me.VIDEO,c.id).catch(n);const f=this.audioRepresentations.get(c.id);f&&this.player.switchRepresentation(Me.AUDIO,f.id).catch(n)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(ve(),_(d=>{var l;return d&&((l=this.videoTracks$.getValue().find(({representation:{id:c}})=>c===d))===null||l===void 0?void 0:l.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var l,c;if(d!=null&&d.is3dVideo&&(!((l=this.params.tuning.spherical)===null||l===void 0)&&l.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe(_(({to:d})=>d===p.READY),ve());this.subscription.add(H(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===p.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(H(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===p.READY)));const u=H(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ge(["init"])).pipe(st(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,i,r,a,n,o;const u=this.params.desiredState.autoVideoTrackSwitching.getState(),d=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id,l=(t=this.videoTracks$.getValue().find(({track:{id:y}})=>y===d))===null||t===void 0?void 0:t.track,c=this.params.output.currentVideoTrack$.getValue(),h=Qe(this.video.buffered,this.video.currentTime*1e3),f=u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=Math.min(h/Math.min(f,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),S=Math.max(l&&!u&&(r=(i=this.audioRepresentations.get(l.id))===null||i===void 0?void 0:i.bitrate)!==null&&r!==void 0?r:0,c&&(n=(a=this.audioRepresentations.get(c.id))===null||a===void 0?void 0:a.bitrate)!==null&&n!==void 0?n:0),b=_i(this.videoTracks$.getValue().map(({track:y})=>y),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:S,forwardBufferHealth:m,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),v=u?b!=null?b:l:l!=null?l:b;return v&&((o=this.videoTracks$.getValue().find(({track:y})=>y===v))===null||o===void 0?void 0:o.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Kt(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(Ee.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),It(this.video)}}class sS extends Jd{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}let rS=class extends zd{constructor(e){super(e),this.liveOffset=new ws}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(Le({interval:Ti(Ha),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()===Te.PLAYING){const n=e.position$.getValue()+(r-1);e.position$.next(n),(a=this.liveOffset)===null||a===void 0||a.resetTo(-n*1e3)}})).add(Le({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(_(({liveBufferTime:r,liveAvailabilityStartTime:a})=>r&&a?r+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t===p.PAUSED&&i===Te.PAUSED,a=-e,n=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)===null||o===void 0||o.resetTo(n,r)})}};class aS extends Jd{constructor(e){super(e),this.liveOffset=new ws}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(Le({interval:Ti(za),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()===Ee.PLAYING&&!this.player.isActiveLowLatency){const n=e.position$.getValue()+(r-1);e.position$.next(n),(a=this.liveOffset)===null||a===void 0||a.resetTo(-n*1e3)}})).add(Le({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(_(({liveBufferTime:r,liveAvailabilityStartTime:a})=>r&&a?r+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t===p.PAUSED&&i===Ee.PAUSED,a=-e,n=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)===null||o===void 0||o.resetTo(n,r)})}}const $t={};var de;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(de||(de={}));const cs=(s,e)=>new fr(t=>{const i=(r,a)=>t.next(a);return s.on(e,i),()=>s.off(e,i)});class nS{constructor(e){this.subscription=new ue,this.videoState=new he(de.INITIALIZING),this.textTracksManager=new yt,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(t!==de.INITIALIZING)switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===ee.Requested&&this.seek(a.position),i){case p.STOPPED:switch(t){case de.STOPPED:break;case de.READY:case de.PLAYING:case de.PAUSED:this.stop();break;default:z(t)}break;case p.READY:switch(t){case de.STOPPED:this.prepare();break;case de.READY:case de.PLAYING:case de.PAUSED:break;default:z(t)}break;case p.PLAYING:switch(t){case de.PLAYING:break;case de.STOPPED:this.prepare();break;case de.READY:case de.PAUSED:this.playIfAllowed();break;default:z(t)}break;case p.PAUSED:switch(t){case de.PAUSED:break;case de.STOPPED:this.prepare();break;case de.READY:this.videoState.setState(de.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED);break;case de.PLAYING:this.pause();break;default:z(t)}break;default:z(i)}},this.video=Rt(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ye(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)===null||e===void 0||e.detachMedia(),(t=this.hls)===null||t===void 0||t.destroy(),this.params.output.element$.next(void 0),It(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:R.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(r=>{e||($t.Hls=r.default,$t.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){P($t.Hls,"hls.js not loaded"),this.hls=new $t.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(de.STOPPED)}subscribe(){P($t.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:R.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=Lt(this.video),a=(d,l)=>this.subscription.add(d.subscribe(l,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(ri(this.video,e.isLooped,i)),this.subscription.add(Dt(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Qt(this.video,e.playbackRate,r.playbackRateState$,i)),this.subscription.add(cs(this.hls,$t.Events.ERROR).subscribe(d=>{var l;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:R.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${(l=d.err)===null||l===void 0?void 0:l.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(de.PLAYING),I(e.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED),I(e.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())===null||d===void 0?void 0:d.to)===de.READY&&this.videoState.setState(de.READY),this.videoState.getState()===de.PLAYING&&this.playIfAllowed()},i)),a(cs(this.hls,$t.Events.MANIFEST_PARSED).pipe(_(({levels:d})=>d.reduce((l,c)=>{var h,f;const m=c.name||c.height.toString(10),{width:S,height:b}=c,v=(f=Ki((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:si({width:S,height:b});if(!v)return l;const y=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,g={id:m.toString(),quality:v,bitrate:c.bitrate/1e3,size:{width:S,height:b},fps:y};return this.trackLevels.set(m,{track:g,level:c}),l.push(g),l},[]))),t.availableVideoTracks$),a(cs(this.hls,$t.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){const l=[];for(const c of d.subtitleTracks){const h=c.name,f=c.attrs.URI||"",m=c.lang,S="internal";l.push({id:h,url:f,language:m,type:S})}e.internalTextTracks.startTransitionTo(l)}}),a(cs(this.hls,$t.Events.LEVEL_LOADING).pipe(_(({url:d})=>Ye(d))),t.hostname$),this.subscription.add(vt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:i}));const n=d=>{var l;return(l=Array.from(this.trackLevels.values()).find(({level:c})=>c===d))===null||l===void 0?void 0:l.track},o=cs(this.hls,$t.Events.LEVEL_SWITCHED).pipe(_(({level:d})=>n(this.hls.levels[d])));o.pipe(ae(D)).subscribe(t.currentVideoTrack$,i),this.subscription.add(vt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),d=>{var l;if(j(d))return;const c=(l=this.trackLevels.get(d.id))===null||l===void 0?void 0:l.level;if(!c)return;const h=this.hls.levels.indexOf(c),f=this.hls.currentLevel,m=this.hls.levels[f];!m||c.bitrate>m.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o,onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const u=H(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Ge(["init"])).pipe(st(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(de.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(de.PLAYING),await Kt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:t}))||(this.videoState.setState(de.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))}pause(){this.videoState.startTransitionTo(de.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(de.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0)}}const _o="X-Playback-Duration";var Po=async s=>{var e;const t=await $i(s),i=await t.text(),r=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(i))===null||e===void 0?void 0:e[1];return r?parseInt(r,10):t.headers.has(_o)?parseInt(t.headers.get(_o),10):void 0};const oS=s=>{let e=null;if(s.QUALITY&&(e=Ki(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=si({width:t,height:i})}return e!=null?e:null},Xd=async(s,e=s)=>{var t,i;const n=(await(await $i(s)).text()).split(`
|
|
46
|
+
`),o=[],u=[];for(let d=0;d<n.length;d++){const l=n[d],c=l.match(/^#EXT-X-STREAM-INF:(.+)/),h=l.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!c&&!h)){if(c){const f=Ei(c[1].split(",").map(E=>E.split("="))),m=(t=f.QUALITY)!==null&&t!==void 0?t:`stream-${f.BANDWIDTH}`,S=oS(f);let b;f.BANDWIDTH&&(b=parseInt(f.BANDWIDTH,10)/1e3||void 0),!b&&f["AVERAGE-BANDWIDTH"]&&(b=parseInt(f["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const v=f["FRAME-RATE"]?parseFloat(f["FRAME-RATE"]):void 0;let y;if(f.RESOLUTION){const[E,$]=f.RESOLUTION.split("x").map(L=>parseInt(L,10));E&&$&&(y={width:E,height:$})}const g=new URL(n[++d],e).toString();S&&o.push({id:m,quality:S,url:g,bandwidth:b,size:y,fps:v})}if(h){const f=Ei(h[1].split(",").map(v=>v.split("=")).map(([v,y])=>[v,y.replace(/^"|"$/g,"")])),m=(i=f.URI)===null||i===void 0?void 0:i.replace(/playlist$/,"subtitles.vtt"),S=f.LANGUAGE,b=f.NAME;m&&S&&u.push({type:"internal",id:S,label:b,language:S,url:m,isAuto:!1})}}}return{qualityManifests:o,textTracks:u}};var pe;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(pe||(pe={}));class dS{constructor(e){var t;this.subscription=new ue,this.videoState=new he(pe.STOPPED),this.textTracksManager=new yt,this.manifests$=new T([]),this.liveOffset=new ws,this.manifestStartTime$=new T(void 0),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const r=this.videoState.getState(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition(),d=this.params.desiredState.autoVideoTrackLimits.getTransition();if(a===p.STOPPED){r!==pe.STOPPED&&(this.videoState.startTransitionTo(pe.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(pe.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(r===pe.STOPPED){this.videoState.startTransitionTo(pe.READY),this.prepare();return}if(o||u||d){const h=this.videoState.getState();this.videoState.setState(pe.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),d&&this.params.output.autoVideoTrackLimits$.next(d.to),c.state===ee.None&&this.params.desiredState.seekState.setState({state:ee.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==p.PAUSED&&c.state===ee.Requested){this.videoState.startTransitionTo(pe.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case pe.READY:a===p.READY?I(this.params.desiredState.playbackState,p.READY):a===p.PAUSED?(this.videoState.setState(pe.PAUSED),this.liveOffset.pause(),I(this.params.desiredState.playbackState,p.PAUSED)):a===p.PLAYING&&(this.videoState.startTransitionTo(pe.PLAYING),this.playIfAllowed());return;case pe.PLAYING:a===p.PAUSED?(this.videoState.startTransitionTo(pe.PAUSED),this.liveOffset.pause(),this.video.pause()):(n==null?void 0:n.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case pe.PAUSED:if(a===p.PLAYING)if(this.videoState.startTransitionTo(pe.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let h=this.liveOffset.getTotalOffset();h>=this.maxSeekBackTime$.getValue()&&(h=0,this.liveOffset.resetTo(h)),this.liveOffset.resume(),this.params.output.position$.next(-h/1e3),this.prepare()}else(n==null?void 0:n.to)===p.PAUSED&&(I(this.params.desiredState.playbackState,p.PAUSED),this.liveOffset.pause());return;case pe.CHANGING_MANIFEST:break;default:return z(r)}},this.params=e,this.video=Rt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:at.INVARIANT,url:this.params.source.url},Xd(He(this.params.source.url),this.params.source.url).then(({qualityManifests:i})=>{if(i.length===0){this.params.output.error$.next({id:"HlsLiveProviderInternal:partial_metadata",category:R.WTF,message:"HlsLiveProvider: there are no qualities in manifest"});return}this.manifests$.next([this.masterManifest,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:R.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ye(this.params.source.url)),this.maxSeekBackTime$=new T((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t,i,r;const{autoVideoTrackSwitching:a,videoTrack:n}=this.params.desiredState,o=a.getState(),u=n.getTransition(),d=(r=(t=(e=u==null?void 0:u.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(i=n.getState())===null||i===void 0?void 0:i.id)!==null&&r!==void 0?r:"master",l=this.manifests$.getValue();if(!l.length)return;const c=o?"master":d;return o&&!u&&n.startTransitionTo(this.masterManifest),l.find(h=>h.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:R.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Lt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Dt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Qt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(pe.PLAYING),I(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(pe.PAUSED),I(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===pe.READY&&this.videoState.setState(pe.READY),this.videoState.getState()===pe.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(ve(),_(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&D(d.to)){const c=d.to.id;this.params.desiredState.videoTrack.setState(d.to);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Ye(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===pe.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===ee.Requested&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var o,u,d;const l=(d=(u=(o=this.video)===null||o===void 0?void 0:o.getStartDate)===null||u===void 0?void 0:u.call(o))===null||d===void 0?void 0:d.getTime();this.manifestStartTime$.next(l||void 0)},i)),this.subscription.add(Le({startTime:this.manifestStartTime$.pipe(ae(D)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(_(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));const n=H(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ge(["init"])).pipe(st(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),It(this.video)}prepare(){var e,t;const i=this.selectManifest();if(j(i))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URL(i.url);if((r||a)&&i.id===this.masterManifest.id){const{max:d,min:l}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:a)!==null&&t!==void 0?t:{};for(const[c,h]of[[d,"mq"],[l,"lq"]]){const f=String(parseFloat(c||""));h&&c&&n.searchParams.set(h,f)}}const o=this.params.format===A.HLS_LIVE_CMAF?Se.DASH_CMAF_OFFSET_P:Se.OFFSET_P,u=He(n.toString(),this.liveOffset.getTotalOffset(),o);this.video.setAttribute("src",u),this.video.load(),Po(u).then(d=>{var l;if(!j(d))this.maxSeekBackTime$.next(d);else{const c=(l=this.params.source.maxSeekBackTime)!==null&&l!==void 0?l:this.maxSeekBackTime$.getValue();if(j(c)||!isFinite(c))try{$i(u).then(h=>h.text()).then(h=>{var f;const m=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))===null||f===void 0?void 0:f[1];if(m){const S=new URL(m,u).toString();Po(S).then(b=>{j(b)||this.maxSeekBackTime$.next(b)})}})}catch(h){}}})}playIfAllowed(){Kt(this.video).then(e=>{e||(this.videoState.setState(pe.PAUSED),this.liveOffset.pause(),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}var ge;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(ge||(ge={}));class uS{constructor(e){this.subscription=new ue,this.videoState=new he(ge.STOPPED),this.textTracksManager=new yt,this.manifests$=new T([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const i=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r===p.STOPPED){i!==ge.STOPPED&&(this.videoState.startTransitionTo(ge.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ge.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(i===ge.STOPPED){this.videoState.startTransitionTo(ge.READY),this.prepare();return}if(n||o||u){const c=this.videoState.getState();this.videoState.setState(ge.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state===ee.None&&this.params.desiredState.seekState.setState({state:ee.Requested,position:h*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==p.PAUSED&&l.state===ee.Requested&&this.seek(l.position),i){case ge.READY:r===p.READY?I(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(ge.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(ge.PLAYING),this.playIfAllowed());return;case ge.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(ge.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case ge.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(ge.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;case ge.CHANGING_MANIFEST:break;default:return z(i)}},this.params=e,this.video=Rt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:at.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ye(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Xd(this.params.source.url).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:R.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var e,t,i,r;const{autoVideoTrackSwitching:a,videoTrack:n}=this.params.desiredState,o=a.getState(),u=n.getTransition(),d=(r=(t=(e=u==null?void 0:u.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(i=n.getState())===null||i===void 0?void 0:i.id)!==null&&r!==void 0?r:"master",l=this.manifests$.getValue();if(!l.length)return;const c=o?"master":d;return o&&!u&&n.startTransitionTo(this.masterManifest),l.find(h=>h.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:R.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Lt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(ri(this.video,t.isLooped,i)),this.subscription.add(Dt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Qt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ge.PLAYING),I(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ge.PAUSED),I(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ge.READY&&this.videoState.setState(ge.READY),this.videoState.getState()===ge.PLAYING&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&D(d.to)){const c=d.to.id;this.params.desiredState.videoTrack.setState(d.to);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Ye(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===ge.CHANGING_MANIFEST&&this.videoState.setState(u.to),o.state===ee.Requested&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(_(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!lu()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:o}=this.video;this.subscription.add(H(U(o,"addtrack"),U(o,"removetrack"),U(o,"change"),Ge(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}const n=H(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Ge(["init"])).pipe(st(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),It(this.video)}prepare(){var e,t;const i=this.selectManifest();if(j(i))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URL(i.url);if((r||a)&&i.id===this.masterManifest.id){const{max:o,min:u}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:a)!==null&&t!==void 0?t:{};for(const[d,l]of[[o,"mq"],[u,"lq"]]){const c=String(parseFloat(d||""));l&&d&&n.searchParams.set(l,c)}}this.video.setAttribute("src",n.toString()),this.video.load()}playIfAllowed(){Kt(this.video).then(e=>{e||(this.videoState.setState(ge.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var $e;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})($e||($e={}));class lS{constructor(e){this.subscription=new ue,this.videoState=new he($e.STOPPED),this.trackUrls={},this.textTracksManager=new yt,this.syncPlayback=()=>{var t,i,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition();if(n===p.STOPPED){a!==$e.STOPPED&&(this.videoState.startTransitionTo($e.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState($e.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.autoVideoTrackLimits.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.seekState.getState();if(d&&a!==$e.READY&&!l){this.handleQualityLimitTransition(d.to.max);return}if(a===$e.STOPPED){this.videoState.startTransitionTo($e.READY),this.prepare();return}if(l){const{currentTime:h}=this.video;this.prepare(),c.state===ee.None&&this.params.desiredState.seekState.setState({state:ee.Requested,position:h*1e3,forcePrecise:!0}),l.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((r=(i=this.trackUrls[l.to.id])===null||i===void 0?void 0:i.track)===null||r===void 0?void 0:r.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((o==null?void 0:o.to)!==p.PAUSED&&c.state===ee.Requested&&this.seek(c.position),a){case $e.READY:n===p.READY?I(this.params.desiredState.playbackState,p.READY):n===p.PAUSED?(this.videoState.setState($e.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING&&(this.videoState.startTransitionTo($e.PLAYING),this.playIfAllowed());return;case $e.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo($e.PAUSED),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case $e.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo($e.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return z(a)}},this.params=e,this.video=Rt(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{const a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:R.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Lt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(ri(this.video,t.isLooped,i)),this.subscription.add(Dt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Qt(this.video,t.playbackRate,r.playbackRateState$,i)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState($e.PLAYING),I(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState($e.PAUSED),I(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===$e.READY&&this.videoState.setState($e.READY);const u=this.params.desiredState.videoTrack.getTransition();u&&D(u.to)&&(this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to.id].track)),this.videoState.getState()===$e.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const n=H(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Ge(["init"])).pipe(st(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),It(this.video)}prepare(){var e;const t=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id;P(t,"MpegProvider: track is not selected");let{url:i}=this.trackUrls[t];P(i,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(i=ii(i)),this.video.setAttribute("src",i),this.video.load(),this.params.output.hostname$.next(Ye(i))}playIfAllowed(){Kt(this.video).then(e=>{e||(this.videoState.setState($e.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,i,r,a;let n,o=e;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const u=(i=Object.values(this.trackUrls).find(c=>!yi(c.track.quality)&&Fo(c.track.quality,e)))===null||i===void 0?void 0:i.track,d=(r=this.params.desiredState.videoTrack.getState())===null||r===void 0?void 0:r.id,l=(a=this.trackUrls[d!=null?d:"0"])===null||a===void 0?void 0:a.track;if(u&&l&&Ra(l.quality,u.quality)&&(n=u),!n){const c=Object.values(this.trackUrls).filter(f=>!yi(f.track.quality)&&Vi(f.track.quality,e)),h=c.length;h&&(n=c[h-1].track)}n&&(o=n.quality)}else if(!e){const u=Object.values(this.trackUrls).map(d=>d.track);n=_i(u,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}n&&(this.params.output.currentVideoTrack$.next(n),this.params.desiredState.videoTrack.startTransitionTo(n)),this.params.output.autoVideoTrackLimits$.next({max:o})}}const Do=["stun:videostun.mycdn.me:80"],cS=1e3,hS=3,ma=()=>null;class fS{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=ma,this.externalStopCallback=ma,this.externalErrorCallback=ma,this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:Do}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:R.WTF,message:e.message})}async onPeerConnectionStream(e){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),cS)}normalizeOptions(e={}){const t={stunServerList:Do,maxRetryNumber:hS,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var me;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(me||(me={}));class pS{constructor(e){this.videoState=new he(me.STOPPED),this.maxSeekBackTime$=new T(0),this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(i===p.STOPPED){t!==me.STOPPED&&(this.videoState.startTransitionTo(me.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(me.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===me.STOPPED){this.videoState.startTransitionTo(me.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case me.READY:i===p.PAUSED?(this.videoState.setState(me.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):i===p.PLAYING&&(this.videoState.startTransitionTo(me.PLAYING),this.playIfAllowed());return;case me.PLAYING:i===p.PAUSED?(this.videoState.startTransitionTo(me.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case me.PAUSED:i===p.PLAYING?(this.videoState.startTransitionTo(me.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return z(t)}},this.subscription=new ue,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Rt(e.container),this.liveStreamClient=new fS(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),It(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:R.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};H(this.videoState.stateChangeStarted$.pipe(_(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(_(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const r=Lt(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())===null||n===void 0?void 0:n.to)===me.READY&&this.videoState.setState(me.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(me.PAUSED)},i)).add(r.playing$.subscribe(()=>{this.videoState.setState(me.PLAYING)},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Dt(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case me.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(p.STOPPED);break;case me.READY:break;case me.PAUSED:t.playbackState.setState(p.PAUSED);break;case me.PLAYING:t.playbackState.setState(p.PLAYING);break;default:return z(n.to)}},i)).add(H(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Ge(["init"])).pipe(st(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Ye(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:at.INVARIANT}),this.video.srcObject=e,I(this.params.desiredState.playbackState,p.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(me.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:R.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Kt(this.video).then(e=>{e||(this.videoState.setState(me.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class Ro{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}}var ga,va,Sa,ba,ya,Ta,Ea,$a,Us,Aa,Vs,wa,Hs,ka,Gs,_a,Ys,Pa,zs,Da;const Zd=hr().device===cu.Android,ti=document.createElement("video"),mS='video/mp4; codecs="avc1.42000a,mp4a.40.2"',gS='video/mp4; codecs="hev1.1.6.L93.B0"',eu='video/webm; codecs="vp09.00.10.08"',tu='video/webm; codecs="av01.0.00M.08"',vS='audio/mp4; codecs="mp4a.40.2"',SS='audio/webm; codecs="opus"',xe={mms:!!(window.ManagedMediaSource&&(!((va=(ga=window.ManagedSourceBuffer)===null||ga===void 0?void 0:ga.prototype)===null||va===void 0)&&va.appendBuffer)),mse:!!(window.MediaSource&&window.MediaStreamTrack&&(!((ba=(Sa=window.SourceBuffer)===null||Sa===void 0?void 0:Sa.prototype)===null||ba===void 0)&&ba.appendBuffer)),hls:!!(!((ya=ti.canPlayType)===null||ya===void 0)&&ya.call(ti,"application/x-mpegurl")||!((Ta=ti.canPlayType)===null||Ta===void 0)&&Ta.call(ti,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},it={mp4:!!(!((Ea=ti.canPlayType)===null||Ea===void 0)&&Ea.call(ti,"video/mp4")),webm:!!(!(($a=ti.canPlayType)===null||$a===void 0)&&$a.call(ti,"video/webm")),cmaf:!0},Pt={h264:!!(!((Aa=(Us=window.MediaSource||window.ManagedMediaSource)===null||Us===void 0?void 0:Us.isTypeSupported)===null||Aa===void 0)&&Aa.call(Us,mS)),h265:!!(!((wa=(Vs=window.MediaSource||window.ManagedMediaSource)===null||Vs===void 0?void 0:Vs.isTypeSupported)===null||wa===void 0)&&wa.call(Vs,gS)),vp9:!!(!((ka=(Hs=window.MediaSource||window.ManagedMediaSource)===null||Hs===void 0?void 0:Hs.isTypeSupported)===null||ka===void 0)&&ka.call(Hs,eu)),av1:!!(!((_a=(Gs=window.MediaSource||window.ManagedMediaSource)===null||Gs===void 0?void 0:Gs.isTypeSupported)===null||_a===void 0)&&_a.call(Gs,tu)),aac:!!(!((Pa=(Ys=window.MediaSource||window.ManagedMediaSource)===null||Ys===void 0?void 0:Ys.isTypeSupported)===null||Pa===void 0)&&Pa.call(Ys,vS)),opus:!!(!((Da=(zs=window.MediaSource||window.ManagedMediaSource)===null||zs===void 0?void 0:zs.isTypeSupported)===null||Da===void 0)&&Da.call(zs,SS))},Mi=(Pt.h264||Pt.h265)&&Pt.aac;var ei;(function(s){s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient"})(ei||(ei={}));var Gt;(function(s){s.DASH="dash",s.HLS="hls",s.MPEG="mpeg"})(Gt||(Gt={}));let gi;const bS=async()=>{if(!window.navigator.mediaCapabilities)return;const s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:tu}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:eu}})]);gi={[A.DASH_WEBM_AV1]:e,[A.DASH_WEBM]:t}};try{bS()}catch(s){console.error(s)}const Ts=xe.hls&&it.mp4,yS=()=>Object.keys(Pt).filter(s=>Pt[s]),TS=(s,e=!1,t=!1)=>s.filter(i=>{switch(i){case A.DASH:return xe.mse&&it.mp4&&Mi;case A.DASH_SEP:return(xe.mse||xe.mms&&t)&&it.mp4&&Mi;case A.DASH_WEBM:return(xe.mse||xe.mms&&t)&&it.webm&&Pt.vp9&&Pt.opus;case A.DASH_WEBM_AV1:return(xe.mse||xe.mms&&t)&&it.webm&&Pt.av1&&Pt.opus;case A.DASH_LIVE:return xe.mse&&it.mp4&&Mi;case A.DASH_LIVE_CMAF:return(xe.mse||xe.mms&&t)&&it.mp4&&Mi&&it.cmaf;case A.DASH_ONDEMAND:return(xe.mse||xe.mms&&t)&&it.mp4&&Mi;case A.HLS:case A.HLS_ONDEMAND:return Ts||e&&xe.mse&&it.mp4&&Mi;case A.HLS_LIVE:case A.HLS_LIVE_CMAF:return Ts;case A.MPEG:return it.mp4;case A.DASH_LIVE_WEBM:return!1;case A.WEB_RTC_LIVE:return xe.webrtc&&xe.ws&&Pt.h264&&(it.mp4||it.webm);default:return z(i)}}),hs=s=>{const e=A.DASH_WEBM,t=A.DASH_WEBM_AV1;switch(s){case ei.VP9:return[e,t];case ei.AV1:return[t,e];case ei.NONE:return[];case ei.SMOOTH:return gi?gi[t].smooth?[t,e]:gi[e].smooth?[e,t]:[t,e]:[e,t];case ei.POWER_EFFICIENT:return gi?gi[t].powerEfficient?[t,e]:gi[e].powerEfficient?[e,t]:[t,e]:[e,t];default:z(s)}return[e,t]},ES=({webmCodec:s,androidPreferredFormat:e})=>{if(Zd)switch(e){case Gt.MPEG:return[A.MPEG,...hs(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND];case Gt.HLS:return[A.HLS,A.HLS_ONDEMAND,...hs(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.MPEG];case Gt.DASH:return[...hs(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG]}return Ts?[...hs(s),A.DASH_SEP,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG,A.DASH]:[...hs(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG]},$S=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{const i=e?[A.DASH_LIVE_CMAF,A.DASH_LIVE]:[A.DASH_LIVE,A.DASH_LIVE_CMAF],r=e?[A.HLS_LIVE_CMAF,A.HLS_LIVE]:[A.HLS_LIVE,A.HLS_LIVE_CMAF],a=[...i,...r],n=[...r,...i];let o;if(Zd)switch(s){case Gt.DASH:{o=a;break}case Gt.HLS:case Gt.MPEG:{o=n;break}}else Ts?o=n:o=a;return t?[A.WEB_RTC_LIVE,...o]:[...o,A.WEB_RTC_LIVE]},Io=s=>s?[A.HLS_LIVE,A.HLS_LIVE_CMAF,A.DASH_LIVE_CMAF]:[A.DASH_WEBM,A.DASH_WEBM_AV1,A.DASH_SEP,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG];var AS=s=>new fr(e=>{const t=new ue,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(_(({from:d,to:l})=>`${d}-${l}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(_(({type:d})=>d!==void 0)),n=new C;let o=0,u="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>n.next(d),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const wS={cacheDuration:12e4},kS={chunkDuration:5e3,maxParallelRequests:5};class _S{constructor(e){this.current$=new T({type:void 0}),this.providerError$=new C,this.noAvailableProvidersError$=new C,this.providerOutput={position$:new T(0),duration$:new T(1/0),volume$:new T({muted:!1,volume:1}),currentVideoTrack$:new T(void 0),availableVideoTracks$:new T([]),availableAudioTracks$:new T([]),isAudioAvailable$:new T(!0),autoVideoTrackLimitingAvailable$:new T(!1),autoVideoTrackLimits$:new T(void 0),currentBuffer$:new T(void 0),isBuffering$:new T(!0),error$:new C,warning$:new C,willSeekEvent$:new C,seekedEvent$:new C,loopedEvent$:new C,endedEvent$:new C,firstBytesEvent$:new C,firstFrameEvent$:new C,canplay$:new C,isLive$:new T(void 0),isLowLatency$:new T(!1),canChangePlaybackSpeed$:new T(!0),liveTime$:new T(void 0),liveBufferTime$:new T(void 0),availableTextTracks$:new T([]),currentTextTrack$:new T(void 0),hostname$:new T(void 0),httpConnectionType$:new T(void 0),httpConnectionReused$:new T(void 0),inPiP$:new T(!1),inFullscreen$:new T(!1),element$:new T(void 0),availableSources$:new T(void 0),is3DVideo$:new T(!1)},this.subscription=new ue,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=TS([...$S(this.params.tuning),...ES(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>D(e.sources[o])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning;let a=[];i?a=[i]:r.length?a=[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new Ro(a),console.log("this.params.tuning.useManagedMediaSource "+this.params.tuning.useManagedMediaSource),console.log(a);const n=[...Io(!0),...Io(!1)];this.chromecastFormatsIterator=new Ro(n.filter(o=>D(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(console.log("Choose provider "+t),j(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:R.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!==ee.None;if(this.params.desiredState.seekState.setState({state:ee.Requested,position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){const n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case Ue.SCREEN:return this.createScreenProvider(t);case Ue.CHROMECAST:return this.createChromecastProvider(t);default:return z(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:r}=this.params,a=this.providerOutput,n={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(console.log("Creating provider "+e),e){case A.DASH:{const o=this.applyFailoverHost(t[e]);return P(o),new _m({...n,source:o,config:wS})}case A.DASH_SEP:case A.DASH_WEBM:case A.DASH_WEBM_AV1:case A.DASH_ONDEMAND:{console.log("Inside CASE DASH_SEP");const o=this.applyFailoverHost(t[e]);return P(o),this.params.tuning.useDashJs?new lo({...n,source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):this.params.tuning.useNewDashVkProvider?(console.log("WE ARE IN A RIGHT PLACE"),new sS({...n,source:o})):new dv({...n,source:o})}case A.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),this.params.tuning.useDashJsCMAF?new lo({...n,source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):this.params.tuning.useNewDashVkProvider?new aS({...n,source:o}):new rS({...n,source:o})}case A.HLS:case A.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),Ts||!this.params.tuning.useHlsJs?new uS({...n,source:o}):new nS({...n,source:o})}case A.HLS_LIVE:case A.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new dS({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case A.MPEG:{const o=this.applyFailoverHost(t[e]);return P(o),new lS({...n,source:o})}case A.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new Em({...n,source:o,config:{...kS,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case A.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new pS({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case A.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return z(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return P(o),new Lp({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?Ue.CHROMECAST:Ue.SCREEN}chooseFormat(e){switch(e){case Ue.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case Ue.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return z(e)}}skipFormat(e){switch(e){case Ue.SCREEN:return this.screenFormatsIterator.next();case Ue.CHROMECAST:return this.chromecastFormatsIterator.next();default:return z(e)}}handleNoFormatsError(e){switch(e){case Ue.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case Ue.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return z(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=r=>{const a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return Ei(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){const e=new ue;let t=!1,i=0;const r=le();return e.add(H(this.providerOutput.error$,AS({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(_(a=>({id:`ProviderHangup:${a}`,category:R.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const a=this.params.desiredState.playbackState.transitionEnded$.pipe(ae(({to:n})=>n===p.PLAYING),Ae()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{const n=this.current$.getValue().destination;if(n===Ue.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(Ue.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const o=a.category===R.NETWORK,u=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit,l=u&&(o&&t||!d),c=a.id.includes("partial_metadata"),h=le()-r;l?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):c&&h<=this.params.tuning.providerRefetchManifestMaxTime?this.reinitProvider():d?(i++,this.reinitProvider()):this.switchToNextProvider(n!=null?n:Ue.SCREEN)}})),e}}const PS=5e3,Lo="one_video_throughput",xo="one_video_rtt",Yt=window.navigator.connection,Co=()=>{const s=Yt==null?void 0:Yt.downlink;if(D(s)&&s!==10)return s*1e3},Bo=()=>{const s=Yt==null?void 0:Yt.rtt;if(D(s)&&s!==3e3)return s},Mo=(s,e,t)=>{const i=t*8,r=i/s;return i/(r+e)};class gs{constructor(e){var t,i;this.subscription=new ue,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=gs.load(Lo)||(e.useBrowserEstimation?Co():void 0)||PS,a=(i=(t=gs.load(xo))!==null&&t!==void 0?t:e.useBrowserEstimation?Bo():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new T(r),this.rtt$=new T(a),this.rttAdjustedThroughput$=new T(Mo(r,a,e.rttPenaltyRequestSize)),this.throughput=qa.getSmoothedValue(r,-1,e),this.rtt=qa.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const u=Co();u&&this.throughput.next(u);const d=Bo();D(d)&&this.rtt.next(d)};Yt&&"onchange"in Yt&&this.subscription.add(U(Yt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Fr.set(Lo,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Fr.set(xo,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Le({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(_(({throughput:n,rtt:o})=>Mo(n,o,e.rttPenaltyRequestSize)),ae(n=>{const o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=le();const r=new ue;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(U(e,"progress").pipe(Ae()).subscribe(a=>{t=a.loaded,i=le()}));break;case 1:case 0:r.add(U(e,"loadstart").subscribe(()=>{t=0,i=le()}));break}r.add(U(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=le(),u=n-t,d=o-i;this.addRawSpeed(u,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){const i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,a=le(),n=0,o=le();const u=l=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${l}`).catch(()=>{})},d=async({done:l,value:c})=>{if(l)!t&&this.addRawSpeed(r,le()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){if(le()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=c.byteLength;else{const f=o-a;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,a=le()}o=le()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&le()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,le()-o,this.concurrentDownloads.size),n=0,o=le());await(i==null?void 0:i.read().then(d,u))}};this.concurrentDownloads.add(e),i==null||i.read().then(d,u)}addRawSpeed(e,t,i=1,r=!1){if(gs.sanityCheck(e,t,r)){const a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){const r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var t;const i=Fr.get(e);if(D(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const Oo={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:at.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:ei.VP9,androidPreferredFormat:Gt.MPEG,preferCMAF:!0,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,dashMaxWaitingDuration:5e3,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useDashJsCMAF:!1,useNewDashVkProvider:!0,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,providerRefetchManifestMaxTime:1e4,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},DS=s=>{var e;return{...hu(s,Oo),configName:[...(e=s.configName)!==null&&e!==void 0?e:[],...Oo.configName]}};var No=({seekState:s,position$:e})=>H(s.stateChangeEnded$.pipe(_(({to:t})=>{var i;return t.state===ee.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),ae(D)),e.pipe(ae(()=>s.getState().state===ee.None))),RS=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return P(e,`Wrong container or containerId {${s.container}}`),e};const IS=(s,e,t,i)=>{s!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(ae(r=>r.length>0),Ae()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};class nb{constructor(e={configName:[]}){if(this.subscription=new ue,this.logger=new fu,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.desiredState={playbackState:new he(p.STOPPED),seekState:new he({state:ee.None}),volume:new he({volume:1,muted:!1}),videoTrack:new he(void 0),autoVideoTrackSwitching:new he(!0),autoVideoTrackLimits:new he({}),isLooped:new he(!1),playbackRate:new he(1),externalTextTracks:new he([]),internalTextTracks:new he([]),currentTextTrack:new he(void 0),textTrackCuesSettings:new he({}),cameraOrientation:new he({x:0,y:0})},this.info={playbackState$:new T(p.STOPPED),position$:new T(0),duration$:new T(1/0),muted$:new T(!1),volume$:new T(1),availableQualities$:new T([]),availableQualitiesFps$:new T({}),availableAudioTracks$:new T([]),isAudioAvailable$:new T(!0),currentQuality$:new T(void 0),isAutoQualityEnabled$:new T(!0),autoQualityLimitingAvailable$:new T(!1),autoQualityLimits$:new T({}),currentPlaybackRate$:new T(1),currentBuffer$:new T({start:0,end:0}),isBuffering$:new T(!0),isStalled$:new T(!1),isEnded$:new T(!1),isLooped$:new T(!1),isLive$:new T(void 0),canChangePlaybackSpeed$:new T(void 0),atLiveEdge$:new T(void 0),atLiveDurationEdge$:new T(void 0),liveTime$:new T(void 0),liveBufferTime$:new T(void 0),currentFormat$:new T(void 0),availableTextTracks$:new T([]),currentTextTrack$:new T(void 0),throughputEstimation$:new T(void 0),rttEstimation$:new T(void 0),videoBitrate$:new T(void 0),hostname$:new T(void 0),httpConnectionType$:new T(void 0),httpConnectionReused$:new T(void 0),surface$:new T(Zt.NONE),chromecastState$:new T(Ce.NOT_AVAILABLE),chromecastDeviceName$:new T(void 0),intrinsicVideoSize$:new T(void 0),availableSources$:new T(void 0),is3DVideo$:new T(!1)},this.events={inited$:new C,ready$:new C,started$:new C,playing$:new C,paused$:new C,stopped$:new C,willStart$:new C,willResume$:new C,willPause$:new C,willStop$:new C,willDestruct$:new C,watchCoverageRecord$:new C,watchCoverageLive$:new C,managedError$:new C,fatalError$:new C,ended$:new C,looped$:new C,seeked$:new C,willSeek$:new C,firstBytes$:new C,firstFrame$:new C,canplay$:new C,log$:new C},this.experimental={element$:new T(void 0),tuningConfigName$:new T([]),enableDebugTelemetry$:new T(!1),dumpTelemetry:im},this.initLogs(),this.tuning=DS(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new gu({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new gs(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{const a=Reflect.get(t,i,r);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const u=n.map(c=>JSON.stringify(c,(h,f)=>{const m=typeof f;return["number","string","boolean"].includes(m)?f:f===null?null:`<${m}>`})),d=`Player.${String(i)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:R.WTF,message:l,thrown:o}),o}}}})}initVideo(e){var t,i,r;return this.config=e,this.domContainer=RS(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new _S({sources:e.sources,meta:(i=e.meta)!==null&&i!==void 0?i:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===p.STOPPED&&e.startTransitionTo(p.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==p.PLAYING&&t.startTransitionTo(p.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?U(document,"visibilitychange").pipe(Ae()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==p.PAUSED&&e.startTransitionTo(p.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==p.STOPPED&&e.startTransitionTo(p.STOPPED),this}seekTime(e,t=!0){const i=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=i&&!r&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:ee.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===Ce.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===Ce.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){P(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(ae(i=>i.length>0),Ae()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var t;P(this.providerContainer);const i=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return i&&(this.desiredState.playbackRate.setState(e),i.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return IS(e,this.desiredState.currentTextTrack,(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){const i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const i=this.getScene3D();if(i){const r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;const e=this.providerContainer.providerOutput.element$.getValue();if(j(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===ee.None?void 0:t.position;return D(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const i=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=i==null?void 0:i.provider)===null||t===void 0)&&t.scene3D)return i.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(H(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(_(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(_(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ae(({from:e})=>e===p.STOPPED),Ae()).subscribe(()=>{this.initedAt=le(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case p.READY:this.events.ready$.next();break;case p.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case p.PAUSED:this.events.paused$.next();break;case p.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case p.PAUSED:this.events.willPause$.next();break;case p.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case p.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===ee.Requested?this.desiredState.seekState.setState({...n,state:ee.Applying}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:R.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===ee.Applying&&(this.desiredState.seekState.setState({state:ee.None}),this.events.seeked$.next())})).add(e.current$.pipe(_(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(_(n=>n.destination),ve()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(_(n=>n.map(({quality:o})=>o).sort((o,u)=>yi(o)?1:yi(u)?-1:Vi(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{const o={};for(const u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.hostname$.pipe(ve()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(ve()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(ve()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(_(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(Le({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:No({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(_(({isLive:n,position:o,isLowLatency:u})=>{const d=u?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return n&&Math.abs(o)<d/1e3}),ve(),vs(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(Le({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(_(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),ve(),vs(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(_(n=>n.muted),ve()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(_(n=>n.volume),ve()).subscribe(this.info.volume$)).add(No({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(H(e.providerOutput.endedEvent$.pipe(Hi(!0)),e.providerOutput.seekedEvent$.pipe(Hi(!1))).pipe(ve()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(_(n=>({id:n?`No${n}`:"NoProviders",category:R.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(Ae(),_(n=>n!=null?n:le()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(Ae(),_(()=>le()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Ae(),_(()=>le()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new T(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new T(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ae(({to:n})=>n===p.PLAYING),Ae()).subscribe(()=>i.next(!1)));let r=0;const a=H(e.providerOutput.isBuffering$,t,i).pipe(_(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),ve());this.subscription.add(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(H(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var o,u;const d=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(o=n==null?void 0:n.size)===null||o===void 0?void 0:o.width,height:(u=n==null?void 0:n.size)===null||u===void 0?void 0:u.height},{width:d==null?void 0:d.videoWidth,height:d==null?void 0:d.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(H(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),d=this.chromecastInitializer.castState$.getValue();let l;d===Ce.CONNECTED?l=Zt.SECOND_SCREEN:u?n?l=Zt.PIP:o?l=Zt.FULLSCREEN:l=Zt.INLINE:l=Zt.NONE,this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(_(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new ue;this.subscription.add(t),this.subscription.add(e.current$.pipe(ve((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ae(i=>i.length>0),Ae()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var t;let i;const r=(t=this.desiredState.videoTrack.getState())===null||t===void 0?void 0:t.quality;r&&(i=e.find(({quality:a})=>a===r),i||this.setAutoQuality(!0)),i||(i=_i(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(i),this.info.currentQuality$.next(i.quality),this.info.videoBitrate$.next(i.bitrate)}initLogs(){this.subscription.add(H(this.desiredState.videoTrack.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(_(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(_(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(_(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;P(this.providerContainer),P(t),tm(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>em(i)),this.providerContainer.current$.subscribe(({type:i})=>Ms("provider",i)),t.duration$.subscribe(i=>Ms("duration",i)),t.availableVideoTracks$.pipe(ae(i=>!!i.length),Ae()).subscribe(i=>Ms("tracks",i)),this.events.fatalError$.subscribe(new wt("fatalError")),this.events.managedError$.subscribe(new wt("managedError")),t.position$.subscribe(new wt("position")),t.currentVideoTrack$.pipe(_(i=>i==null?void 0:i.quality)).subscribe(new wt("quality")),this.info.currentBuffer$.subscribe(new wt("buffer")),t.isBuffering$.subscribe(new wt("isBuffering"))].forEach(i=>this.subscription.add(i)),Ms("codecs",yS())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:R.DOM,message:String(r)})})};this.subscription.add(H(U(document,"visibilitychange"),U(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===p.PLAYING,n=!!e&&!(e!=null&&e.released);r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const i=e.find(r=>r.quality===t);i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}}const ob=`@vkontakte/videoplayer-core@${pu}`;export{Ce as ChromecastState,Ss as HttpConnectionType,lb as Observable,p as PlaybackState,nb as Player,ob as SDK_VERSION,cb as Subject,hb as Subscription,Zt as Surface,pu as VERSION,fb as ValueSubject,A as VideoFormat,pb as VideoQuality};
|