@vkontakte/videoplayer-core 2.0.98-dev.58399882.0 → 2.0.98-dev.7d273671.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 +9 -9
- package/es2018.esm.js +14 -14
- package/esnext.cjs.js +10 -10
- package/esnext.esm.js +12 -12
- package/evergreen.esm.js +12 -12
- package/index.d.ts +4 -1
- package/package.json +3 -4
package/es2015.esm.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.98-dev.
|
|
3
|
-
* Thu,
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.98-dev.7d273671.0
|
|
3
|
+
* Thu, 15 Feb 2024 09:58:09 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-98/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{ValueSubject as T,Subject as O,Subscription as ce,isNonNullable as D,ErrorCategory as I,isNullable as W,fromEvent as V,assertNever as z,merge as G,tap as _r,map as P,observableFrom as We,filterChanged as ye,assertNonNullable as R,debounce as ct,getHighestQuality as pc,timeout as mc,getCurrentBrowser as zr,CurrentClientBrowser as Zn,combine as Be,once as _e,mapTo as ss,filter as oe,now as he,assertNotEmptyArray as vc,videoSizeToQuality as ci,isInvariantQuality as Ri,isHigher as ts,isLower as xs,isHigherOrEqual as Pr,isLowerOrEqual as eo,Observable as qr,interval as Ii,VideoQuality as ut,videoQualityToHeight as gc,abortable as fe,getExponentialDelay as Ls,throttle as Sc,isIOS as bc,CurrentClientDevice as yc,safeStorage as Ea,fillWithDefault as Tc,Logger as Ec}from"@vkontakte/videoplayer-shared/es2015.esm.js";import{Observable as KE,Subject as JE,Subscription as XE,ValueSubject as ZE,VideoQuality as e$}from"@vkontakte/videoplayer-shared/es2015.esm.js";import $c from"lodash/debounce.js";const Ac="2.0.98-dev.58399882.0";var m;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(m||(m={}));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 Ye;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(Ye||(Ye={}));var Ne;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})(Ne||(Ne={}));var Ms;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(Ms||(Ms={}));var ie;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(ie||(ie={}));var ni;(function(s){s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip"})(ni||(ni={}));function ee(s,e,t,i){function r(a){return a instanceof t?a:new t(function(n){n(a)})}return new(t||(t=Promise))(function(a,n){function o(l){try{d(i.next(l))}catch(c){n(c)}}function u(l){try{d(i.throw(l))}catch(c){n(c)}}function d(l){l.done?a(l.value):r(l.value).then(o,u)}d((i=i.apply(s,e||[])).next())})}function _(s){return this instanceof _?(this.v=s,this):new _(s)}function pe(s,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(s,e||[]),r,a=[];return r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r;function n(h){i[h]&&(r[h]=function(f){return new Promise(function(p,S){a.push([h,f,p,S])>1||o(h,f)})})}function o(h,f){try{u(i[h](f))}catch(p){c(a[0][3],p)}}function u(h){h.value instanceof _?Promise.resolve(h.value.v).then(d,l):c(a[0][2],h)}function d(h){o("next",h)}function l(h){o("throw",h)}function c(h,f){h(f),a.shift(),a.length&&o(a[0][0],a[0][1])}}var wc=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 kc{constructor(e){var t;this.connection$=new T(void 0),this.castState$=new T(Ne.NOT_AVAILABLE),this.errorEvent$=new O,this.realCastState$=new T(Ne.NOT_AVAILABLE),this.subscription=new ce,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||wc("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:I.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var 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();W(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();W(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(V(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(G(V(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(_r(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),P(r=>r.castState)),We([i.getCastState()])).pipe(ye(),P(_c),_r(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===Ne.CONNECTED,o=D(this.connection$.getValue());if(n&&!o){const u=i.getCurrentSession();R(u);const d=u.getCastDevice(),l=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(W(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===Ne.CONNECTED?D(this.connection$.getValue())?Ne.CONNECTED:Ne.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:I.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const _c=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return Ne.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return Ne.AVAILABLE;case cast.framework.CastState.CONNECTING:return Ne.CONNECTING;case cast.framework.CastState.CONNECTED:return Ne.CONNECTED;default:return z(s)}};var $a=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Wr(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var bt=function(s){try{return!!s()}catch(e){return!0}},Pc=bt,Qr=!Pc(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),$u=Qr,Au=Function.prototype,kn=Au.call,Dc=$u&&Au.bind.bind(kn,kn),yt=$u?Dc:function(s){return function(){return kn.apply(s,arguments)}},wu=yt,Rc=wu({}.toString),Ic=wu("".slice),Hs=function(s){return Ic(Rc(s),8,-1)},xc=yt,Lc=bt,Cc=Hs,Aa=Object,Oc=xc("".split),Bc=Lc(function(){return!Aa("z").propertyIsEnumerable(0)})?function(s){return Cc(s)=="String"?Oc(s,""):Aa(s)}:Aa,Gs=function(s){return s==null},Mc=Gs,Nc=TypeError,to=function(s){if(Mc(s))throw Nc("Can't call method on "+s);return s},Fc=Bc,Uc=to,js=function(s){return Fc(Uc(s))},us={},er=function(s){return s&&s.Math==Math&&s},Ve=er(typeof globalThis=="object"&&globalThis)||er(typeof window=="object"&&window)||er(typeof self=="object"&&self)||er(typeof $a=="object"&&$a)||function(){return this}()||$a||Function("return this")(),_n=typeof document=="object"&&document.all,Vc=typeof _n=="undefined"&&_n!==void 0,ku={all:_n,IS_HTMLDDA:Vc},_u=ku,Hc=_u.all,Ie=_u.IS_HTMLDDA?function(s){return typeof s=="function"||s===Hc}:function(s){return typeof s=="function"},Gc=Ve,jc=Ie,xo=Gc.WeakMap,Yc=jc(xo)&&/native code/.test(String(xo)),Lo=Ie,Pu=ku,zc=Pu.all,ei=Pu.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:Lo(s)||s===zc}:function(s){return typeof s=="object"?s!==null:Lo(s)},qc=bt,hi=!qc(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Oi={},Wc=Ve,Co=ei,Pn=Wc.document,Qc=Co(Pn)&&Co(Pn.createElement),io=function(s){return Qc?Pn.createElement(s):{}},Kc=hi,Jc=bt,Xc=io,Du=!Kc&&!Jc(function(){return Object.defineProperty(Xc("div"),"a",{get:function(){return 7}}).a!=7}),Zc=hi,eh=bt,Ru=Zc&&eh(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),th=ei,ih=String,sh=TypeError,ti=function(s){if(th(s))return s;throw sh(ih(s)+" is not an object")},rh=Qr,tr=Function.prototype.call,ht=rh?tr.bind(tr):function(){return tr.apply(tr,arguments)},so={},wa=so,ka=Ve,ah=Ie,Oo=function(s){return ah(s)?s:void 0},Bi=function(s,e){return arguments.length<2?Oo(wa[s])||Oo(ka[s]):wa[s]&&wa[s][e]||ka[s]&&ka[s][e]},nh=yt,Kr=nh({}.isPrototypeOf),Jr=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Iu=Ve,_a=Jr,Bo=Iu.process,Mo=Iu.Deno,No=Bo&&Bo.versions||Mo&&Mo.version,Fo=No&&No.v8,wt,Dr;Fo&&(wt=Fo.split("."),Dr=wt[0]>0&&wt[0]<4?1:+(wt[0]+wt[1]));!Dr&&_a&&(wt=_a.match(/Edge\/(\d+)/),(!wt||wt[1]>=74)&&(wt=_a.match(/Chrome\/(\d+)/),wt&&(Dr=+wt[1])));var xu=Dr,Uo=xu,oh=bt,dh=Ve,uh=dh.String,Lu=!!Object.getOwnPropertySymbols&&!oh(function(){var s=Symbol();return!uh(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Uo&&Uo<41}),lh=Lu,Cu=lh&&!Symbol.sham&&typeof Symbol.iterator=="symbol",ch=Bi,hh=Ie,fh=Kr,ph=Cu,mh=Object,Ou=ph?function(s){return typeof s=="symbol"}:function(s){var e=ch("Symbol");return hh(e)&&fh(e.prototype,mh(s))},vh=String,Xr=function(s){try{return vh(s)}catch(e){return"Object"}},gh=Ie,Sh=Xr,bh=TypeError,Mi=function(s){if(gh(s))return s;throw bh(Sh(s)+" is not a function")},yh=Mi,Th=Gs,Zr=function(s,e){var t=s[e];return Th(t)?void 0:yh(t)},Pa=ht,Da=Ie,Ra=ei,Eh=TypeError,$h=function(s,e){var t,i;if(e==="string"&&Da(t=s.toString)&&!Ra(i=Pa(t,s))||Da(t=s.valueOf)&&!Ra(i=Pa(t,s))||e!=="string"&&Da(t=s.toString)&&!Ra(i=Pa(t,s)))return i;throw Eh("Can't convert object to primitive value")},Bu={exports:{}},Ah=!0,Vo=Ve,wh=Object.defineProperty,kh=function(s,e){try{wh(Vo,s,{value:e,configurable:!0,writable:!0})}catch(t){Vo[s]=e}return e},_h=Ve,Ph=kh,Ho="__core-js_shared__",Dh=_h[Ho]||Ph(Ho,{}),ro=Dh,Go=ro;(Bu.exports=function(s,e){return Go[s]||(Go[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 Mu=Bu.exports,Rh=to,Ih=Object,ea=function(s){return Ih(Rh(s))},xh=yt,Lh=ea,Ch=xh({}.hasOwnProperty),Mt=Object.hasOwn||function(e,t){return Ch(Lh(e),t)},Oh=yt,Bh=0,Mh=Math.random(),Nh=Oh(1 .toString),Nu=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Nh(++Bh+Mh,36)},Fh=Ve,Uh=Mu,jo=Mt,Vh=Nu,Hh=Lu,Gh=Cu,Ki=Fh.Symbol,Ia=Uh("wks"),jh=Gh?Ki.for||Ki:Ki&&Ki.withoutSetter||Vh,Ke=function(s){return jo(Ia,s)||(Ia[s]=Hh&&jo(Ki,s)?Ki[s]:jh("Symbol."+s)),Ia[s]},Yh=ht,Yo=ei,zo=Ou,zh=Zr,qh=$h,Wh=Ke,Qh=TypeError,Kh=Wh("toPrimitive"),Jh=function(s,e){if(!Yo(s)||zo(s))return s;var t=zh(s,Kh),i;if(t){if(e===void 0&&(e="default"),i=Yh(t,s,e),!Yo(i)||zo(i))return i;throw Qh("Can't convert object to primitive value")}return e===void 0&&(e="number"),qh(s,e)},Xh=Jh,Zh=Ou,ao=function(s){var e=Xh(s,"string");return Zh(e)?e:e+""},ef=hi,tf=Du,sf=Ru,ir=ti,qo=ao,rf=TypeError,xa=Object.defineProperty,af=Object.getOwnPropertyDescriptor,La="enumerable",Ca="configurable",Oa="writable";Oi.f=ef?sf?function(e,t,i){if(ir(e),t=qo(t),ir(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Oa in i&&!i[Oa]){var r=af(e,t);r&&r[Oa]&&(e[t]=i.value,i={configurable:Ca in i?i[Ca]:r[Ca],enumerable:La in i?i[La]:r[La],writable:!1})}return xa(e,t,i)}:xa:function(e,t,i){if(ir(e),t=qo(t),ir(i),tf)try{return xa(e,t,i)}catch(r){}if("get"in i||"set"in i)throw rf("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var ta=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},nf=hi,of=Oi,df=ta,Ys=nf?function(s,e,t){return of.f(s,e,df(1,t))}:function(s,e,t){return s[e]=t,s},uf=Mu,lf=Nu,Wo=uf("keys"),no=function(s){return Wo[s]||(Wo[s]=lf(s))},oo={},cf=Yc,Fu=Ve,hf=ei,ff=Ys,Ba=Mt,Ma=ro,pf=no,mf=oo,Qo="Object already initialized",Dn=Fu.TypeError,vf=Fu.WeakMap,Rr,Ns,Ir,gf=function(s){return Ir(s)?Ns(s):Rr(s,{})},Sf=function(s){return function(e){var t;if(!hf(e)||(t=Ns(e)).type!==s)throw Dn("Incompatible receiver, "+s+" required");return t}};if(cf||Ma.state){var Rt=Ma.state||(Ma.state=new vf);Rt.get=Rt.get,Rt.has=Rt.has,Rt.set=Rt.set,Rr=function(s,e){if(Rt.has(s))throw Dn(Qo);return e.facade=s,Rt.set(s,e),e},Ns=function(s){return Rt.get(s)||{}},Ir=function(s){return Rt.has(s)}}else{var Hi=pf("state");mf[Hi]=!0,Rr=function(s,e){if(Ba(s,Hi))throw Dn(Qo);return e.facade=s,ff(s,Hi,e),e},Ns=function(s){return Ba(s,Hi)?s[Hi]:{}},Ir=function(s){return Ba(s,Hi)}}var Uu={set:Rr,get:Ns,has:Ir,enforce:gf,getterFor:Sf},bf=Qr,Vu=Function.prototype,Ko=Vu.apply,Jo=Vu.call,Hu=typeof Reflect=="object"&&Reflect.apply||(bf?Jo.bind(Ko):function(){return Jo.apply(Ko,arguments)}),yf=Hs,Tf=yt,Gu=function(s){if(yf(s)==="Function")return Tf(s)},uo={},ju={},Yu={}.propertyIsEnumerable,zu=Object.getOwnPropertyDescriptor,Ef=zu&&!Yu.call({1:2},1);ju.f=Ef?function(e){var t=zu(this,e);return!!t&&t.enumerable}:Yu;var $f=hi,Af=ht,wf=ju,kf=ta,_f=js,Pf=ao,Df=Mt,Rf=Du,Xo=Object.getOwnPropertyDescriptor;uo.f=$f?Xo:function(e,t){if(e=_f(e),t=Pf(t),Rf)try{return Xo(e,t)}catch(i){}if(Df(e,t))return kf(!Af(wf.f,e,t),e[t])};var If=bt,xf=Ie,Lf=/#|\.prototype\./,zs=function(s,e){var t=Of[Cf(s)];return t==Mf?!0:t==Bf?!1:xf(e)?If(e):!!e},Cf=zs.normalize=function(s){return String(s).replace(Lf,".").toLowerCase()},Of=zs.data={},Bf=zs.NATIVE="N",Mf=zs.POLYFILL="P",qu=zs,Zo=Gu,Nf=Mi,Ff=Qr,Uf=Zo(Zo.bind),ia=function(s,e){return Nf(s),e===void 0?s:Ff?Uf(s,e):function(){return s.apply(e,arguments)}},sr=Ve,Vf=Hu,Hf=Gu,Gf=Ie,jf=uo.f,Yf=qu,Gi=so,zf=ia,ji=Ys,ed=Mt,qf=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 Vf(s,this,arguments)};return e.prototype=s.prototype,e},_t=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?sr:r?sr[t]:(sr[t]||{}).prototype,o=i?Gi:Gi[t]||ji(Gi,t,{})[t],u=o.prototype,d,l,c,h,f,p,S,b,v;for(h in e)d=Yf(i?h:t+(r?".":"#")+h,s.forced),l=!d&&n&&ed(n,h),p=o[h],l&&(s.dontCallGetSet?(v=jf(n,h),S=v&&v.value):S=n[h]),f=l&&S?S:e[h],!(l&&typeof p==typeof f)&&(s.bind&&l?b=zf(f,sr):s.wrap&&l?b=qf(f):a&&Gf(f)?b=Hf(f):b=f,(s.sham||f&&f.sham||p&&p.sham)&&ji(b,"sham",!0),ji(o,h,b),a&&(c=t+"Prototype",ed(Gi,c)||ji(Gi,c,{}),ji(Gi[c],h,f),s.real&&u&&(d||!u[h])&&ji(u,h,f)))},Rn=hi,Wf=Mt,Wu=Function.prototype,Qf=Rn&&Object.getOwnPropertyDescriptor,lo=Wf(Wu,"name"),Kf=lo&&function(){}.name==="something",Jf=lo&&(!Rn||Rn&&Qf(Wu,"name").configurable),Xf={EXISTS:lo,PROPER:Kf,CONFIGURABLE:Jf},Qu={},Zf=Math.ceil,ep=Math.floor,tp=Math.trunc||function(e){var t=+e;return(t>0?ep:Zf)(t)},ip=tp,co=function(s){var e=+s;return e!==e||e===0?0:ip(e)},sp=co,rp=Math.max,ap=Math.min,np=function(s,e){var t=sp(s);return t<0?rp(t+e,0):ap(t,e)},op=co,dp=Math.min,up=function(s){return s>0?dp(op(s),9007199254740991):0},lp=up,ho=function(s){return lp(s.length)},cp=js,hp=np,fp=ho,td=function(s){return function(e,t,i){var r=cp(e),a=fp(r),n=hp(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}},pp={includes:td(!0),indexOf:td(!1)},mp=yt,Na=Mt,vp=js,gp=pp.indexOf,Sp=oo,id=mp([].push),bp=function(s,e){var t=vp(s),i=0,r=[],a;for(a in t)!Na(Sp,a)&&Na(t,a)&&id(r,a);for(;e.length>i;)Na(t,a=e[i++])&&(~gp(r,a)||id(r,a));return r},Ku=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],yp=bp,Tp=Ku,Ep=Object.keys||function(e){return yp(e,Tp)},$p=hi,Ap=Ru,wp=Oi,kp=ti,_p=js,Pp=Ep;Qu.f=$p&&!Ap?Object.defineProperties:function(e,t){kp(e);for(var i=_p(t),r=Pp(t),a=r.length,n=0,o;a>n;)wp.f(e,o=r[n++],i[o]);return e};var Dp=Bi,Ju=Dp("document","documentElement"),Rp=ti,Ip=Qu,sd=Ku,xp=oo,Lp=Ju,Cp=io,Op=no,rd=">",ad="<",In="prototype",xn="script",Xu=Op("IE_PROTO"),Fa=function(){},Zu=function(s){return ad+xn+rd+s+ad+"/"+xn+rd},nd=function(s){s.write(Zu("")),s.close();var e=s.parentWindow.Object;return s=null,e},Bp=function(){var s=Cp("iframe"),e="java"+xn+":",t;return s.style.display="none",Lp.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Zu("document.F=Object")),t.close(),t.F},rr,$r=function(){try{rr=new ActiveXObject("htmlfile")}catch(e){}$r=typeof document!="undefined"?document.domain&&rr?nd(rr):Bp():nd(rr);for(var s=sd.length;s--;)delete $r[In][sd[s]];return $r()};xp[Xu]=!0;var el=Object.create||function(e,t){var i;return e!==null?(Fa[In]=Rp(e),i=new Fa,Fa[In]=null,i[Xu]=e):i=$r(),t===void 0?i:Ip.f(i,t)},Mp=bt,Np=!Mp(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),Fp=Mt,Up=Ie,Vp=ea,Hp=no,Gp=Np,od=Hp("IE_PROTO"),Ln=Object,jp=Ln.prototype,tl=Gp?Ln.getPrototypeOf:function(s){var e=Vp(s);if(Fp(e,od))return e[od];var t=e.constructor;return Up(t)&&e instanceof t?t.prototype:e instanceof Ln?jp:null},Yp=Ys,fo=function(s,e,t,i){return i&&i.enumerable?s[e]=t:Yp(s,e,t),s},zp=bt,qp=Ie,Wp=ei,Qp=el,dd=tl,Kp=fo,Jp=Ke,Cn=Jp("iterator"),il=!1,Jt,Ua,Va;[].keys&&(Va=[].keys(),"next"in Va?(Ua=dd(dd(Va)),Ua!==Object.prototype&&(Jt=Ua)):il=!0);var Xp=!Wp(Jt)||zp(function(){var s={};return Jt[Cn].call(s)!==s});Xp?Jt={}:Jt=Qp(Jt);qp(Jt[Cn])||Kp(Jt,Cn,function(){return this});var sl={IteratorPrototype:Jt,BUGGY_SAFARI_ITERATORS:il},Zp=Ke,em=Zp("toStringTag"),rl={};rl[em]="z";var po=String(rl)==="[object z]",tm=po,im=Ie,Ar=Hs,sm=Ke,rm=sm("toStringTag"),am=Object,nm=Ar(function(){return arguments}())=="Arguments",om=function(s,e){try{return s[e]}catch(t){}},qs=tm?Ar:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=om(e=am(s),rm))=="string"?t:nm?Ar(e):(i=Ar(e))=="Object"&&im(e.callee)?"Arguments":i},dm=po,um=qs,lm=dm?{}.toString:function(){return"[object "+um(this)+"]"},cm=po,hm=Oi.f,fm=Ys,pm=Mt,mm=lm,vm=Ke,ud=vm("toStringTag"),mo=function(s,e,t,i){if(s){var r=t?s:s.prototype;pm(r,ud)||hm(r,ud,{configurable:!0,value:e}),i&&!cm&&fm(r,"toString",mm)}},gm=sl.IteratorPrototype,Sm=el,bm=ta,ym=mo,Tm=us,Em=function(){return this},$m=function(s,e,t,i){var r=e+" Iterator";return s.prototype=Sm(gm,{next:bm(+!i,t)}),ym(s,r,!1,!0),Tm[r]=Em,s},Am=_t,wm=ht,al=Xf,km=$m,_m=tl,Pm=mo,ld=fo,Dm=Ke,cd=us,nl=sl,Rm=al.PROPER;al.CONFIGURABLE;nl.IteratorPrototype;var ar=nl.BUGGY_SAFARI_ITERATORS,Ha=Dm("iterator"),hd="keys",nr="values",fd="entries",Im=function(){return this},xm=function(s,e,t,i,r,a,n){km(t,e,i);var o=function(v){if(v===r&&h)return h;if(!ar&&v in l)return l[v];switch(v){case hd:return function(){return new t(this,v)};case nr:return function(){return new t(this,v)};case fd:return function(){return new t(this,v)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,l=s.prototype,c=l[Ha]||l["@@iterator"]||r&&l[r],h=!ar&&c||o(r),f=e=="Array"&&l.entries||c,p,S,b;if(f&&(p=_m(f.call(new s)),p!==Object.prototype&&p.next&&(Pm(p,u,!0,!0),cd[u]=Im)),Rm&&r==nr&&c&&c.name!==nr&&(d=!0,h=function(){return wm(c,this)}),r)if(S={values:o(nr),keys:a?h:o(hd),entries:o(fd)},n)for(b in S)(ar||d||!(b in l))&&ld(l,b,S[b]);else Am({target:e,proto:!0,forced:ar||d},S);return n&&l[Ha]!==h&&ld(l,Ha,h,{name:r}),cd[e]=h,S},Lm=function(s,e){return{value:s,done:e}},Cm=js,pd=us,ol=Uu;Oi.f;var Om=xm,or=Lm,dl="Array Iterator",Bm=ol.set,Mm=ol.getterFor(dl);Om(Array,"Array",function(s,e){Bm(this,{type:dl,target:Cm(s),index:0,kind:e})},function(){var s=Mm(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,or(void 0,!0)):t=="keys"?or(i,!1):t=="values"?or(e[i],!1):or([i,e[i]],!1)},"values");pd.Arguments=pd.Array;var Nm=Ke,Fm=us,Um=Nm("iterator"),Vm=Array.prototype,Hm=function(s){return s!==void 0&&(Fm.Array===s||Vm[Um]===s)},Gm=qs,md=Zr,jm=Gs,Ym=us,zm=Ke,qm=zm("iterator"),ul=function(s){if(!jm(s))return md(s,qm)||md(s,"@@iterator")||Ym[Gm(s)]},Wm=ht,Qm=Mi,Km=ti,Jm=Xr,Xm=ul,Zm=TypeError,ev=function(s,e){var t=arguments.length<2?Xm(s):e;if(Qm(t))return Km(Wm(t,s));throw Zm(Jm(s)+" is not iterable")},tv=ht,vd=ti,iv=Zr,sv=function(s,e,t){var i,r;vd(s);try{if(i=iv(s,"return"),!i){if(e==="throw")throw t;return t}i=tv(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return vd(i),t},rv=ia,av=ht,nv=ti,ov=Xr,dv=Hm,uv=ho,gd=Kr,lv=ev,cv=ul,Sd=sv,hv=TypeError,wr=function(s,e){this.stopped=s,this.result=e},bd=wr.prototype,vo=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=rv(e,i),d,l,c,h,f,p,S,b=function(y){return d&&Sd(d,"normal",y),new wr(!0,y)},v=function(y){return r?(nv(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=cv(s),!l)throw hv(ov(s)+" is not iterable");if(dv(l)){for(c=0,h=uv(s);h>c;c++)if(f=v(s[c]),f&&gd(bd,f))return f;return new wr(!1)}d=lv(s,l)}for(p=a?s.next:d.next;!(S=av(p,d)).done;){try{f=v(S.value)}catch(y){Sd(d,"throw",y)}if(typeof f=="object"&&f&&gd(bd,f))return f}return new wr(!1)},fv=ao,pv=Oi,mv=ta,vv=function(s,e,t){var i=fv(e);i in s?pv.f(s,i,mv(0,t)):s[i]=t},gv=_t,Sv=vo,bv=vv;gv({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Sv(e,function(i,r){bv(t,i,r)},{AS_ENTRIES:!0}),t}});var yv=so,Tv=yv.Object.fromEntries,Ev={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},$v=Ev,Av=Ve,wv=qs,kv=Ys,yd=us,_v=Ke,Td=_v("toStringTag");for(var Ga in $v){var Ed=Av[Ga],ja=Ed&&Ed.prototype;ja&&wv(ja)!==Td&&kv(ja,Td,Ga),yd[Ga]=yd.Array}var Pv=Tv,Dv=Pv,Rv=Dv,Iv=Rv,xi=Wr(Iv),xv=Hs,sa=typeof process!="undefined"&&xv(process)=="process",Lv=Oi,Cv=function(s,e,t){return Lv.f(s,e,t)},Ov=Bi,Bv=Cv,Mv=Ke,Nv=hi,$d=Mv("species"),Fv=function(s){var e=Ov(s);Nv&&e&&!e[$d]&&Bv(e,$d,{configurable:!0,get:function(){return this}})},Uv=Kr,Vv=TypeError,Hv=function(s,e){if(Uv(e,s))return s;throw Vv("Incorrect invocation")},Gv=yt,jv=Ie,On=ro,Yv=Gv(Function.toString);jv(On.inspectSource)||(On.inspectSource=function(s){return Yv(s)});var ll=On.inspectSource,zv=yt,qv=bt,cl=Ie,Wv=qs,Qv=Bi,Kv=ll,hl=function(){},Jv=[],fl=Qv("Reflect","construct"),go=/^\s*(?:class|function)\b/,Xv=zv(go.exec),Zv=!go.exec(hl),As=function(e){if(!cl(e))return!1;try{return fl(hl,Jv,e),!0}catch(t){return!1}},pl=function(e){if(!cl(e))return!1;switch(Wv(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Zv||!!Xv(go,Kv(e))}catch(t){return!0}};pl.sham=!0;var eg=!fl||qv(function(){var s;return As(As.call)||!As(Object)||!As(function(){s=!0})||s})?pl:As,tg=eg,ig=Xr,sg=TypeError,rg=function(s){if(tg(s))return s;throw sg(ig(s)+" is not a constructor")},Ad=ti,ag=rg,ng=Gs,og=Ke,dg=og("species"),ml=function(s,e){var t=Ad(s).constructor,i;return t===void 0||ng(i=Ad(t)[dg])?e:ag(i)},ug=yt,lg=ug([].slice),cg=TypeError,hg=function(s,e){if(s<e)throw cg("Not enough arguments");return s},fg=Jr,vl=/(?:ipad|iphone|ipod).*applewebkit/i.test(fg),lt=Ve,pg=Hu,mg=ia,wd=Ie,vg=Mt,gl=bt,kd=Ju,gg=lg,_d=io,Sg=hg,bg=vl,yg=sa,Bn=lt.setImmediate,Mn=lt.clearImmediate,Tg=lt.process,Ya=lt.Dispatch,Eg=lt.Function,Pd=lt.MessageChannel,$g=lt.String,za=0,Cs={},Dd="onreadystatechange",Fs,wi,qa,Wa;gl(function(){Fs=lt.location});var So=function(s){if(vg(Cs,s)){var e=Cs[s];delete Cs[s],e()}},Qa=function(s){return function(){So(s)}},Rd=function(s){So(s.data)},Id=function(s){lt.postMessage($g(s),Fs.protocol+"//"+Fs.host)};(!Bn||!Mn)&&(Bn=function(e){Sg(arguments.length,1);var t=wd(e)?e:Eg(e),i=gg(arguments,1);return Cs[++za]=function(){pg(t,void 0,i)},wi(za),za},Mn=function(e){delete Cs[e]},yg?wi=function(s){Tg.nextTick(Qa(s))}:Ya&&Ya.now?wi=function(s){Ya.now(Qa(s))}:Pd&&!bg?(qa=new Pd,Wa=qa.port2,qa.port1.onmessage=Rd,wi=mg(Wa.postMessage,Wa)):lt.addEventListener&&wd(lt.postMessage)&&!lt.importScripts&&Fs&&Fs.protocol!=="file:"&&!gl(Id)?(wi=Id,lt.addEventListener("message",Rd,!1)):Dd in _d("script")?wi=function(s){kd.appendChild(_d("script"))[Dd]=function(){kd.removeChild(this),So(s)}}:wi=function(s){setTimeout(Qa(s),0)});var Sl={set:Bn,clear:Mn},bl=function(){this.head=null,this.tail=null};bl.prototype={add:function(s){var e={item:s,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var s=this.head;if(s){var e=this.head=s.next;return e===null&&(this.tail=null),s.item}}};var yl=bl,Ag=Jr,wg=/ipad|iphone|ipod/i.test(Ag)&&typeof Pebble!="undefined",kg=Jr,_g=/web0s(?!.*chrome)/i.test(kg),Li=Ve,xd=ia,Pg=uo.f,Ka=Sl.set,Dg=yl,Rg=vl,Ig=wg,xg=_g,Ja=sa,Ld=Li.MutationObserver||Li.WebKitMutationObserver,Cd=Li.document,Od=Li.process,dr=Li.Promise,Bd=Pg(Li,"queueMicrotask"),Nn=Bd&&Bd.value,Yi,Xa,Za,ur,Md;if(!Nn){var lr=new Dg,cr=function(){var s,e;for(Ja&&(s=Od.domain)&&s.exit();e=lr.get();)try{e()}catch(t){throw lr.head&&Yi(),t}s&&s.enter()};!Rg&&!Ja&&!xg&&Ld&&Cd?(Xa=!0,Za=Cd.createTextNode(""),new Ld(cr).observe(Za,{characterData:!0}),Yi=function(){Za.data=Xa=!Xa}):!Ig&&dr&&dr.resolve?(ur=dr.resolve(void 0),ur.constructor=dr,Md=xd(ur.then,ur),Yi=function(){Md(cr)}):Ja?Yi=function(){Od.nextTick(cr)}:(Ka=xd(Ka,Li),Yi=function(){Ka(cr)}),Nn=function(s){lr.head||Yi(),lr.add(s)}}var Lg=Nn,Cg=function(s,e){try{arguments.length==1?console.error(s):console.error(s,e)}catch(t){}},bo=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}},Og=Ve,ls=Og.Promise,Tl=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",Bg=Tl,Mg=sa,Ng=!Bg&&!Mg&&typeof window=="object"&&typeof document=="object",Fg=Ve,Os=ls,Ug=Ie,Vg=qu,Hg=ll,Gg=Ke,jg=Ng,Yg=Tl,en=xu,Nd=Os&&Os.prototype,zg=Gg("species"),Fn=!1,El=Ug(Fg.PromiseRejectionEvent),qg=Vg("Promise",function(){var s=Hg(Os),e=s!==String(Os);if(!e&&en===66||!(Nd.catch&&Nd.finally))return!0;if(!en||en<51||!/native code/.test(s)){var t=new Os(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[zg]=i,Fn=t.then(function(){})instanceof i,!Fn)return!0}return!e&&(jg||Yg)&&!El}),Ws={CONSTRUCTOR:qg,REJECTION_EVENT:El,SUBCLASSING:Fn},cs={},Fd=Mi,Wg=TypeError,Qg=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw Wg("Bad Promise constructor");e=i,t=r}),this.resolve=Fd(e),this.reject=Fd(t)};cs.f=function(s){return new Qg(s)};var Kg=_t,xr=sa,ui=Ve,Qs=ht,Jg=fo,Xg=mo,Zg=Fv,eS=Mi,Un=Ie,tS=ei,iS=Hv,sS=ml,$l=Sl.set,yo=Lg,rS=Cg,aS=bo,nS=yl,Al=Uu,Vn=ls,To=Ws,wl=cs,ra="Promise",kl=To.CONSTRUCTOR,oS=To.REJECTION_EVENT;To.SUBCLASSING;var tn=Al.getterFor(ra),dS=Al.set,uS=Vn&&Vn.prototype,Ji=Vn,sn=uS,_l=ui.TypeError,Hn=ui.document,Eo=ui.process,Gn=wl.f,lS=Gn,cS=!!(Hn&&Hn.createEvent&&ui.dispatchEvent),Pl="unhandledrejection",hS="rejectionhandled",Ud=0,Dl=1,fS=2,$o=1,Rl=2,hr,Vd,pS,Il=function(s){var e;return tS(s)&&Un(e=s.then)?e:!1},xl=function(s,e){var t=e.value,i=e.state==Dl,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,d,l;try{r?(i||(e.rejection===Rl&&vS(e),e.rejection=$o),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),l=!0)),u===s.promise?n(_l("Promise-chain cycle")):(d=Il(u))?Qs(d,u,a,n):a(u)):n(t)}catch(c){o&&!l&&o.exit(),n(c)}},Ll=function(s,e){s.notified||(s.notified=!0,yo(function(){for(var t=s.reactions,i;i=t.get();)xl(i,s);s.notified=!1,e&&!s.rejection&&mS(s)}))},Cl=function(s,e,t){var i,r;cS?(i=Hn.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),ui.dispatchEvent(i)):i={promise:e,reason:t},!oS&&(r=ui["on"+s])?r(i):s===Pl&&rS("Unhandled promise rejection",t)},mS=function(s){Qs($l,ui,function(){var e=s.facade,t=s.value,i=Hd(s),r;if(i&&(r=aS(function(){xr?Eo.emit("unhandledRejection",t,e):Cl(Pl,e,t)}),s.rejection=xr||Hd(s)?Rl:$o,r.error))throw r.value})},Hd=function(s){return s.rejection!==$o&&!s.parent},vS=function(s){Qs($l,ui,function(){var e=s.facade;xr?Eo.emit("rejectionHandled",e):Cl(hS,e,s.value)})},Xi=function(s,e,t){return function(i){s(e,i,t)}},is=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=fS,Ll(s,!0))},jn=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw _l("Promise can't be resolved itself");var i=Il(e);i?yo(function(){var r={done:!1};try{Qs(i,e,Xi(jn,r,s),Xi(is,r,s))}catch(a){is(r,a,s)}}):(s.value=e,s.state=Dl,Ll(s,!1))}catch(r){is({done:!1},r,s)}}};kl&&(Ji=function(e){iS(this,sn),eS(e),Qs(hr,this);var t=tn(this);try{e(Xi(jn,t),Xi(is,t))}catch(i){is(t,i)}},sn=Ji.prototype,hr=function(e){dS(this,{type:ra,done:!1,notified:!1,parent:!1,reactions:new nS,rejection:!1,state:Ud,value:void 0})},hr.prototype=Jg(sn,"then",function(e,t){var i=tn(this),r=Gn(sS(this,Ji));return i.parent=!0,r.ok=Un(e)?e:!0,r.fail=Un(t)&&t,r.domain=xr?Eo.domain:void 0,i.state==Ud?i.reactions.add(r):yo(function(){xl(r,i)}),r.promise}),Vd=function(){var s=new hr,e=tn(s);this.promise=s,this.resolve=Xi(jn,e),this.reject=Xi(is,e)},wl.f=Gn=function(s){return s===Ji||s===pS?new Vd(s):lS(s)});Kg({global:!0,constructor:!0,wrap:!0,forced:kl},{Promise:Ji});Xg(Ji,ra,!1,!0);Zg(ra);var gS=Ke,Ol=gS("iterator"),Bl=!1;try{var SS=0,Gd={next:function(){return{done:!!SS++}},return:function(){Bl=!0}};Gd[Ol]=function(){return this},Array.from(Gd,function(){throw 2})}catch(s){}var bS=function(s,e){if(!e&&!Bl)return!1;var t=!1;try{var i={};i[Ol]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t},yS=ls,TS=bS,ES=Ws.CONSTRUCTOR,Ml=ES||!TS(function(s){yS.all(s).then(void 0,function(){})}),$S=_t,AS=ht,wS=Mi,kS=cs,_S=bo,PS=vo,DS=Ml;$S({target:"Promise",stat:!0,forced:DS},{all:function(e){var t=this,i=kS.f(t),r=i.resolve,a=i.reject,n=_S(function(){var o=wS(t.resolve),u=[],d=0,l=1;PS(e,function(c){var h=d++,f=!1;l++,AS(o,t,c).then(function(p){f||(f=!0,u[h]=p,--l||r(u))},a)}),--l||r(u)});return n.error&&a(n.value),i.promise}});var RS=_t,IS=Ws.CONSTRUCTOR,jd=ls;jd&&jd.prototype;RS({target:"Promise",proto:!0,forced:IS,real:!0},{catch:function(s){return this.then(void 0,s)}});var xS=_t,LS=ht,CS=Mi,OS=cs,BS=bo,MS=vo,NS=Ml;xS({target:"Promise",stat:!0,forced:NS},{race:function(e){var t=this,i=OS.f(t),r=i.reject,a=BS(function(){var n=CS(t.resolve);MS(e,function(o){LS(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}});var FS=_t,US=ht,VS=cs,HS=Ws.CONSTRUCTOR;FS({target:"Promise",stat:!0,forced:HS},{reject:function(e){var t=VS.f(this);return US(t.reject,void 0,e),t.promise}});var GS=ti,jS=ei,YS=cs,Nl=function(s,e){if(GS(s),jS(e)&&e.constructor===s)return e;var t=YS.f(s),i=t.resolve;return i(e),t.promise},zS=_t,qS=Bi,WS=Ah,QS=ls,KS=Ws.CONSTRUCTOR,JS=Nl,XS=qS("Promise"),ZS=!KS;zS({target:"Promise",stat:!0,forced:WS},{resolve:function(e){return JS(ZS&&this===XS?QS:this,e)}});var eb=_t,Yn=ls,tb=bt,ib=Bi,sb=Ie,rb=ml,Yd=Nl,ab=Yn&&Yn.prototype,nb=!!Yn&&tb(function(){ab.finally.call({then:function(){}},function(){})});eb({target:"Promise",proto:!0,real:!0,forced:nb},{finally:function(s){var e=rb(this,ib("Promise")),t=sb(s);return this.then(t?function(i){return Yd(e,s()).then(function(){return i})}:s,t?function(i){return Yd(e,s()).then(function(){throw i})}:s)}});var ob=Bi,Ao=ob,db=Ao,ub=db("Promise","finally"),lb=ub,cb=lb,hb=cb,fb=hb,Ks=Wr(fb),Te;(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"})(Te||(Te={}));var qe=(s,e=0,t=Te.OFFSET_P)=>{switch(t){case Te.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Te.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case Te.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 Lr=(s,e)=>{var t;switch(e){case Te.OFFSET_P:return NaN;case Te.PLAYBACK_SHIFT:{const i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case Te.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 x=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};class me{constructor(e){this.transitionStarted$=new O,this.transitionEnded$=new O,this.transitionUpdated$=new O,this.forceChanged$=new O,this.stateChangeStarted$=G(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=G(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 pb=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 te;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(te||(te={}));const mb=5,vb=5,gb=500,zd=7e3;class Sb{constructor(e){this.subscription=new ce,this.loadMediaTimeoutSubscription=new ce,this.videoState=new me(te.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===m.STOPPED){i!==te.STOPPED&&(this.videoState.startTransitionTo(te.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==m.PAUSED&&o.state===ie.Requested&&i!==te.STOPPED){this.seek(o.position/1e3);return}switch(a){case m.READY:{switch(i){case te.PLAYING:case te.PAUSED:case te.READY:break;case te.STOPPED:this.videoState.startTransitionTo(te.READY),this.prepare();break;default:z(i)}break}case m.PLAYING:{switch(i){case te.PLAYING:break;case te.PAUSED:this.videoState.startTransitionTo(te.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case te.READY:this.videoState.startTransitionTo(te.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case te.STOPPED:this.videoState.startTransitionTo(te.READY),this.prepare();break;default:z(i)}break}case m.PAUSED:{switch(i){case te.PLAYING:this.videoState.startTransitionTo(te.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case te.PAUSED:break;case te.READY:this.videoState.startTransitionTo(te.PAUSED),this.videoState.setState(te.PAUSED);break;case te.STOPPED:this.videoState.startTransitionTo(te.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(pb(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 ce;this.subscription.add(e),this.subscription.add(G(this.videoState.stateChangeStarted$.pipe(P(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(P(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 O;e.add(r.pipe(ct(gb)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(V(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===ie.Applying||Math.abs(o-a)>mb)&&r.next(o),a=o})),e.add(V(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(V(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(V(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(V(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<vb&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),x(this.params.desiredState.playbackState,m.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(V(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(V(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const i=G(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,We(["init"])).pipe(ct(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(te.PAUSED),x(this.params.desiredState.playbackState,m.PAUSED)):(this.videoState.setState(te.PLAYING),x(this.params.desiredState.playbackState,m.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:ie.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)===te.PAUSED||e===te.PLAYING)&&(this.videoState.setState(te.PAUSED),x(this.params.desiredState.playbackState,m.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===te.PLAYING||e===te.PAUSED)&&(this.videoState.setState(te.PLAYING),x(this.params.desiredState.playbackState,m.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===te.READY&&this.videoState.setState(te.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===m.READY&&x(this.params.desiredState.playbackState,m.READY)}handleRemoteStop(){this.videoState.getState()!==te.STOPPED&&this.videoState.setState(te.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];R(l);const c=pc(Object.keys(l));R(c);const h=l[c];R(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case A.HLS:case A.HLS_ONDEMAND:{const l=i[e];R(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];R(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case A.DASH_LIVE_CMAF:{const l=i[e];R(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];R(l),r=qe(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:I.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===ie.Applying||i.state===ie.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(mc(zd).subscribe(()=>a(`timeout(${zd})`)))});Ks(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===ie.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{const a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:I.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}var bb=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)},yb=s=>{const e=new T(1/0),t=new O,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,p,S;const b=xi(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=(p=b["x-delivery-type"])!==null&&p!==void 0?p:Ms.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,p=h.progress;h.onload=function(...S){return u(this),f(...S)},h.progress=function(...S){return d(this),p(...S)},o()}return c(h)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:i}},li=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},Tb=s=>s.extend("RequestModifier",()=>({modifyRequestURL:li}),!0),Eb=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 kt=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=s.getState(),o=e(),u=W(r),d=new ce;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},fi=(s,e,t)=>kt(e,()=>s.loop,i=>{D(i)&&(s.loop=i)},{onError:t}),Nt=(s,e,t,i)=>kt(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}),ii=(s,e,t,i)=>kt(e,()=>s.playbackRate,r=>{D(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),$b=s=>["__",s.language,s.label].join("|"),Ab=(s,e)=>{if(s.id===e)return!0;const[t,i,r]=e.split("|");return s.language===i&&s.label===r};class Pt{constructor(){this.available$=new O,this.current$=new T(void 0),this.error$=new O,this.subscription=new ce,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:I.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(kt(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(P(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(kt(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(P(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(kt(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(kt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){R(this.video);const{textTracks:e}=this.video;this.subscription.add(V(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(G(V(e,"addtrack"),V(e,"removetrack"),We(["init"])).pipe(P(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),ye((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(G(V(e,"change"),We(["init"])).pipe(P(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),P(i=>i&&this.htmlTextTrackToITextTrack(i).id),ye()).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(V(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(V(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){R(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Pt.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,i;const{language:r,label:a}=e,n=e.id?e.id:$b(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){R(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(W(e)||!Ab(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){R(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){R(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 wo=s=>{s.removeAttribute("src"),s.load()},wb=s=>{try{s.pause(),s.playbackRate=0,wo(s),s.remove()}catch(e){console.error(e)}};class kb{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 zn=window.WeakMap?new WeakMap:new kb,Ft=s=>{let e=s.querySelector("video");const t=!!e;return e?wo(e):(e=document.createElement("video"),s.appendChild(e)),zn.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},Ut=s=>{const e=zn.get(s);zn.delete(s),e?wo(s):wb(s)};class Js{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 Fl=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},qd=s=>{const e=Fl(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},_b=s=>{const e=Fl(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)},qn=3;class Pb{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<qn&&(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||qn))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 Ul=(s,e,t=qn)=>{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 Vt=s=>{const e=g=>V(s,g).pipe(ss(void 0)),i=G(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(g=>V(s,g))).pipe(P(g=>g.type==="ended"?s.readyState<2:s.readyState<3),ye()),r=G(V(s,"progress"),V(s,"timeupdate")).pipe(P(()=>Ul(s.buffered,s.currentTime))),n=zr().browser===Zn.Safari?Be({play:e("play").pipe(_e()),playing:e("playing")}).pipe(ss(void 0)):e("playing"),o=V(s,"volumechange").pipe(P(()=>({muted:s.muted,volume:s.volume}))),u=V(s,"ratechange").pipe(P(()=>s.playbackRate)),d=V(s,"error").pipe(oe(()=>!!(s.error||s.played.length)),P(()=>{var g;const E=s.error;return{id:E?`MediaError#${E.code}`:"HtmlVideoError",category:I.VIDEO_PIPELINE,message:E?E.message:"Error event from HTML video element",thrown:(g=s.error)!==null&&g!==void 0?g:void 0}})),l=V(s,"timeupdate").pipe(P(()=>s.currentTime)),c=new O,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 p=V(s,"enterpictureinpicture"),S=V(s,"leavepictureinpicture"),b=new T(_b(s));p.subscribe(()=>b.next(!0)),S.subscribe(()=>b.next(!1));const v=new T(qd(s));return V(s,"fullscreenchange").pipe(P(()=>qd(s))).subscribe(v),{playing$:n,pause$:e("pause").pipe(oe(()=>!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$:V(s,"durationchange").pipe(P(()=>s.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:o,playbackRateState$:u,inPiP$:b,inFullscreen$:v}},aa=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var Db=_t,Rb=ea,Ib=ho,xb=co;Db({target:"Array",proto:!0},{at:function(e){var t=Rb(this),i=Ib(t),r=xb(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});var Lb=Ao,Cb=Lb("Array","at"),Ob=Cb,Bb=Ob,Mb=Bb,Nb=Mb,Oe=Wr(Nb);let ko=!1,Kt={};const Fb=s=>{ko=s},Ub=()=>{Kt={}},Vb=s=>{s(Kt)},fr=(s,e)=>{var t;ko&&(Kt.meta=(t=Kt.meta)!==null&&t!==void 0?t:{},Kt.meta[s]=e)};class Lt{constructor(e){this.name=e}next(e){var t,i;if(!ko)return;Kt.series=(t=Kt.series)!==null&&t!==void 0?t:{};const r=(i=Kt.series[this.name])!==null&&i!==void 0?i:[];r.push([Date.now(),e]),Kt.series[this.name]=r}}var _i;(function(s){s.FitsContainer="FitsContainer",s.FitsThroughput="FitsThroughput",s.Buffer="Buffer",s.DroppedFramesLimit="DroppedFramesLimit",s.FitsQualityLimits="FitsQualityLimits"})(_i||(_i={}));const Hb=new Lt("best_bitrate"),Gb=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class Vl{constructor(){this.history={}}recordSelection(e){this.history[e.id]=he()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const jb='Assertion "ABR Tracks is empty array" failed',Ni=(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,p,S,b;vc(s,jb);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&&ci(y),E=i.considerPlaybackRate&&D(o)?o:1,$=s.filter(N=>!Ri(N.quality)).sort((N,C)=>ts(N.quality,C.quality)?-1:1),L=(f=Oe($,-1))===null||f===void 0?void 0:f.quality,j=(p=Oe($,0))===null||p===void 0?void 0:p.quality,K=W(r)||D(r.min)&&D(r.max)&&xs(r.max,r.min)||D(r.min)&&j&&ts(r.min,j)||D(r.max)&&L&&xs(r.max,L),H=E*Gb(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),q={},B=$.filter(N=>(g?xs(N.quality,g):!0)?(D(t)&&isFinite(t)&&D(N.bitrate)?t-a>=N.bitrate*H:!0)?i.lazyQualitySwitch&&D(i.minBufferToSwitchUp)&&u&&!Ri(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&ts(N.quality,u.quality)?(q[N.quality]=_i.Buffer,!1):!!l&&Pr(N.quality,l)?(q[N.quality]=_i.DroppedFramesLimit,!1):K||(W(r.max)||eo(N.quality,r.max))&&(W(r.min)||Pr(N.quality,r.min))?!0:(q[N.quality]=_i.FitsQualityLimits,!1):(q[N.quality]=_i.FitsThroughput,!1):(q[N.quality]=_i.FitsContainer,!1))[0];B&&B.bitrate&&Hb.next(B.bitrate);const M=(S=B!=null?B:$[Math.ceil(($.length-1)/2)])!==null&&S!==void 0?S:s[0];M.quality!==((b=d==null?void 0:d.last)===null||b===void 0?void 0:b.quality)&&c({message:`
|
|
6
|
+
import{ValueSubject as T,Subject as O,Subscription as ce,isNonNullable as I,ErrorCategory as R,isNullable as W,fromEvent as V,assertNever as z,merge as G,tap as Bs,map as P,observableFrom as We,filterChanged as ye,assertNonNullable as D,debounce as lt,getHighestQuality as fc,timeout as pc,getCurrentBrowser as jr,CurrentClientBrowser as Xn,combine as Be,once as _e,mapTo as ss,filter as oe,now as he,assertNotEmptyArray as mc,videoSizeToQuality as ci,isInvariantQuality as Ii,isHigher as ts,isLower as $r,isHigherOrEqual as An,isLowerOrEqual as Tu,Observable as Yr,debounceFn as vc,interval as Ri,VideoQuality as ft,videoQualityToHeight as gc,abortable as fe,getExponentialDelay as Ls,throttle as Sc,isIOS as bc,CurrentClientDevice as yc,safeStorage as ya,fillWithDefault as Tc,Logger as Ec}from"@vkontakte/videoplayer-shared/es2015.esm.js";import{Observable as WE,Subject as QE,Subscription as KE,ValueSubject as JE,VideoQuality as XE}from"@vkontakte/videoplayer-shared/es2015.esm.js";const $c="2.0.98-dev.7d273671.0";var m;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(m||(m={}));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 Ye;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(Ye||(Ye={}));var Ne;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})(Ne||(Ne={}));var Ms;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(Ms||(Ms={}));var ie;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(ie||(ie={}));var ni;(function(s){s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip"})(ni||(ni={}));function J(s,e,t,i){function r(a){return a instanceof t?a:new t(function(n){n(a)})}return new(t||(t=Promise))(function(a,n){function o(l){try{d(i.next(l))}catch(c){n(c)}}function u(l){try{d(i.throw(l))}catch(c){n(c)}}function d(l){l.done?a(l.value):r(l.value).then(o,u)}d((i=i.apply(s,e||[])).next())})}function _(s){return this instanceof _?(this.v=s,this):new _(s)}function pe(s,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(s,e||[]),r,a=[];return r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r;function n(h){i[h]&&(r[h]=function(f){return new Promise(function(p,S){a.push([h,f,p,S])>1||o(h,f)})})}function o(h,f){try{u(i[h](f))}catch(p){c(a[0][3],p)}}function u(h){h.value instanceof _?Promise.resolve(h.value.v).then(d,l):c(a[0][2],h)}function d(h){o("next",h)}function l(h){o("throw",h)}function c(h,f){h(f),a.shift(),a.length&&o(a[0][0],a[0][1])}}var Ac=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 wc{constructor(e){var t;this.connection$=new T(void 0),this.castState$=new T(Ne.NOT_AVAILABLE),this.errorEvent$=new O,this.realCastState$=new T(Ne.NOT_AVAILABLE),this.subscription=new ce,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=I((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||Ac("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(){I(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();W(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();W(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(V(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(G(V(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Bs(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),P(r=>r.castState)),We([i.getCastState()])).pipe(ye(),P(kc),Bs(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===Ne.CONNECTED,o=I(this.connection$.getValue());if(n&&!o){const u=i.getCurrentSession();D(u);const d=u.getCastDevice(),l=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(W(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===Ne.CONNECTED?I(this.connection$.getValue())?Ne.CONNECTED:Ne.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 kc=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return Ne.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return Ne.AVAILABLE;case cast.framework.CastState.CONNECTING:return Ne.CONNECTING;case cast.framework.CastState.CONNECTED:return Ne.CONNECTED;default:return z(s)}};var Ta=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function zr(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var bt=function(s){try{return!!s()}catch(e){return!0}},_c=bt,qr=!_c(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),Eu=qr,$u=Function.prototype,wn=$u.call,Pc=Eu&&$u.bind.bind(wn,wn),yt=Eu?Pc:function(s){return function(){return wn.apply(s,arguments)}},Au=yt,Dc=Au({}.toString),Ic=Au("".slice),Hs=function(s){return Ic(Dc(s),8,-1)},Rc=yt,Lc=bt,xc=Hs,Ea=Object,Cc=Rc("".split),Oc=Lc(function(){return!Ea("z").propertyIsEnumerable(0)})?function(s){return xc(s)=="String"?Cc(s,""):Ea(s)}:Ea,Gs=function(s){return s==null},Bc=Gs,Mc=TypeError,Zn=function(s){if(Bc(s))throw Mc("Can't call method on "+s);return s},Nc=Oc,Fc=Zn,js=function(s){return Nc(Fc(s))},us={},er=function(s){return s&&s.Math==Math&&s},Ve=er(typeof globalThis=="object"&&globalThis)||er(typeof window=="object"&&window)||er(typeof self=="object"&&self)||er(typeof Ta=="object"&&Ta)||function(){return this}()||Ta||Function("return this")(),kn=typeof document=="object"&&document.all,Uc=typeof kn=="undefined"&&kn!==void 0,wu={all:kn,IS_HTMLDDA:Uc},ku=wu,Vc=ku.all,Re=ku.IS_HTMLDDA?function(s){return typeof s=="function"||s===Vc}:function(s){return typeof s=="function"},Hc=Ve,Gc=Re,Io=Hc.WeakMap,jc=Gc(Io)&&/native code/.test(String(Io)),Ro=Re,_u=wu,Yc=_u.all,ei=_u.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:Ro(s)||s===Yc}:function(s){return typeof s=="object"?s!==null:Ro(s)},zc=bt,hi=!zc(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Oi={},qc=Ve,Lo=ei,_n=qc.document,Wc=Lo(_n)&&Lo(_n.createElement),eo=function(s){return Wc?_n.createElement(s):{}},Qc=hi,Kc=bt,Jc=eo,Pu=!Qc&&!Kc(function(){return Object.defineProperty(Jc("div"),"a",{get:function(){return 7}}).a!=7}),Xc=hi,Zc=bt,Du=Xc&&Zc(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),eh=ei,th=String,ih=TypeError,ti=function(s){if(eh(s))return s;throw ih(th(s)+" is not an object")},sh=qr,tr=Function.prototype.call,ct=sh?tr.bind(tr):function(){return tr.apply(tr,arguments)},to={},$a=to,Aa=Ve,rh=Re,xo=function(s){return rh(s)?s:void 0},Bi=function(s,e){return arguments.length<2?xo($a[s])||xo(Aa[s]):$a[s]&&$a[s][e]||Aa[s]&&Aa[s][e]},ah=yt,Wr=ah({}.isPrototypeOf),Qr=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Iu=Ve,wa=Qr,Co=Iu.process,Oo=Iu.Deno,Bo=Co&&Co.versions||Oo&&Oo.version,Mo=Bo&&Bo.v8,wt,Pr;Mo&&(wt=Mo.split("."),Pr=wt[0]>0&&wt[0]<4?1:+(wt[0]+wt[1]));!Pr&&wa&&(wt=wa.match(/Edge\/(\d+)/),(!wt||wt[1]>=74)&&(wt=wa.match(/Chrome\/(\d+)/),wt&&(Pr=+wt[1])));var Ru=Pr,No=Ru,nh=bt,oh=Ve,dh=oh.String,Lu=!!Object.getOwnPropertySymbols&&!nh(function(){var s=Symbol();return!dh(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&No&&No<41}),uh=Lu,xu=uh&&!Symbol.sham&&typeof Symbol.iterator=="symbol",lh=Bi,ch=Re,hh=Wr,fh=xu,ph=Object,Cu=fh?function(s){return typeof s=="symbol"}:function(s){var e=lh("Symbol");return ch(e)&&hh(e.prototype,ph(s))},mh=String,Kr=function(s){try{return mh(s)}catch(e){return"Object"}},vh=Re,gh=Kr,Sh=TypeError,Mi=function(s){if(vh(s))return s;throw Sh(gh(s)+" is not a function")},bh=Mi,yh=Gs,Jr=function(s,e){var t=s[e];return yh(t)?void 0:bh(t)},ka=ct,_a=Re,Pa=ei,Th=TypeError,Eh=function(s,e){var t,i;if(e==="string"&&_a(t=s.toString)&&!Pa(i=ka(t,s))||_a(t=s.valueOf)&&!Pa(i=ka(t,s))||e!=="string"&&_a(t=s.toString)&&!Pa(i=ka(t,s)))return i;throw Th("Can't convert object to primitive value")},Ou={exports:{}},$h=!0,Fo=Ve,Ah=Object.defineProperty,wh=function(s,e){try{Ah(Fo,s,{value:e,configurable:!0,writable:!0})}catch(t){Fo[s]=e}return e},kh=Ve,_h=wh,Uo="__core-js_shared__",Ph=kh[Uo]||_h(Uo,{}),io=Ph,Vo=io;(Ou.exports=function(s,e){return Vo[s]||(Vo[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 Bu=Ou.exports,Dh=Zn,Ih=Object,Xr=function(s){return Ih(Dh(s))},Rh=yt,Lh=Xr,xh=Rh({}.hasOwnProperty),Mt=Object.hasOwn||function(e,t){return xh(Lh(e),t)},Ch=yt,Oh=0,Bh=Math.random(),Mh=Ch(1 .toString),Mu=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Mh(++Oh+Bh,36)},Nh=Ve,Fh=Bu,Ho=Mt,Uh=Mu,Vh=Lu,Hh=xu,Ki=Nh.Symbol,Da=Fh("wks"),Gh=Hh?Ki.for||Ki:Ki&&Ki.withoutSetter||Uh,Ke=function(s){return Ho(Da,s)||(Da[s]=Vh&&Ho(Ki,s)?Ki[s]:Gh("Symbol."+s)),Da[s]},jh=ct,Go=ei,jo=Cu,Yh=Jr,zh=Eh,qh=Ke,Wh=TypeError,Qh=qh("toPrimitive"),Kh=function(s,e){if(!Go(s)||jo(s))return s;var t=Yh(s,Qh),i;if(t){if(e===void 0&&(e="default"),i=jh(t,s,e),!Go(i)||jo(i))return i;throw Wh("Can't convert object to primitive value")}return e===void 0&&(e="number"),zh(s,e)},Jh=Kh,Xh=Cu,so=function(s){var e=Jh(s,"string");return Xh(e)?e:e+""},Zh=hi,ef=Pu,tf=Du,ir=ti,Yo=so,sf=TypeError,Ia=Object.defineProperty,rf=Object.getOwnPropertyDescriptor,Ra="enumerable",La="configurable",xa="writable";Oi.f=Zh?tf?function(e,t,i){if(ir(e),t=Yo(t),ir(i),typeof e=="function"&&t==="prototype"&&"value"in i&&xa in i&&!i[xa]){var r=rf(e,t);r&&r[xa]&&(e[t]=i.value,i={configurable:La in i?i[La]:r[La],enumerable:Ra in i?i[Ra]:r[Ra],writable:!1})}return Ia(e,t,i)}:Ia:function(e,t,i){if(ir(e),t=Yo(t),ir(i),ef)try{return Ia(e,t,i)}catch(r){}if("get"in i||"set"in i)throw sf("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Zr=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},af=hi,nf=Oi,of=Zr,Ys=af?function(s,e,t){return nf.f(s,e,of(1,t))}:function(s,e,t){return s[e]=t,s},df=Bu,uf=Mu,zo=df("keys"),ro=function(s){return zo[s]||(zo[s]=uf(s))},ao={},lf=jc,Nu=Ve,cf=ei,hf=Ys,Ca=Mt,Oa=io,ff=ro,pf=ao,qo="Object already initialized",Pn=Nu.TypeError,mf=Nu.WeakMap,Dr,Ns,Ir,vf=function(s){return Ir(s)?Ns(s):Dr(s,{})},gf=function(s){return function(e){var t;if(!cf(e)||(t=Ns(e)).type!==s)throw Pn("Incompatible receiver, "+s+" required");return t}};if(lf||Oa.state){var It=Oa.state||(Oa.state=new mf);It.get=It.get,It.has=It.has,It.set=It.set,Dr=function(s,e){if(It.has(s))throw Pn(qo);return e.facade=s,It.set(s,e),e},Ns=function(s){return It.get(s)||{}},Ir=function(s){return It.has(s)}}else{var Hi=ff("state");pf[Hi]=!0,Dr=function(s,e){if(Ca(s,Hi))throw Pn(qo);return e.facade=s,hf(s,Hi,e),e},Ns=function(s){return Ca(s,Hi)?s[Hi]:{}},Ir=function(s){return Ca(s,Hi)}}var Fu={set:Dr,get:Ns,has:Ir,enforce:vf,getterFor:gf},Sf=qr,Uu=Function.prototype,Wo=Uu.apply,Qo=Uu.call,Vu=typeof Reflect=="object"&&Reflect.apply||(Sf?Qo.bind(Wo):function(){return Qo.apply(Wo,arguments)}),bf=Hs,yf=yt,Hu=function(s){if(bf(s)==="Function")return yf(s)},no={},Gu={},ju={}.propertyIsEnumerable,Yu=Object.getOwnPropertyDescriptor,Tf=Yu&&!ju.call({1:2},1);Gu.f=Tf?function(e){var t=Yu(this,e);return!!t&&t.enumerable}:ju;var Ef=hi,$f=ct,Af=Gu,wf=Zr,kf=js,_f=so,Pf=Mt,Df=Pu,Ko=Object.getOwnPropertyDescriptor;no.f=Ef?Ko:function(e,t){if(e=kf(e),t=_f(t),Df)try{return Ko(e,t)}catch(i){}if(Pf(e,t))return wf(!$f(Af.f,e,t),e[t])};var If=bt,Rf=Re,Lf=/#|\.prototype\./,zs=function(s,e){var t=Cf[xf(s)];return t==Bf?!0:t==Of?!1:Rf(e)?If(e):!!e},xf=zs.normalize=function(s){return String(s).replace(Lf,".").toLowerCase()},Cf=zs.data={},Of=zs.NATIVE="N",Bf=zs.POLYFILL="P",zu=zs,Jo=Hu,Mf=Mi,Nf=qr,Ff=Jo(Jo.bind),ea=function(s,e){return Mf(s),e===void 0?s:Nf?Ff(s,e):function(){return s.apply(e,arguments)}},sr=Ve,Uf=Vu,Vf=Hu,Hf=Re,Gf=no.f,jf=zu,Gi=to,Yf=ea,ji=Ys,Xo=Mt,zf=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 Uf(s,this,arguments)};return e.prototype=s.prototype,e},_t=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?sr:r?sr[t]:(sr[t]||{}).prototype,o=i?Gi:Gi[t]||ji(Gi,t,{})[t],u=o.prototype,d,l,c,h,f,p,S,b,g;for(h in e)d=jf(i?h:t+(r?".":"#")+h,s.forced),l=!d&&n&&Xo(n,h),p=o[h],l&&(s.dontCallGetSet?(g=Gf(n,h),S=g&&g.value):S=n[h]),f=l&&S?S:e[h],!(l&&typeof p==typeof f)&&(s.bind&&l?b=Yf(f,sr):s.wrap&&l?b=zf(f):a&&Hf(f)?b=Vf(f):b=f,(s.sham||f&&f.sham||p&&p.sham)&&ji(b,"sham",!0),ji(o,h,b),a&&(c=t+"Prototype",Xo(Gi,c)||ji(Gi,c,{}),ji(Gi[c],h,f),s.real&&u&&(d||!u[h])&&ji(u,h,f)))},Dn=hi,qf=Mt,qu=Function.prototype,Wf=Dn&&Object.getOwnPropertyDescriptor,oo=qf(qu,"name"),Qf=oo&&function(){}.name==="something",Kf=oo&&(!Dn||Dn&&Wf(qu,"name").configurable),Jf={EXISTS:oo,PROPER:Qf,CONFIGURABLE:Kf},Wu={},Xf=Math.ceil,Zf=Math.floor,ep=Math.trunc||function(e){var t=+e;return(t>0?Zf:Xf)(t)},tp=ep,uo=function(s){var e=+s;return e!==e||e===0?0:tp(e)},ip=uo,sp=Math.max,rp=Math.min,ap=function(s,e){var t=ip(s);return t<0?sp(t+e,0):rp(t,e)},np=uo,op=Math.min,dp=function(s){return s>0?op(np(s),9007199254740991):0},up=dp,lo=function(s){return up(s.length)},lp=js,cp=ap,hp=lo,Zo=function(s){return function(e,t,i){var r=lp(e),a=hp(r),n=cp(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}},fp={includes:Zo(!0),indexOf:Zo(!1)},pp=yt,Ba=Mt,mp=js,vp=fp.indexOf,gp=ao,ed=pp([].push),Sp=function(s,e){var t=mp(s),i=0,r=[],a;for(a in t)!Ba(gp,a)&&Ba(t,a)&&ed(r,a);for(;e.length>i;)Ba(t,a=e[i++])&&(~vp(r,a)||ed(r,a));return r},Qu=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],bp=Sp,yp=Qu,Tp=Object.keys||function(e){return bp(e,yp)},Ep=hi,$p=Du,Ap=Oi,wp=ti,kp=js,_p=Tp;Wu.f=Ep&&!$p?Object.defineProperties:function(e,t){wp(e);for(var i=kp(t),r=_p(t),a=r.length,n=0,o;a>n;)Ap.f(e,o=r[n++],i[o]);return e};var Pp=Bi,Ku=Pp("document","documentElement"),Dp=ti,Ip=Wu,td=Qu,Rp=ao,Lp=Ku,xp=eo,Cp=ro,id=">",sd="<",In="prototype",Rn="script",Ju=Cp("IE_PROTO"),Ma=function(){},Xu=function(s){return sd+Rn+id+s+sd+"/"+Rn+id},rd=function(s){s.write(Xu("")),s.close();var e=s.parentWindow.Object;return s=null,e},Op=function(){var s=xp("iframe"),e="java"+Rn+":",t;return s.style.display="none",Lp.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Xu("document.F=Object")),t.close(),t.F},rr,Ar=function(){try{rr=new ActiveXObject("htmlfile")}catch(e){}Ar=typeof document!="undefined"?document.domain&&rr?rd(rr):Op():rd(rr);for(var s=td.length;s--;)delete Ar[In][td[s]];return Ar()};Rp[Ju]=!0;var Zu=Object.create||function(e,t){var i;return e!==null?(Ma[In]=Dp(e),i=new Ma,Ma[In]=null,i[Ju]=e):i=Ar(),t===void 0?i:Ip.f(i,t)},Bp=bt,Mp=!Bp(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),Np=Mt,Fp=Re,Up=Xr,Vp=ro,Hp=Mp,ad=Vp("IE_PROTO"),Ln=Object,Gp=Ln.prototype,el=Hp?Ln.getPrototypeOf:function(s){var e=Up(s);if(Np(e,ad))return e[ad];var t=e.constructor;return Fp(t)&&e instanceof t?t.prototype:e instanceof Ln?Gp:null},jp=Ys,co=function(s,e,t,i){return i&&i.enumerable?s[e]=t:jp(s,e,t),s},Yp=bt,zp=Re,qp=ei,Wp=Zu,nd=el,Qp=co,Kp=Ke,xn=Kp("iterator"),tl=!1,Jt,Na,Fa;[].keys&&(Fa=[].keys(),"next"in Fa?(Na=nd(nd(Fa)),Na!==Object.prototype&&(Jt=Na)):tl=!0);var Jp=!qp(Jt)||Yp(function(){var s={};return Jt[xn].call(s)!==s});Jp?Jt={}:Jt=Wp(Jt);zp(Jt[xn])||Qp(Jt,xn,function(){return this});var il={IteratorPrototype:Jt,BUGGY_SAFARI_ITERATORS:tl},Xp=Ke,Zp=Xp("toStringTag"),sl={};sl[Zp]="z";var ho=String(sl)==="[object z]",em=ho,tm=Re,wr=Hs,im=Ke,sm=im("toStringTag"),rm=Object,am=wr(function(){return arguments}())=="Arguments",nm=function(s,e){try{return s[e]}catch(t){}},qs=em?wr:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=nm(e=rm(s),sm))=="string"?t:am?wr(e):(i=wr(e))=="Object"&&tm(e.callee)?"Arguments":i},om=ho,dm=qs,um=om?{}.toString:function(){return"[object "+dm(this)+"]"},lm=ho,cm=Oi.f,hm=Ys,fm=Mt,pm=um,mm=Ke,od=mm("toStringTag"),fo=function(s,e,t,i){if(s){var r=t?s:s.prototype;fm(r,od)||cm(r,od,{configurable:!0,value:e}),i&&!lm&&hm(r,"toString",pm)}},vm=il.IteratorPrototype,gm=Zu,Sm=Zr,bm=fo,ym=us,Tm=function(){return this},Em=function(s,e,t,i){var r=e+" Iterator";return s.prototype=gm(vm,{next:Sm(+!i,t)}),bm(s,r,!1,!0),ym[r]=Tm,s},$m=_t,Am=ct,rl=Jf,wm=Em,km=el,_m=fo,dd=co,Pm=Ke,ud=us,al=il,Dm=rl.PROPER;rl.CONFIGURABLE;al.IteratorPrototype;var ar=al.BUGGY_SAFARI_ITERATORS,Ua=Pm("iterator"),ld="keys",nr="values",cd="entries",Im=function(){return this},Rm=function(s,e,t,i,r,a,n){wm(t,e,i);var o=function(g){if(g===r&&h)return h;if(!ar&&g in l)return l[g];switch(g){case ld:return function(){return new t(this,g)};case nr:return function(){return new t(this,g)};case cd:return function(){return new t(this,g)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,l=s.prototype,c=l[Ua]||l["@@iterator"]||r&&l[r],h=!ar&&c||o(r),f=e=="Array"&&l.entries||c,p,S,b;if(f&&(p=km(f.call(new s)),p!==Object.prototype&&p.next&&(_m(p,u,!0,!0),ud[u]=Im)),Dm&&r==nr&&c&&c.name!==nr&&(d=!0,h=function(){return Am(c,this)}),r)if(S={values:o(nr),keys:a?h:o(ld),entries:o(cd)},n)for(b in S)(ar||d||!(b in l))&&dd(l,b,S[b]);else $m({target:e,proto:!0,forced:ar||d},S);return n&&l[Ua]!==h&&dd(l,Ua,h,{name:r}),ud[e]=h,S},Lm=function(s,e){return{value:s,done:e}},xm=js,hd=us,nl=Fu;Oi.f;var Cm=Rm,or=Lm,ol="Array Iterator",Om=nl.set,Bm=nl.getterFor(ol);Cm(Array,"Array",function(s,e){Om(this,{type:ol,target:xm(s),index:0,kind:e})},function(){var s=Bm(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,or(void 0,!0)):t=="keys"?or(i,!1):t=="values"?or(e[i],!1):or([i,e[i]],!1)},"values");hd.Arguments=hd.Array;var Mm=Ke,Nm=us,Fm=Mm("iterator"),Um=Array.prototype,Vm=function(s){return s!==void 0&&(Nm.Array===s||Um[Fm]===s)},Hm=qs,fd=Jr,Gm=Gs,jm=us,Ym=Ke,zm=Ym("iterator"),dl=function(s){if(!Gm(s))return fd(s,zm)||fd(s,"@@iterator")||jm[Hm(s)]},qm=ct,Wm=Mi,Qm=ti,Km=Kr,Jm=dl,Xm=TypeError,Zm=function(s,e){var t=arguments.length<2?Jm(s):e;if(Wm(t))return Qm(qm(t,s));throw Xm(Km(s)+" is not iterable")},ev=ct,pd=ti,tv=Jr,iv=function(s,e,t){var i,r;pd(s);try{if(i=tv(s,"return"),!i){if(e==="throw")throw t;return t}i=ev(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return pd(i),t},sv=ea,rv=ct,av=ti,nv=Kr,ov=Vm,dv=lo,md=Wr,uv=Zm,lv=dl,vd=iv,cv=TypeError,kr=function(s,e){this.stopped=s,this.result=e},gd=kr.prototype,po=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=sv(e,i),d,l,c,h,f,p,S,b=function(y){return d&&vd(d,"normal",y),new kr(!0,y)},g=function(y){return r?(av(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=lv(s),!l)throw cv(nv(s)+" is not iterable");if(ov(l)){for(c=0,h=dv(s);h>c;c++)if(f=g(s[c]),f&&md(gd,f))return f;return new kr(!1)}d=uv(s,l)}for(p=a?s.next:d.next;!(S=rv(p,d)).done;){try{f=g(S.value)}catch(y){vd(d,"throw",y)}if(typeof f=="object"&&f&&md(gd,f))return f}return new kr(!1)},hv=so,fv=Oi,pv=Zr,mv=function(s,e,t){var i=hv(e);i in s?fv.f(s,i,pv(0,t)):s[i]=t},vv=_t,gv=po,Sv=mv;vv({target:"Object",stat:!0},{fromEntries:function(e){var t={};return gv(e,function(i,r){Sv(t,i,r)},{AS_ENTRIES:!0}),t}});var bv=to,yv=bv.Object.fromEntries,Tv={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},Ev=Tv,$v=Ve,Av=qs,wv=Ys,Sd=us,kv=Ke,bd=kv("toStringTag");for(var Va in Ev){var yd=$v[Va],Ha=yd&&yd.prototype;Ha&&Av(Ha)!==bd&&wv(Ha,bd,Va),Sd[Va]=Sd.Array}var _v=yv,Pv=_v,Dv=Pv,Iv=Dv,Li=zr(Iv),Rv=Hs,ta=typeof process!="undefined"&&Rv(process)=="process",Lv=Oi,xv=function(s,e,t){return Lv.f(s,e,t)},Cv=Bi,Ov=xv,Bv=Ke,Mv=hi,Td=Bv("species"),Nv=function(s){var e=Cv(s);Mv&&e&&!e[Td]&&Ov(e,Td,{configurable:!0,get:function(){return this}})},Fv=Wr,Uv=TypeError,Vv=function(s,e){if(Fv(e,s))return s;throw Uv("Incorrect invocation")},Hv=yt,Gv=Re,Cn=io,jv=Hv(Function.toString);Gv(Cn.inspectSource)||(Cn.inspectSource=function(s){return jv(s)});var ul=Cn.inspectSource,Yv=yt,zv=bt,ll=Re,qv=qs,Wv=Bi,Qv=ul,cl=function(){},Kv=[],hl=Wv("Reflect","construct"),mo=/^\s*(?:class|function)\b/,Jv=Yv(mo.exec),Xv=!mo.exec(cl),As=function(e){if(!ll(e))return!1;try{return hl(cl,Kv,e),!0}catch(t){return!1}},fl=function(e){if(!ll(e))return!1;switch(qv(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Xv||!!Jv(mo,Qv(e))}catch(t){return!0}};fl.sham=!0;var Zv=!hl||zv(function(){var s;return As(As.call)||!As(Object)||!As(function(){s=!0})||s})?fl:As,eg=Zv,tg=Kr,ig=TypeError,sg=function(s){if(eg(s))return s;throw ig(tg(s)+" is not a constructor")},Ed=ti,rg=sg,ag=Gs,ng=Ke,og=ng("species"),pl=function(s,e){var t=Ed(s).constructor,i;return t===void 0||ag(i=Ed(t)[og])?e:rg(i)},dg=yt,ug=dg([].slice),lg=TypeError,cg=function(s,e){if(s<e)throw lg("Not enough arguments");return s},hg=Qr,ml=/(?:ipad|iphone|ipod).*applewebkit/i.test(hg),ut=Ve,fg=Vu,pg=ea,$d=Re,mg=Mt,vl=bt,Ad=Ku,vg=ug,wd=eo,gg=cg,Sg=ml,bg=ta,On=ut.setImmediate,Bn=ut.clearImmediate,yg=ut.process,Ga=ut.Dispatch,Tg=ut.Function,kd=ut.MessageChannel,Eg=ut.String,ja=0,xs={},_d="onreadystatechange",Fs,wi,Ya,za;vl(function(){Fs=ut.location});var vo=function(s){if(mg(xs,s)){var e=xs[s];delete xs[s],e()}},qa=function(s){return function(){vo(s)}},Pd=function(s){vo(s.data)},Dd=function(s){ut.postMessage(Eg(s),Fs.protocol+"//"+Fs.host)};(!On||!Bn)&&(On=function(e){gg(arguments.length,1);var t=$d(e)?e:Tg(e),i=vg(arguments,1);return xs[++ja]=function(){fg(t,void 0,i)},wi(ja),ja},Bn=function(e){delete xs[e]},bg?wi=function(s){yg.nextTick(qa(s))}:Ga&&Ga.now?wi=function(s){Ga.now(qa(s))}:kd&&!Sg?(Ya=new kd,za=Ya.port2,Ya.port1.onmessage=Pd,wi=pg(za.postMessage,za)):ut.addEventListener&&$d(ut.postMessage)&&!ut.importScripts&&Fs&&Fs.protocol!=="file:"&&!vl(Dd)?(wi=Dd,ut.addEventListener("message",Pd,!1)):_d in wd("script")?wi=function(s){Ad.appendChild(wd("script"))[_d]=function(){Ad.removeChild(this),vo(s)}}:wi=function(s){setTimeout(qa(s),0)});var gl={set:On,clear:Bn},Sl=function(){this.head=null,this.tail=null};Sl.prototype={add:function(s){var e={item:s,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var s=this.head;if(s){var e=this.head=s.next;return e===null&&(this.tail=null),s.item}}};var bl=Sl,$g=Qr,Ag=/ipad|iphone|ipod/i.test($g)&&typeof Pebble!="undefined",wg=Qr,kg=/web0s(?!.*chrome)/i.test(wg),xi=Ve,Id=ea,_g=no.f,Wa=gl.set,Pg=bl,Dg=ml,Ig=Ag,Rg=kg,Qa=ta,Rd=xi.MutationObserver||xi.WebKitMutationObserver,Ld=xi.document,xd=xi.process,dr=xi.Promise,Cd=_g(xi,"queueMicrotask"),Mn=Cd&&Cd.value,Yi,Ka,Ja,ur,Od;if(!Mn){var lr=new Pg,cr=function(){var s,e;for(Qa&&(s=xd.domain)&&s.exit();e=lr.get();)try{e()}catch(t){throw lr.head&&Yi(),t}s&&s.enter()};!Dg&&!Qa&&!Rg&&Rd&&Ld?(Ka=!0,Ja=Ld.createTextNode(""),new Rd(cr).observe(Ja,{characterData:!0}),Yi=function(){Ja.data=Ka=!Ka}):!Ig&&dr&&dr.resolve?(ur=dr.resolve(void 0),ur.constructor=dr,Od=Id(ur.then,ur),Yi=function(){Od(cr)}):Qa?Yi=function(){xd.nextTick(cr)}:(Wa=Id(Wa,xi),Yi=function(){Wa(cr)}),Mn=function(s){lr.head||Yi(),lr.add(s)}}var Lg=Mn,xg=function(s,e){try{arguments.length==1?console.error(s):console.error(s,e)}catch(t){}},go=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}},Cg=Ve,ls=Cg.Promise,yl=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",Og=yl,Bg=ta,Mg=!Og&&!Bg&&typeof window=="object"&&typeof document=="object",Ng=Ve,Cs=ls,Fg=Re,Ug=zu,Vg=ul,Hg=Ke,Gg=Mg,jg=yl,Xa=Ru,Bd=Cs&&Cs.prototype,Yg=Hg("species"),Nn=!1,Tl=Fg(Ng.PromiseRejectionEvent),zg=Ug("Promise",function(){var s=Vg(Cs),e=s!==String(Cs);if(!e&&Xa===66||!(Bd.catch&&Bd.finally))return!0;if(!Xa||Xa<51||!/native code/.test(s)){var t=new Cs(function(a){a(1)}),i=function(a){a(function(){},function(){})},r=t.constructor={};if(r[Yg]=i,Nn=t.then(function(){})instanceof i,!Nn)return!0}return!e&&(Gg||jg)&&!Tl}),Ws={CONSTRUCTOR:zg,REJECTION_EVENT:Tl,SUBCLASSING:Nn},cs={},Md=Mi,qg=TypeError,Wg=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw qg("Bad Promise constructor");e=i,t=r}),this.resolve=Md(e),this.reject=Md(t)};cs.f=function(s){return new Wg(s)};var Qg=_t,Rr=ta,ui=Ve,Qs=ct,Kg=co,Jg=fo,Xg=Nv,Zg=Mi,Fn=Re,eS=ei,tS=Vv,iS=pl,El=gl.set,So=Lg,sS=xg,rS=go,aS=bl,$l=Fu,Un=ls,bo=Ws,Al=cs,ia="Promise",wl=bo.CONSTRUCTOR,nS=bo.REJECTION_EVENT;bo.SUBCLASSING;var Za=$l.getterFor(ia),oS=$l.set,dS=Un&&Un.prototype,Ji=Un,en=dS,kl=ui.TypeError,Vn=ui.document,yo=ui.process,Hn=Al.f,uS=Hn,lS=!!(Vn&&Vn.createEvent&&ui.dispatchEvent),_l="unhandledrejection",cS="rejectionhandled",Nd=0,Pl=1,hS=2,To=1,Dl=2,hr,Fd,fS,Il=function(s){var e;return eS(s)&&Fn(e=s.then)?e:!1},Rl=function(s,e){var t=e.value,i=e.state==Pl,r=i?s.ok:s.fail,a=s.resolve,n=s.reject,o=s.domain,u,d,l;try{r?(i||(e.rejection===Dl&&mS(e),e.rejection=To),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),l=!0)),u===s.promise?n(kl("Promise-chain cycle")):(d=Il(u))?Qs(d,u,a,n):a(u)):n(t)}catch(c){o&&!l&&o.exit(),n(c)}},Ll=function(s,e){s.notified||(s.notified=!0,So(function(){for(var t=s.reactions,i;i=t.get();)Rl(i,s);s.notified=!1,e&&!s.rejection&&pS(s)}))},xl=function(s,e,t){var i,r;lS?(i=Vn.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),ui.dispatchEvent(i)):i={promise:e,reason:t},!nS&&(r=ui["on"+s])?r(i):s===_l&&sS("Unhandled promise rejection",t)},pS=function(s){Qs(El,ui,function(){var e=s.facade,t=s.value,i=Ud(s),r;if(i&&(r=rS(function(){Rr?yo.emit("unhandledRejection",t,e):xl(_l,e,t)}),s.rejection=Rr||Ud(s)?Dl:To,r.error))throw r.value})},Ud=function(s){return s.rejection!==To&&!s.parent},mS=function(s){Qs(El,ui,function(){var e=s.facade;Rr?yo.emit("rejectionHandled",e):xl(cS,e,s.value)})},Xi=function(s,e,t){return function(i){s(e,i,t)}},is=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=hS,Ll(s,!0))},Gn=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw kl("Promise can't be resolved itself");var i=Il(e);i?So(function(){var r={done:!1};try{Qs(i,e,Xi(Gn,r,s),Xi(is,r,s))}catch(a){is(r,a,s)}}):(s.value=e,s.state=Pl,Ll(s,!1))}catch(r){is({done:!1},r,s)}}};wl&&(Ji=function(e){tS(this,en),Zg(e),Qs(hr,this);var t=Za(this);try{e(Xi(Gn,t),Xi(is,t))}catch(i){is(t,i)}},en=Ji.prototype,hr=function(e){oS(this,{type:ia,done:!1,notified:!1,parent:!1,reactions:new aS,rejection:!1,state:Nd,value:void 0})},hr.prototype=Kg(en,"then",function(e,t){var i=Za(this),r=Hn(iS(this,Ji));return i.parent=!0,r.ok=Fn(e)?e:!0,r.fail=Fn(t)&&t,r.domain=Rr?yo.domain:void 0,i.state==Nd?i.reactions.add(r):So(function(){Rl(r,i)}),r.promise}),Fd=function(){var s=new hr,e=Za(s);this.promise=s,this.resolve=Xi(Gn,e),this.reject=Xi(is,e)},Al.f=Hn=function(s){return s===Ji||s===fS?new Fd(s):uS(s)});Qg({global:!0,constructor:!0,wrap:!0,forced:wl},{Promise:Ji});Jg(Ji,ia,!1,!0);Xg(ia);var vS=Ke,Cl=vS("iterator"),Ol=!1;try{var gS=0,Vd={next:function(){return{done:!!gS++}},return:function(){Ol=!0}};Vd[Cl]=function(){return this},Array.from(Vd,function(){throw 2})}catch(s){}var SS=function(s,e){if(!e&&!Ol)return!1;var t=!1;try{var i={};i[Cl]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t},bS=ls,yS=SS,TS=Ws.CONSTRUCTOR,Bl=TS||!yS(function(s){bS.all(s).then(void 0,function(){})}),ES=_t,$S=ct,AS=Mi,wS=cs,kS=go,_S=po,PS=Bl;ES({target:"Promise",stat:!0,forced:PS},{all:function(e){var t=this,i=wS.f(t),r=i.resolve,a=i.reject,n=kS(function(){var o=AS(t.resolve),u=[],d=0,l=1;_S(e,function(c){var h=d++,f=!1;l++,$S(o,t,c).then(function(p){f||(f=!0,u[h]=p,--l||r(u))},a)}),--l||r(u)});return n.error&&a(n.value),i.promise}});var DS=_t,IS=Ws.CONSTRUCTOR,Hd=ls;Hd&&Hd.prototype;DS({target:"Promise",proto:!0,forced:IS,real:!0},{catch:function(s){return this.then(void 0,s)}});var RS=_t,LS=ct,xS=Mi,CS=cs,OS=go,BS=po,MS=Bl;RS({target:"Promise",stat:!0,forced:MS},{race:function(e){var t=this,i=CS.f(t),r=i.reject,a=OS(function(){var n=xS(t.resolve);BS(e,function(o){LS(n,t,o).then(i.resolve,r)})});return a.error&&r(a.value),i.promise}});var NS=_t,FS=ct,US=cs,VS=Ws.CONSTRUCTOR;NS({target:"Promise",stat:!0,forced:VS},{reject:function(e){var t=US.f(this);return FS(t.reject,void 0,e),t.promise}});var HS=ti,GS=ei,jS=cs,Ml=function(s,e){if(HS(s),GS(e)&&e.constructor===s)return e;var t=jS.f(s),i=t.resolve;return i(e),t.promise},YS=_t,zS=Bi,qS=$h,WS=ls,QS=Ws.CONSTRUCTOR,KS=Ml,JS=zS("Promise"),XS=!QS;YS({target:"Promise",stat:!0,forced:qS},{resolve:function(e){return KS(XS&&this===JS?WS:this,e)}});var ZS=_t,jn=ls,eb=bt,tb=Bi,ib=Re,sb=pl,Gd=Ml,rb=jn&&jn.prototype,ab=!!jn&&eb(function(){rb.finally.call({then:function(){}},function(){})});ZS({target:"Promise",proto:!0,real:!0,forced:ab},{finally:function(s){var e=sb(this,tb("Promise")),t=ib(s);return this.then(t?function(i){return Gd(e,s()).then(function(){return i})}:s,t?function(i){return Gd(e,s()).then(function(){throw i})}:s)}});var nb=Bi,Eo=nb,ob=Eo,db=ob("Promise","finally"),ub=db,lb=ub,cb=lb,hb=cb,Ks=zr(hb),Te;(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"})(Te||(Te={}));var qe=(s,e=0,t=Te.OFFSET_P)=>{switch(t){case Te.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Te.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case Te.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 Lr=(s,e)=>{var t;switch(e){case Te.OFFSET_P:return NaN;case Te.PLAYBACK_SHIFT:{const i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case Te.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 L=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};class me{constructor(e){this.transitionStarted$=new O,this.transitionEnded$=new O,this.transitionUpdated$=new O,this.forceChanged$=new O,this.stateChangeStarted$=G(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=G(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||I(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 fb=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 ee;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(ee||(ee={}));const pb=5,mb=5,vb=500,jd=7e3;class gb{constructor(e){this.subscription=new ce,this.loadMediaTimeoutSubscription=new ce,this.videoState=new me(ee.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===m.STOPPED){i!==ee.STOPPED&&(this.videoState.startTransitionTo(ee.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==m.PAUSED&&o.state===ie.Requested&&i!==ee.STOPPED){this.seek(o.position/1e3);return}switch(a){case m.READY:{switch(i){case ee.PLAYING:case ee.PAUSED:case ee.READY:break;case ee.STOPPED:this.videoState.startTransitionTo(ee.READY),this.prepare();break;default:z(i)}break}case m.PLAYING:{switch(i){case ee.PLAYING:break;case ee.PAUSED:this.videoState.startTransitionTo(ee.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case ee.READY:this.videoState.startTransitionTo(ee.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case ee.STOPPED:this.videoState.startTransitionTo(ee.READY),this.prepare();break;default:z(i)}break}case m.PAUSED:{switch(i){case ee.PLAYING:this.videoState.startTransitionTo(ee.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case ee.PAUSED:break;case ee.READY:this.videoState.startTransitionTo(ee.PAUSED),this.videoState.setState(ee.PAUSED);break;case ee.STOPPED:this.videoState.startTransitionTo(ee.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(fb(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 ce;this.subscription.add(e),this.subscription.add(G(this.videoState.stateChangeStarted$.pipe(P(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(P(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 O;e.add(r.pipe(lt(vb)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(V(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===ie.Applying||Math.abs(o-a)>pb)&&r.next(o),a=o})),e.add(V(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(V(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(V(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(V(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<mb&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),L(this.params.desiredState.playbackState,m.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(V(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(V(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const i=G(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,We(["init"])).pipe(lt(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(ee.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED)):(this.videoState.setState(ee.PLAYING),L(this.params.desiredState.playbackState,m.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:ie.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)===ee.PAUSED||e===ee.PLAYING)&&(this.videoState.setState(ee.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===ee.PLAYING||e===ee.PAUSED)&&(this.videoState.setState(ee.PLAYING),L(this.params.desiredState.playbackState,m.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===ee.READY&&this.videoState.setState(ee.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===m.READY&&L(this.params.desiredState.playbackState,m.READY)}handleRemoteStop(){this.videoState.getState()!==ee.STOPPED&&this.videoState.setState(ee.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];D(l);const c=fc(Object.keys(l));D(c);const h=l[c];D(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case A.HLS:case A.HLS_ONDEMAND:{const l=i[e];D(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];D(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case A.DASH_LIVE_CMAF:{const l=i[e];D(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];D(l),r=qe(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 I(u)&&(o.metadata.title=u),I(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===ie.Applying||i.state===ie.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(pc(jd).subscribe(()=>a(`timeout(${jd})`)))});Ks(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===ie.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})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}var Sb=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)},bb=s=>{const e=new T(1/0),t=new O,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,p,S;const b=Li(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;I($)&&!isNaN($)&&e.next($)}const g=(p=b["x-delivery-type"])!==null&&p!==void 0?p:Ms.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,p=h.progress;h.onload=function(...S){return u(this),f(...S)},h.progress=function(...S){return d(this),p(...S)},o()}return c(h)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:i}},li=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},yb=s=>s.extend("RequestModifier",()=>({modifyRequestURL:li}),!0),Tb=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 kt=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=s.getState(),o=e(),u=W(r),d=new ce;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},fi=(s,e,t)=>kt(e,()=>s.loop,i=>{I(i)&&(s.loop=i)},{onError:t}),Nt=(s,e,t,i)=>kt(e,()=>({muted:s.muted,volume:s.volume}),r=>{I(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}),ii=(s,e,t,i)=>kt(e,()=>s.playbackRate,r=>{I(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Eb=s=>["__",s.language,s.label].join("|"),$b=(s,e)=>{if(s.id===e)return!0;const[t,i,r]=e.split("|");return s.language===i&&s.label===r};class Pt{constructor(){this.available$=new O,this.current$=new T(void 0),this.error$=new O,this.subscription=new ce,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(kt(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{I(a)&&this.setInternal(a)},{equal:(a,n)=>I(a)&&I(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(P(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(kt(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{I(a)&&this.setExternal(a)},{equal:(a,n)=>I(a)&&I(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(P(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(kt(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(kt(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){D(this.video);const{textTracks:e}=this.video;this.subscription.add(V(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(G(V(e,"addtrack"),V(e,"removetrack"),We(["init"])).pipe(P(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),ye((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(G(V(e,"change"),We(["init"])).pipe(P(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),P(i=>i&&this.htmlTextTrackToITextTrack(i).id),ye()).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(V(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(V(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;I(t.align)&&(r.align=t.align),I(t.position)&&(r.position=t.position),I(t.size)&&(r.size=t.size),I(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){D(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Pt.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,i;const{language:r,label:a}=e,n=e.id?e.id:Eb(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){D(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(W(e)||!$b(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){D(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){D(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 $o=s=>{s.removeAttribute("src"),s.load()},Ab=s=>{try{s.pause(),s.playbackRate=0,$o(s),s.remove()}catch(e){console.error(e)}};class wb{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 Yn=window.WeakMap?new WeakMap:new wb,Ft=s=>{let e=s.querySelector("video");const t=!!e;return e?$o(e):(e=document.createElement("video"),s.appendChild(e)),Yn.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},Ut=s=>{const e=Yn.get(s);Yn.delete(s),e?$o(s):Ab(s)};class Js{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 Nl=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},Yd=s=>{const e=Nl(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},kb=s=>{const e=Nl(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)},zn=3;class _b{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<zn&&(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||zn))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 Fl=(s,e,t=zn)=>{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 Vt=s=>{const e=v=>V(s,v).pipe(ss(void 0)),i=G(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>V(s,v))).pipe(P(v=>v.type==="ended"?s.readyState<2:s.readyState<3),ye()),r=G(V(s,"progress"),V(s,"timeupdate")).pipe(P(()=>Fl(s.buffered,s.currentTime))),n=jr().browser===Xn.Safari?Be({play:e("play").pipe(_e()),playing:e("playing")}).pipe(ss(void 0)):e("playing"),o=V(s,"volumechange").pipe(P(()=>({muted:s.muted,volume:s.volume}))),u=V(s,"ratechange").pipe(P(()=>s.playbackRate)),d=V(s,"error").pipe(oe(()=>!!(s.error||s.played.length)),P(()=>{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=V(s,"timeupdate").pipe(P(()=>s.currentTime)),c=new O,h=.3;let f;l.subscribe(v=>{s.loop&&I(f)&&I(v)&&f>=s.duration-h&&v<=h&&c.next(f),f=v});const p=V(s,"enterpictureinpicture"),S=V(s,"leavepictureinpicture"),b=new T(kb(s));p.subscribe(()=>b.next(!0)),S.subscribe(()=>b.next(!1));const g=new T(Yd(s));return V(s,"fullscreenchange").pipe(P(()=>Yd(s))).subscribe(g),{playing$:n,pause$:e("pause").pipe(oe(()=>!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$:V(s,"durationchange").pipe(P(()=>s.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:o,playbackRateState$:u,inPiP$:b,inFullscreen$:g}},sa=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var Pb=_t,Db=Xr,Ib=lo,Rb=uo;Pb({target:"Array",proto:!0},{at:function(e){var t=Db(this),i=Ib(t),r=Rb(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});var Lb=Eo,xb=Lb("Array","at"),Cb=xb,Ob=Cb,Bb=Ob,Mb=Bb,Oe=zr(Mb);let Ao=!1,Kt={};const Nb=s=>{Ao=s},Fb=()=>{Kt={}},Ub=s=>{s(Kt)},fr=(s,e)=>{var t;Ao&&(Kt.meta=(t=Kt.meta)!==null&&t!==void 0?t:{},Kt.meta[s]=e)};class xt{constructor(e){this.name=e}next(e){var t,i;if(!Ao)return;Kt.series=(t=Kt.series)!==null&&t!==void 0?t:{};const r=(i=Kt.series[this.name])!==null&&i!==void 0?i:[];r.push([Date.now(),e]),Kt.series[this.name]=r}}var _i;(function(s){s.FitsContainer="FitsContainer",s.FitsThroughput="FitsThroughput",s.Buffer="Buffer",s.DroppedFramesLimit="DroppedFramesLimit",s.FitsQualityLimits="FitsQualityLimits"})(_i||(_i={}));const Vb=new xt("best_bitrate"),Hb=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class Ul{constructor(){this.history={}}recordSelection(e){this.history[e.id]=he()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Gb='Assertion "ABR Tracks is empty array" failed',Ni=(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,p,S,b;mc(s,Gb);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&&ci(y),E=i.considerPlaybackRate&&I(o)?o:1,$=s.filter(N=>!Ii(N.quality)).sort((N,C)=>ts(N.quality,C.quality)?-1:1),x=(f=Oe($,-1))===null||f===void 0?void 0:f.quality,j=(p=Oe($,0))===null||p===void 0?void 0:p.quality,K=W(r)||I(r.min)&&I(r.max)&&$r(r.max,r.min)||I(r.min)&&j&&ts(r.min,j)||I(r.max)&&x&&$r(r.max,x),H=E*Hb(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),q={},B=$.filter(N=>(v?$r(N.quality,v):!0)?(I(t)&&isFinite(t)&&I(N.bitrate)?t-a>=N.bitrate*H:!0)?i.lazyQualitySwitch&&I(i.minBufferToSwitchUp)&&u&&!Ii(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&ts(N.quality,u.quality)?(q[N.quality]=_i.Buffer,!1):!!l&&An(N.quality,l)?(q[N.quality]=_i.DroppedFramesLimit,!1):K||(W(r.max)||Tu(N.quality,r.max))&&(W(r.min)||An(N.quality,r.min))?!0:(q[N.quality]=_i.FitsQualityLimits,!1):(q[N.quality]=_i.FitsThroughput,!1):(q[N.quality]=_i.FitsContainer,!1))[0];B&&B.bitrate&&Vb.next(B.bitrate);const M=(S=B!=null?B:$[Math.ceil(($.length-1)/2)])!==null&&S!==void 0?S:s[0];M.quality!==((b=d==null?void 0:d.last)===null||b===void 0?void 0:b.quality)&&c({message:`
|
|
7
7
|
[available tracks]
|
|
8
8
|
${s.map(N=>`{ id: ${N.id}, quality: ${N.quality}, bitrate: ${N.bitrate} }`).join(`
|
|
9
9
|
`)}
|
|
@@ -13,7 +13,7 @@ import{ValueSubject as T,Subject as O,Subscription as ce,isNonNullable as D,Erro
|
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[limit params]
|
|
16
|
-
containerQualityLimit: ${
|
|
16
|
+
containerQualityLimit: ${v},
|
|
17
17
|
throughput: ${t},
|
|
18
18
|
reserve: ${a},
|
|
19
19
|
playbackRate: ${o},
|
|
@@ -32,15 +32,15 @@ import{ValueSubject as T,Subject as O,Subscription as ce,isNonNullable as D,Erro
|
|
|
32
32
|
|
|
33
33
|
[best track] ${B==null?void 0:B.quality}
|
|
34
34
|
[selected track] ${M==null?void 0:M.quality}
|
|
35
|
-
`});const
|
|
35
|
+
`});const X=M&&d&&d.history[M.id]&&he()-d.history[M.id]<=i.trackCooldown&&(!d.last||M.id!==d.last.id);if(M!=null&&M.id&&d&&!X&&d.recordSelection(M),X&&(d!=null&&d.last)){const N=d.last;return d==null||d.recordSwitch(N),c({message:`
|
|
36
36
|
[last selected] ${N==null?void 0:N.quality}
|
|
37
|
-
`}),N}return d==null||d.recordSwitch(M),M};var Qe=s=>new URL(s).hostname;const Yb=300,Us=(s,e=Yb)=>new qr(t=>{const{width:i,height:r}=s.getBoundingClientRect();if(t.next({width:i,height:r}),!window.ResizeObserver)return;const a=new ResizeObserver($c(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 Xs{constructor(){this.onDroopedVideoFramesLimit$=new O,this.subscription=new ce,this.playing=!1,this.tracks=[],this.forceChecker$=new O,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&&!Ri(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&&ts(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(V(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=Ii(this.droppedFramesChecker.checkTime).pipe(oe(()=>this.playing),oe(()=>{const r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(ct(this.droppedFramesChecker.checkTime)),i=G(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])=>xs(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 ws={};var ne;(function(s){s.DOWNLOADING_LIB="downloading_lib",s.STOPPED="stopped",s.STREAM_INITIALIZED="stream_initialized",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(ne||(ne={}));const Re=(s,e)=>new qr(t=>{const i=r=>t.next(r);return s.on(e,i),()=>s.off(e,i)});class Wd{constructor(e){this.subscription=new ce,this.videoState=new me(ne.DOWNLOADING_LIB),this.textTracksManager=new Pt,this.droppedFramesManager=new Xs,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 Js,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===ne.DOWNLOADING_LIB||t===ne.STREAM_INITIALIZED))switch((r==null?void 0:r.to)!==m.PAUSED&&a.state===ie.Requested&&t!==ne.STOPPED&&i!==m.STOPPED&&(n?this.seek(a.position-this.liveOffset.getTotalPausedTime()):this.seek(a.position)),i){case m.STOPPED:{switch(t){case ne.STOPPED:break;case ne.PLAYING:case ne.PAUSED:case ne.READY:this.stop();break;default:z(t)}break}case m.READY:{switch(t){case ne.STOPPED:this.prepare();break;case ne.PLAYING:case ne.PAUSED:case ne.READY:break;default:z(t)}break}case m.PLAYING:{switch(t){case ne.PLAYING:break;case ne.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 ne.READY:this.play();break;case ne.STOPPED:this.prepare();break;default:z(t)}break}case m.PAUSED:{switch(t){case ne.PLAYING:this.pause(),this.liveOffset.pause();break;case ne.PAUSED:break;case ne.READY:this.videoState.setState(ne.PAUSED),x(this.params.desiredState.playbackState,m.PAUSED);break;case ne.STOPPED:this.prepare();break;default:z(t)}break}default:z(i)}},this.video=Ft(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(Qe(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:I.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);Ks(import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(ws.MediaPlayer=r.MediaPlayer,ws.Debug=r.Debug,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){R(ws.MediaPlayer,"dashjs not loaded"),R(ws.Debug,"dashjs not loaded"),this.player=ws.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?aa(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&Eb(this.player),bb(this.player),this.params.tuning.requestQuick&&Tb(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(ne.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=g=>{e.error$.next({id:"DashIFProvider",category:I.WTF,message:"DashIFProvider internal logic error",thrown:g})},r=(g,E)=>this.subscription.add(g.subscribe(E,i));r(Us(this.video),this.elementSize$),r(Re(this.player,"error").pipe(P(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(Re(this.player,"playbackError").pipe(P(g=>({id:"DashJSPlayback",message:g.error}))),e.error$);const a=Re(this.player,"qualityChangeRendered").pipe(oe(({mediaType:g})=>g==="video"),P(({newQuality:g})=>{var E;return(E=this.videoTracks$.getValue().find(({bitrateInfo:$})=>$.qualityIndex===g))===null||E===void 0?void 0:E.track}));a.pipe(oe(D)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(oe(({to:g})=>g===ne.STREAM_INITIALIZED),_e()).subscribe(()=>{this.subscription.add(kt(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(W(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(kt(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(Re(this.player,"bufferStateChanged").pipe(oe(({mediaType:g})=>g==="video"),P(({state:g})=>g==="bufferStalled")),e.isBuffering$),r(Re(this.player,"fragmentLoadingStarted"),({mediaType:g,request:{url:E}})=>{var $,L;const j=this.player.getDashMetrics(),K=j.getLatestFragmentRequestHeaderValueByID(g,"X-Reused"),H=($=j.getLatestFragmentRequestHeaderValueByID(g,"X-Delivery-Type"))!==null&&$!==void 0?$:Ms.HTTP1,q=(L={1:!0,0:!1}[K])!==null&&L!==void 0?L:void 0;this.params.output.httpConnectionType$.next(H),this.params.output.httpConnectionReused$.next(q),e.hostname$.next(Qe(E))}),r(Re(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=[],j=this.player.getQualityFor("video");let K;for(const H of this.player.getBitrateInfoListFor("video")){const q=H.qualityIndex.toString(10),Q=ci(H),B=H.bitrate/1e3,M={width:H.width,height:H.height},J=this.frameRatesByFrameHeight[H.height];if(Q){const N={id:q,quality:Q,bitrate:B,size:M,fps:J};L.push({track:N,bitrateInfo:H}),H.qualityIndex===j&&(K=N)}}this.videoTracks$.next(L),e.availableVideoTracks$.next(L.map(({track:H})=>H)),K&&e.currentVideoTrack$.next(K),this.videoState.setState(ne.STREAM_INITIALIZED),this.videoState.startTransitionTo(ne.READY)}),r(Re(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(G(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=Ni(this.videoTracks$.getValue().map(({track:j})=>j),{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:j})=>j===E);L!=null&&L.bitrateInfo&&this.player.setQualityFor("video",L==null?void 0:L.bitrateInfo.qualityIndex,!1)}),r(Be({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(oe(D))}).pipe(oe(({isLive:g})=>g),P(({maxSeekBackTime:g})=>-g/1e3)),this.params.output.duration$);const n=Re(this.player,"playbackTimeUpdated").pipe(P(({time:g})=>g!=null?g:0));r(Be({availableFrom:this.availableFrom$.pipe(oe(D)),currentTime:n}),({availableFrom:g,currentTime:E})=>this.params.output.liveTime$.next(g+E*1e3)),r(n.pipe(oe(()=>this.isLive$.getValue()===!1)),e.position$),r(Re(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),r(Re(this.player,"playbackEnded"),e.endedEvent$),r(Re(this.player,"playbackProgress").pipe(P(()=>Ul(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(Re(this.player,"playbackPlaying"),()=>{this.videoState.setState(ne.PLAYING),x(t.playbackState,m.PLAYING)}),r(Re(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(ne.PAUSED),x(this.params.desiredState.playbackState,m.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(Re(this.player,"playbackPaused"),()=>{this.videoState.setState(ne.PAUSED),x(t.playbackState,m.PAUSED)}),r(Re(this.player,"canPlay"),()=>{var g;((g=this.videoState.getTransition())===null||g===void 0?void 0:g.to)===ne.READY&&this.videoState.setState(ne.READY)}),r(this.isLive$,e.isLive$),r(Us(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=G(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,We(["init"])).pipe(ct(0));r(o,this.syncPlayback);const{playbackDuration$:u,ping$:d,connectionType$:l,connectionReused$:c}=yb(this.player);r(l,this.params.output.httpConnectionType$),r(c,this.params.output.httpConnectionReused$),r(u,this.maxSeekBackTime$),r(d.pipe(_e()),e.firstBytesEvent$),r(Re(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(Be({isLive:this.isLive$,isShort:e.duration$.pipe(P(g=>g<60))}),({isLive:g,isShort:E})=>{const $=!g&&E;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:$}}})}),r(n.pipe(oe(g=>g>this.params.tuning.insufficientBufferRuleMargin),_e()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(Re(this.player,"manifestLoaded").pipe(_e()).subscribe(()=>{this.subscription.add(Re(this.player,"playbackPlaying").pipe(_e(),ss(void 0)).subscribe(e.firstFrameEvent$,i))},i)),r(Re(this.player,"manifestLoaded"),g=>{var E,$,L,j,K,H,q;if(!(($=(E=g.data)===null||E===void 0?void 0:E.Period)===null||$===void 0)&&$.AdaptationSet){const Q=[];for(const B of(j=(L=g.data)===null||L===void 0?void 0:L.Period)===null||j===void 0?void 0:j.AdaptationSet)if(B.contentType==="text"){const M=(K=B.Representation)===null||K===void 0?void 0:K.id,J=new URL((H=B.Representation)===null||H===void 0?void 0:H.BaseURL,(q=g.data)===null||q===void 0?void 0:q.baseUri).toString(),N="internal",C=B.lang;Q.push({id:M,url:J,type:N,language:C})}t.internalTextTracks.startTransitionTo(Q)}}),this.subscription.add(fi(this.video,t.isLooped,i));const{volumeState$:h,looped$:f,playbackRateState$:p,inPiP$:S,inFullscreen$:b,pause$:v,playing$:y}=Vt(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(P(g=>g.map(({track:E})=>E)))}),this.subscription.add(Nt(this.video,t.volume,h,i)),this.subscription.add(h.subscribe(e.volume$,i)),this.subscription.add(f.subscribe(e.loopedEvent$)),this.subscription.add(ii(this.video,t.playbackRate,p,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(ne.STOPPED),x(this.params.desiredState.playbackState,m.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(ne.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=qe(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Te.PLAYBACK_SHIFT);this.player.attachSource(r)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(ne.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(ne.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){}Ut(this.video),this.params.output.element$.next(void 0)}}var hs=s=>{switch(s){case"mobile":return ut.Q_144P;case"lowest":return ut.Q_240P;case"low":return ut.Q_360P;case"sd":case"medium":return ut.Q_480P;case"hd":case"high":return ut.Q_720P;case"fullhd":case"full":return ut.Q_1080P;case"quadhd":case"quad":return ut.Q_1440P;case"ultrahd":case"ultra":return ut.Q_2160P}};const Qd=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 si=s=>ee(void 0,void 0,void 0,function*(){const e=s.muted;try{yield s.play()}catch(t){if(!Qd(t))return!1;if(e)return console.warn(t),!1;s.muted=!0;try{yield s.play()}catch(i){return Qd(i)&&(s.muted=!1,console.warn(i)),!1}}return!0});function ze(){return he()}function Hl(s){return ze()-s}function Kd(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 zb(s,e,t){const i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function kr(s,e,t,i){const r=window.XMLHttpRequest;let a,n,o,u=!1,d=0,l,c,h=!1,f="arraybuffer",p=7e3,S=2e3,b=()=>{if(u)return;R(l);const B=Hl(l);let M;if(B<S){M=S-B,setTimeout(b,M);return}S*=2,S>p&&(S=p),n&&n.abort(),n=new r,L()};const v=B=>(a=B,Q),y=B=>(c=B,Q),g=()=>(f="json",Q),E=()=>{if(!u){if(--d>=0){b(),i&&i();return}u=!0,c&&c(),t&&t()}},$=B=>(h=B,Q),L=()=>{l=ze(),n=new r,n.open("get",s);let B=0,M,J=0;const N=()=>(R(l),Math.max(l,Math.max(M||0,J||0)));if(a&&n.addEventListener("progress",C=>{const Y=ze();a.updateChunk&&C.loaded>B&&(a.updateChunk(N(),C.loaded-B),B=C.loaded,M=Y)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(u)return;R(n);const C=n.status;if(C>=200&&C<300){if(n.response.byteLength&&a){const Y=n.response.byteLength-B;Y&&a.updateChunk&&a.updateChunk(N(),Y)}c&&c(),n&&e(n.response)}else E()}),n.addEventListener("error",()=>{E()}),h){const C=()=>{R(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(J=ze(),n.removeEventListener("readystatechange",C))};n.addEventListener("readystatechange",C)}return n.responseType=f,n.send(),Q},Q={withBitrateReporting:v,withParallel:$,withJSONResponse:g,withRetryCount:B=>(d=B,Q),withRetryInterval:(B,M)=>(D(B)&&(S=B),D(M)&&(p=M),Q),withTimeout:B=>(o=B,Q),withFinally:y,send:L,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return Q}const qb=100,Wb=2e3,Qb=500;let Kb=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-Qb;if(t-e>Wb){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>qb&&(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 Jb{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=ze(),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=ze()-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=kr(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=ze()}_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=ze();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 pr=1e4,mr=3,Xb=300,Zb=2e3,ey=6e4,ty=10,iy=1,sy=500;class ry{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 Kb(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Kd(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=Kd(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=()=>{zb(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 Jb(mr,pr,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=kr(this.urlResolver.resolve(E,!1),$,L,()=>this._retryCallback()).withTimeout(pr).withBitrateReporting(this.bitrateSwitcher).withRetryCount(mr).withFinally(()=>{u=null}).send()},f=(E,$,L)=>{R(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),$,L,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},p=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)p(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){p(1);return}const L=ze()-1e4;let j=0;for(let H=0;H<this.bufferStates.length;H++){const q=this.bufferStates[H];E=Math.min(E,q.buf),q.ts<L&&j++}this.bufferStates.splice(0,j),t(`update playback rate; minBuffer=${E} drop=${j} jitter=${this.sourceJitter}`);let K=E-iy;this.sourceJitter>=0?K-=this.sourceJitter/2:this.sourceJitter-=1,K>3?p(1.15):K>1?p(1.1):K>.3?p(1.05):p(1)}},v=E=>{let $;const L=()=>$&&$.start?$.start.length:0,j=C=>$.start[C]/1e3,K=C=>$.dur[C]/1e3,H=C=>$.fragIndex+C,q=(C,Y)=>({chunkIdx:H(C),startTS:j(C),dur:K(C),discontinuity:Y}),Q=()=>{let C=0;if($&&$.dur){let Y=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,se=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ve=Y;this.sourceJitter>1&&(ve+=this.sourceJitter-1);let Ee=$.dur.length-1;for(;Ee>=0&&(ve-=$.dur[Ee],!(ve<=0));--Ee);C=Math.min(Ee,$.dur.length-1-se),C=Math.max(C,0)}return q(C,!0)},B=C=>{const Y=L();if(!(Y<=0)){if(D(C)){for(let se=0;se<Y;se++)if(j(se)>C)return q(se)}return Q()}},M=C=>{const Y=L(),se=C?C.chunkIdx+1:0,ve=se-$.fragIndex;if(!(Y<=0)){if(!C||ve<0||ve-Y>ty)return t(`Resync: offset=${ve} bChunks=${Y} chunk=`+JSON.stringify(C)),Q();if(!(ve>=Y))return q(se-$.fragIndex,!1)}},J=(C,Y,se)=>{d&&d.abort(),d=kr(this.urlResolver.resolve(C,!0,this.lowLatency),Y,se,()=>this._retryCallback()).withTimeout(pr).withRetryCount(mr).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(C,Y)=>{J(E,se=>{if(!c())return;$=se;const ve=!!$.lowLatency;ve!==this.lowLatency&&S(ve);let Ee=0;for(let xe=0;xe<$.dur.length;++xe)Ee+=$.dur[xe];Ee>0&&(R(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Ee/$.dur.length)),r({name:"index",zeroTime:$.zeroTime,shiftDuration:$.shiftDuration}),this.sourceJitter=$.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,$.jitter/1e3)):1,C(B(Y))},()=>this._handleNetworkError())},nextChunk:M}},y=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),R(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:E=>{const{videoElement:$,logger:L}=this.params;let j=v(e.jidxUrl),K,H,q,Q,B=0,M,J,N;const C=()=>{M&&(clearTimeout(M),M=void 0);const re=Math.max(sy,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),He=B+re,Xe=ze(),Le=Math.min(1e4,He-Xe);B=Xe;const Pe=()=>{d||c()&&j.seek(()=>{c()&&(B=ze(),Y(),C())})};Le>0?M=window.setTimeout(()=>{this.paused?C():Pe()},Le):Pe()},Y=()=>{let re;for(;re=j.nextChunk(Q);)Q=re,Je(re);const He=j.nextChunk(q);if(He){if(q&&He.discontinuity){L("Detected discontinuity; restarting playback"),this.paused?C():(y(),this._initPlayerWith(e));return}xe(He)}else C()},se=(re,He)=>{if(!c()||!this.sourceBuffer)return;let Xe,Le,Pe;const Gt=jt=>{window.setTimeout(()=>{c()&&se(re,He)},jt)};if(this.sourceBuffer.updating)L("Source buffer is updating; delaying appendBuffer"),Gt(100);else{const jt=ze(),ai=$.currentTime;!this.paused&&$.buffered.length>1&&J===ai&&jt-N>500&&(L("Stall suspected; trying to fix"),this._fixupStall()),J!==ai&&(J=ai,N=jt);const Yt=this._getBufferSizeSec();if(Yt>30)L(`Buffered ${Yt} seconds; delaying appendBuffer`),Gt(2e3);else try{this.sourceBuffer.appendBuffer(re),this.videoPlayStarted?(this.bufferStates.push({ts:jt,buf:Yt}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),He&&He()}catch(Fi){if(Fi.name==="QuotaExceededError")L("QuotaExceededError; delaying appendBuffer"),Pe=this.sourceBuffer.buffered.length,Pe!==0&&(Xe=this.sourceBuffer.buffered.start(0),Le=ai,Le-Xe>4&&this.sourceBuffer.remove(Xe,Le-3)),Gt(1e3);else throw Fi}}},ve=()=>{H&&K&&(L([`Appending chunk, sz=${H.byteLength}:`,JSON.stringify(q)]),se(H,function(){H=null,Y()}))},Ee=re=>e.fragUrlTemplate.replace("%%id%%",re.chunkIdx),xe=re=>{c()&&f(Ee(re),(He,Xe)=>{if(c()){if(Xe/=1e3,H=He,q=re,n=re.startTS,Xe){const Le=Math.min(10,re.dur/Xe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Le:Le}ve()}},()=>this._handleNetworkError())},Je=re=>{c()&&(R(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Ee(re),!1)))},ft=re=>{c()&&(e.cachedHeader=re,se(re,()=>{K=!0,ve()}))};a=!0,j.seek(re=>{if(c()){if(B=ze(),!re){C();return}Q=re,!W(E)||re.startTS>E?xe(re):(q=re,Y())}},E),e.cachedHeader?ft(e.cachedHeader):h(e.headerUrl,ft,()=>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,R(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,p;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(f=this._getBufferSizeSec(),p=c/this.bitrate,f>10&&p>.8||f>15&&p>.5||f>20&&p>.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 p=ze();if(this.chunkRateEstimator.addInterval(h,p,f)){const b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:p-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&&Hl(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=ze();c<o&&(n=h),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=kr(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(pr).withRetryCount(mr).withRetryInterval(Xb,Zb).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;si(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))},ey))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var ae;(function(s){s.STOPPED="stopped",s.MANIFEST_READY="manifest_ready",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(ae||(ae={}));const ay=[ae.PAUSED,ae.PLAYING,ae.READY],ny=[ae.PAUSED,ae.PLAYING,ae.READY];class oy{constructor(e){this.subscription=new ce,this.videoState=new me(ae.STOPPED),this.representations$=new T([]),this.textTracksManager=new Pt,this.droppedFramesManager=new Xs,this.maxSeekBackTime$=new T(1/0),this.zeroTime$=new T(void 0),this.liveOffset=new Js,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:I.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=hs(c.name))!==null&&n!==void 0?n:ci(c.video),p=c.bitrate/1e3,S=Object.assign({},c.video);if(!f)continue;const b={id:h,quality:f,bitrate:p,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)===ae.MANIFEST_READY&&this.videoState.setState(ae.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===m.STOPPED){r!==ae.STOPPED&&(this.videoState.startTransitionTo(ae.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(ae.STOPPED));return}if(a)return;const d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(ny.includes(r)&&(d||l)){this.prepare();return}if((o==null?void 0:o.to)!==m.PAUSED&&u.state===ie.Requested&&ay.includes(r)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(r){case ae.STOPPED:this.videoState.startTransitionTo(ae.MANIFEST_READY),this.dash.attachSource(qe(this.params.source.url));return;case ae.MANIFEST_READY:this.videoState.startTransitionTo(ae.READY),this.prepare();break;case ae.READY:if(n===m.PAUSED)this.videoState.setState(ae.PAUSED);else if(n===m.PLAYING){this.videoState.startTransitionTo(ae.PLAYING);const c=o==null?void 0:o.from;c&&c===m.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(ae.PAUSED)})}return;case ae.PLAYING:n===m.PAUSED&&(this.videoState.startTransitionTo(ae.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case ae.PAUSED:if(n===m.PLAYING)if(this.videoState.startTransitionTo(ae.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(ae.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(qe(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:I.WTF,message:"DashLiveProvider internal logic error",thrown:r})};G(this.videoState.stateChangeStarted$.pipe(P(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(P(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=Ft(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(Qe(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=Vt(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(P(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)===ae.READY&&this.videoState.setState(ae.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(ae.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===ie.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(ae.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(ye(),P(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Be({zeroTime:this.zeroTime$.pipe(oe(D)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(fi(this.video,this.params.desiredState.isLooped,t)).add(Nt(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(ii(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&&gc(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case ae.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(m.STOPPED);break;case ae.MANIFEST_READY:case ae.READY:((a=this.params.desiredState.playbackState.getTransition())===null||a===void 0?void 0:a.to)===m.READY&&this.params.desiredState.playbackState.setState(m.READY);break;case ae.PAUSED:this.params.desiredState.playbackState.setState(m.PAUSED);break;case ae.PLAYING:this.params.desiredState.playbackState.setState(m.PLAYING);break;default:return z(r.to)}},t)).add(G(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,We(["init"])).pipe(ct(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),Ut(this.video)}createLiveDashPlayer(){const e=new ry({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:Ni(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,p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(h||c!==f)&&this.setVideoTrack(l),p&&this.setAutoQuality(d),h||p||c!==f){const S=(n=o.find(({track:b})=>b.id===c))===null||n===void 0?void 0:n.representation;R(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;R(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===m.PAUSED&&i===ae.PAUSED,a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(qe(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}}var _o=s=>{var e,t;const i=s.get("X-Delivery-Type"),r=s.get("X-Reused"),a=i===null?Ms.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}},tt=(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 dy=s=>{const e=document.createElement("a");return e.href=s,e.origin},uy=s=>{const e=document.createElement("a");return e.href=s,e.host};class Gl{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=xi(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(uy(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 Cr{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(Cr._str2ua(S.substr(u))),u=S.length};let p=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(p=li(p)),this._lastXhr=new Gl(p,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=Cr._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 ly{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=li(i)),new Gl(i,t,r=>{this.attachManifest(r,t,dy(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,p,S,b,v,y,g,E,$,L,j,K,H,q,Q,B;const M=d.getElementsByTagName("SegmentBase")[0],J=M&&n(M,"indexRange").split("-"),N=M&&M.getElementsByTagName("Initialization")[0],C=N&&n(N,"range").split("-");if(!C||!J){const Je=d.parentElement;if((Je==null?void 0:Je.getAttribute("contentType"))==="text"){const ft=(l=d.getAttribute("id"))!==null&&l!==void 0?l:void 0,re=(i?i+"/":"")+((p=(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||p===void 0?void 0:p.data),He=(S=Je.getAttribute("lang"))!==null&&S!==void 0?S:void 0;re&&u.push({id:ft,url:re,language:He})}return}const Y=.1,se=Number((b=d.attributes.getNamedItem("bandwidth"))===null||b===void 0?void 0:b.value),ve=(i?i+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let Ee;const xe=(y=(v=d.attributes.getNamedItem("frameRate"))===null||v===void 0?void 0:v.value)!==null&&y!==void 0?y:void 0;Ee=xe?aa(xe):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:se,baseURL:ve,failoverHosts:t,indexFrom:Number(J[0]),indexTo:Number(J[1]),initFrom:Number(C[0]),initTo:Number(C[1]),codecs:(L=($=d.attributes.getNamedItem("codecs"))===null||$===void 0?void 0:$.value)!==null&&L!==void 0?L:void 0,mimeType:(K=(j=d.attributes.getNamedItem("mimeType"))===null||j===void 0?void 0:j.value)!==null&&K!==void 0?K:void 0,fps:Ee,bufferSize:Y*se/8,bufferLength:Y,name:(q=(H=d.attributes.getNamedItem("okQuality"))===null||H===void 0?void 0:H.value)!==null&&q!==void 0?q:void 0,id:(B=(Q=d.attributes.getNamedItem("id"))===null||Q===void 0?void 0:Q.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),p=u+n.getUint32(a+4,!1);a+=12,e.refs.push({fromTime:u/o,toTime:p/o,fromOffset:d,toOffset:f-1}),d=f,u=p}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 p=this._buffer.getNextWithGap(f);p&&(this._video.currentTime=p.from)}catch(p){throw this._params.onError("GapSyncError",`Seek Error ${String(p)}`,p),p}},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 Cr({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||W(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 de;(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"})(de||(de={}));const cy=[de.PAUSED,de.PLAYING];class hy{constructor(e){this.videoState=new me(de.STOPPED),this.subscription=new ce,this.representations$=new T([]),this.currentRepresentation$=new T(void 0),this.textTracksManager=new Pt,this.droppedFramesManager=new Xs,this.elementSize$=new T(void 0),this.dashLiteEvents={idxRequestPing$:new O,responseHeaders$:new O,manifestReady$:new O,representationPlay$:new O,error$:new O},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&&hs(u.name))!==null&&n!==void 0?n:ci(u),c=u.bandwidth/1e3,h={width:u.width,height:u.height},f=u.fps;if(!l)continue;const p={id:d,quality:l,bitrate:c,size:h,fps:f};o.push({track:p,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(de.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 R(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===m.STOPPED){t!==de.STOPPED&&(this.videoState.startTransitionTo(de.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(de.STOPPED),x(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(!i)switch((a==null?void 0:a.to)!==m.PAUSED&&n.state===ie.Requested&&cy.includes(t)&&this.seek(n.position,n.forcePrecise),t){case de.STOPPED:this.videoState.startTransitionTo(de.MANIFEST_LOADED),this.prepare();return;case de.MANIFEST_LOADED:this.videoState.startTransitionTo(de.INITIAL_REPRESENTATION_SELECTED);return;case de.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(de.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case de.METADATA_LOADED:this.videoState.startTransitionTo(de.READY),this.dash.updateRefsForCurrentTime();return;case de.READY:r===m.READY?x(this.params.desiredState.playbackState,m.READY):r===m.PAUSED?(this.videoState.setState(de.PAUSED),x(this.params.desiredState.playbackState,m.PAUSED)):r===m.PLAYING&&(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed());return;case de.PLAYING:r===m.PAUSED?(this.videoState.startTransitionTo(de.PAUSED),this.video.pause()):(a==null?void 0:a.to)===m.PLAYING&&x(this.params.desiredState.playbackState,m.PLAYING);return;case de.PAUSED:r===m.PLAYING?(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===m.PAUSED&&x(this.params.desiredState.playbackState,m.PAUSED);return;default:return z(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),G(this.videoState.stateChangeStarted$.pipe(P(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(P(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=Ft(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(Qe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Pb(this.video),this.dash=new ly({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:I.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:I.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=Vt(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(()=>{W(this.params.desiredState.seekState.getState().state!==ie.Applying)&&(this.videoState.getState()===de.PLAYING||this.videoState.getState()===de.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(fi(this.video,t.isLooped,i)),this.subscription.add(Nt(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ii(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(P(o=>o.map(({track:u})=>u)))}),n(Us(this.video),this.elementSize$),this.subscription.add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===de.READY&&this.videoState.setState(de.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED),x(this.params.desiredState.playbackState,m.PAUSED)})).add(a.playing$.subscribe(()=>{this.videoState.setState(de.PLAYING),x(this.params.desiredState.playbackState,m.PLAYING)},i)).add(a.loadedMetadata$.subscribe(()=>{this.videoState.setState(de.METADATA_LOADED)},i)).add(a.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},i)).add(this.dashLiteEvents.error$.pipe(P(({id:o,message:u,thrown:d})=>({id:`DashLite_${o}`,category:I.WTF,message:u,thrown:d}))).subscribe(this.params.output.error$)).add(G(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$,V(this.video,"progress")).pipe(P(()=>{var o,u,d,l;const c=this.currentRepresentation$.getValue(),h=this.representations$.getValue(),f=this.params.desiredState.autoVideoTrackSwitching.getTransition(),p=(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(p))y=p;else{const g=tt(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=Ni(h.map(({track:j})=>j),{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:j})=>j===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}),ye()).subscribe(this.currentRepresentation$,i)).add(Be({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(oe(o=>o.to===de.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(oe(D))}).pipe(_e()).subscribe(()=>this.videoState.setState(de.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(oe(D),ye((o,u)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?o.height<=u.height:o===u)).subscribe(o=>{const u=tt(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(Qe(o.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:u,reused:d}=_o(o);this.params.output.httpConnectionType$.next(u),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(_e(),ss(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(oe(D)).subscribe(this.handleRepresentationPlay,i)).add(G(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,We(["init"])).pipe(ct(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),Ut(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(){si(this.video).then(e=>{e||(this.videoState.setState(de.PAUSED),x(this.params.desiredState.playbackState,m.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:I.DOM,thrown:e}))}}var Fe;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(Fe||(Fe={}));var Or;(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"})(Or||(Or={}));var vt;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(vt||(vt={}));var ue;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(ue||(ue={}));var rs;(function(s){s.MP4="mp4",s.WEBM="webm"})(rs||(rs={}));var Br;(function(s){s[s.RECTANGULAR=0]="RECTANGULAR",s[s.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",s[s.CUBEMAP=2]="CUBEMAP",s[s.MESH=3]="MESH"})(Br||(Br={}));var Ae;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Ae||(Ae={}));class Jd{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 jl extends Jd{constructor(){super(),this.listeners||Jd.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 Yl=class{constructor(){Object.defineProperty(this,"signal",{value:new jl,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&&(Yl.prototype[Symbol.toStringTag]="AbortController",jl.prototype[Symbol.toStringTag]="AbortSignal");function zl(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 fy(s){typeof s=="function"&&(s={fetch:s});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!zl({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,p)=>{l.addEventListener("abort",()=>p(c),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([h,n(u,d)])}return n(u,d)},Request:a}}const na=zl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),ql=na?fy({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ci=na?ql.fetch:window.fetch;na?ql.Request:window.Request;const St=na?Yl:window.AbortController;var as=(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 py=(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)},my=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Mr=my?py:window.requestIdleCallback;var rn,an;const vy=16;let Wl=!1;try{Wl=zr().browser===Zn.Safari&&parseInt((an=(rn=navigator.userAgent.match(/Version\/(\d+)/))===null||rn===void 0?void 0:rn[1])!==null&&an!==void 0?an:"",10)<=vy}catch(s){console.error(s)}let gy=class{constructor(e){this.bufferFull$=new O,this.error$=new O,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:I.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return ee(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(i=>{const r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return ee(this,void 0,void 0,function*(){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()})})}abort(e){return ee(this,void 0,void 0,function*(){return new Promise(t=>{let i;Wl&&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:I.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:z(t)}}};var Nr=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};let Ht=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}},Ql=class extends Ht{},Sy=class 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}}},by=class extends Ht{parseChildrenBoxes(){return fs(this.content)}},yy=class extends Ht{constructor(e){super(e),this.data=this.content}},Zs=class extends Ht{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}},Ty=class extends Zs{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})}}},Ey=class extends Ht{parseChildrenBoxes(){return fs(this.content)}},$y=class extends Ht{parseChildrenBoxes(){return fs(this.content)}};var Pi;(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"})(Pi||(Pi={}));let Ay=class extends Zs{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=Pi.MONOSCOPIC;break;case 1:this.stereoMode=Pi.TOP_BOTTOM;break;case 2:this.stereoMode=Pi.LEFT_RIGHT;break;case 3:this.stereoMode=Pi.STEREO_CUSTOM;break;case 4:this.stereoMode=Pi.RIGHT_LEFT;break}this.cursor+=1}},wy=class extends Zs{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}},ky=class extends Zs{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}},_y=class extends Ht{parseChildrenBoxes(){return fs(this.content)}},Py=class extends Zs{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()}},Dy=class extends Ht{parseChildrenBoxes(){return fs(this.content)}},Ry=class extends Ht{parseChildrenBoxes(){return fs(this.content)}};const Iy={ftyp:Sy,moov:by,mdat:yy,sidx:Ty,trak:Ey,mdia:_y,tkhd:Py,minf:Dy,sv3d:$y,st3d:Ay,prhd:wy,proj:Ry,equi:ky,unknown:Ql};let xy=class{createBox(e,t){const i=Iy[e];return i?new i(t):new Ql(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return oa.createBox(i,new DataView(e.buffer,e.byteOffset))}};const oa=new xy;function Rs(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:oa.createBox(e,new DataView(s.buffer,i-7))}i++}return null}function Ly(s,e){const t=[];let i=0;for(;i<s.byteLength;){const r=Rs(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 fs(s){const e=[];let t=0;for(;t<s.byteLength;){const i=oa.createFromView(new DataView(s.buffer,s.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const Cy=new TextDecoder("ascii"),Oy=s=>Cy.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",By=s=>{const e=oa.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:ue.NONE,time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},My=s=>{const e=Ly(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},Ny=s=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Br.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(Rs(s,"sv3d")){e.is3dVideo=!0;const i=Rs(s,"st3d");i&&(e.stereoMode=i.stereoMode);const r=Rs(s,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const a=Rs(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},Fy={validateData:Oy,parseInit:Ny,getIndexRange:()=>{},parseSegments:By,parseFeedableSegmentChunk:My};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 Xd={[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}},Kl=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=Fr(s,t),r=i in Xd,a=r?Xd[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=Fr(u),c=d*Math.pow(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}},Fr=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*Math.pow(2,16)+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*Math.pow(2,32)+s.getUint32(1);case 6:return s.getUint16(0)*Math.pow(2,32)+s.getUint32(2);case 7:{const t=s.getUint8(0)*Math.pow(2,48)+s.getUint16(1)*Math.pow(2,32)+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ct=(s,e)=>{switch(e){case F.SignedInteger:return s.getInt8(0);case F.UnsignedInteger:return Fr(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)}},ns=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=Kl(i);if(!e(r))return;r.type===F.Master&&ns(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},Uy=s=>{if(s.getUint32(0)!==w.EBML)return!1;let e,t,i;const r=Kl(s);return ns(r.value,({tag:a,type:n,value:o})=>(a===w.EBMLReadVersion?e=Ct(o,n):a===w.DocType?t=Ct(o,n):a===w.DocTypeReadVersion&&(i=Ct(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Jl=[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],Vy=[w.Timestamp,w.SilentTracks,w.SilentTrackNumber,w.Position,w.PrevSize,w.SimpleBlock,w.BlockGroup,w.EncryptedBlock],Hy=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,d,l=!1;const c=0;return ns(s,({tag:h,type:f,value:p,valueSize:S})=>{if(h===w.SeekID){const b=Ct(p,f);d=Fr(b)}else h!==w.SeekPosition&&(d=void 0);return h===w.Segment?(e=p.byteOffset,t=p.byteOffset+S):h===w.Info?a=!0:h===w.SeekHead?n=!0:h===w.TimestampScale?i=Ct(p,f):h===w.Duration?r=Ct(p,f):h===w.SeekPosition&&d===w.Cues?u=Ct(p,f):h===w.Tracks?ns(p,({tag:b,type:v,value:y})=>b===w.ProjectionType?(l=Ct(y,v)===1,!1):!0):a&&n&&Jl.includes(h)&&(o=!0),!o}),R(e,"Failed to parse webm Segment start"),R(t,"Failed to parse webm Segment end"),R(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:Br.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Gy=s=>{if(W(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},jy=(s,e)=>{let t=!1,i=!1;const r=o=>D(o.time)&&D(o.position),a=[];let n;return ns(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=Ct(d,u));break;case w.CueTrackPositions:break;case w.CueClusterPosition:n&&(n.position=Ct(d,u));break;default:t&&Jl.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:ue.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}}})},Yy=s=>{let e=0,t=!1;try{ns(s,i=>i.tag===w.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Vy.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},zy={validateData:Uy,parseInit:Hy,getIndexRange:Gy,parseSegments:jy,parseFeedableSegmentChunk:Yy},Xl=1e4,qy=3e4,Wy=5e3,Qy=Xl,Ky=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a})=>{var n;const o=(n=a?hs(a):void 0)!==null&&n!==void 0?n:ci({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r}},Jy=({id:s,bitrate:e})=>({id:s,bitrate:e}),Xy=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=Oe(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:Oe(s,-1)},Zy=({id:s,lang:e,url:t,isAuto:i})=>({id:s,url:t,isAuto:i,type:"internal",language:e}),vr=s=>{const e=[];let t=0,i=s.length-1;for(;t<Xl&&i>=0;)e.unshift(s[i]),t+=s[i].time.to-s[i].time.from,i--;return e};let Zd=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 O,this.gaps=[],this.isSeekingLive=!1,this.subscription=new ce,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new St,this.destroyAbortController=new St,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.startWith=fe(this.destroyAbortController.signal,function(l){return pe(this,arguments,function*(){const c=this.representations.get(l);R(c,`Cannot find representation ${l}`),this.playingRepresentationId=l,this.downloadingRepresentationId=l,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${c.mime}; codecs="${c.codecs}"`),this.sourceBufferTaskQueue=new gy(this.sourceBuffer),this.subscription.add(V(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},S=>this.error$.next({id:"SegmentEjection",category:I.WTF,message:"Error when trying to clear segments ejected by browser",thrown:S}))),this.subscription.add(V(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:I.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(S=>{if(!this.sourceBuffer)return;const b=Math.min(this.bufferLimit,Nr(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 yield _(this.loadInit(c,"high",!0));const h=this.initData.get(c.id),f=this.segments.get(c.id),p=this.parsedInitData.get(c.id);if(R(h,"No init buffer for starting representation"),R(f,"No segments for starting representation"),!(h instanceof ArrayBuffer))return yield _(void 0);this.searchGaps(f,c),yield yield _(this.sourceBufferTaskQueue.append(h,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(p)})}.bind(this)),this.switchTo=fe(this.destroyAbortController.signal,function(l){return pe(this,arguments,function*(){if(l===this.downloadingRepresentationId||l===this.switchingToRepresentationId)return yield _(void 0);this.switchingToRepresentationId=l;const c=this.representations.get(l);R(c,`No such representation ${l}`);let h=this.segments.get(l),f=this.initData.get(l);if(W(f)||W(h)?yield yield _(this.loadInit(c,"high",!1)):f instanceof Promise&&(yield yield _(f)),h=this.segments.get(l),R(h,"No segments for starting representation"),f=this.initData.get(l),!f||!(f instanceof ArrayBuffer)||!this.sourceBuffer)return yield _(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=l,this.abort(),yield yield _(this.sourceBufferTaskQueue.append(f,this.downloadAbortController.signal));const p=this.getCurrentPosition();D(p)&&(this.searchGaps(h,c),this.maintain(p))})}.bind(this)),this.seekLive=fe(this.destroyAbortController.signal,function(l){return pe(this,arguments,function*(){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!l)return yield _(void 0);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 yield _(void 0);const g=vr(y.segmentReference.segments);this.segments.set(y.id,g)}const c=this.switchingToRepresentationId?this.switchingToRepresentationId:this.downloadingRepresentationId,h=this.representations.get(c);R(h);const f=vr(h.segmentReference.segments),p=this.initData.get(h.id);if(R(p,"No init buffer for starting representation"),R(f,"No segments for starting representation"),!(p instanceof ArrayBuffer))return yield _(void 0);const S=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),S&&(yield yield _(this.sourceBufferTaskQueue.remove(S.from*1e3,S.to*1e3,this.destroyAbortController.signal))),this.searchGaps(f,h),yield yield _(this.sourceBufferTaskQueue.append(p,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 rs.MP4:this.containerParser=Fy;break;case rs.WEBM:this.containerParser=zy;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 St,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(W(e)||W(this.downloadingRepresentationId)||W(this.playingRepresentationId)||W(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(R(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=tt(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)&&Nr(this.sourceBuffer.buffered)>=this.bufferLimit){const d=tt(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=Oe(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===ue.FED&&!o.length&&tt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const u=Oe(i,-1);u&&u.status===ue.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=>Object.assign(Object.assign({},c),{status:ue.NONE,size:void 0})),u=(i=this.segments.get(n.id))!==null&&i!==void 0?i:[],d=(a=(r=Oe(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=vr(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}},p)=>{const S=h<=i&&f>=i,b=h>i||S||p===0&&i===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&h<=i+v||f<=i+v;return(c===ue.NONE||c===ue.PARTIALLY_EJECTED&&b&&y&&this.sourceBuffer&&!as(this.sourceBuffer.buffered,i))&&b&&y});if(r===-1)return[];if(t!==vt.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===ue.NONE||h.status===ue.PARTIALLY_EJECTED)u.push(h);else break}return u}loadSegments(e,t,i="auto"){return ee(this,void 0,void 0,function*(){if(!e.length)return;let r,a,n=e;const{type:o}=t.segmentReference;switch(o){case vt.BYTE_RANGE:{r=t.segmentReference.url,a={from:Oe(e,0).byte.from,to:Oe(e,-1).byte.to};break}case vt.TEMPLATE:{const d=Oe(e,0);r=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:z(o)}for(const d of n)d.status=ue.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:u}=this.downloadAbortController;if(this.failedDownloads&&(yield fe(u,function(){return pe(this,arguments,function*(){const d=Ls(this.failedDownloads,this.tuning.downloadBackoff);yield 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:I.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=tt((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:I.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=ue.FED,"size"in c.segment&&(c.segment.size=c.fedBytes);for(const f of this.representations.values())if(f.id!==t)for(const p of(h=this.segments.get(f.id))!==null&&h!==void 0?h:[])p.status===ue.FED&&p.time.from===c.segment.time.from&&p.time.to===c.segment.time.to&&(p.status=ue.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===vt.BYTE_RANGE,p=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===ue.DOWNLOADING&&y&&g){h.status=ue.DOWNLOADED,this.activeSegments.delete(c);const E=new DataView(e.buffer,e.byteOffset+b,p);this.sourceBufferTaskQueue.append(E,a).then($=>$&&!a.aborted?o(c):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&y&&(c.loadedBytes=Math.min(p,r-b),c.loadedBytes>c.feedingBytes)){const E=new DataView(e.buffer,e.byteOffset+b+c.feedingBytes,c.loadedBytes-c.feedingBytes),$=c.loadedBytes===p?E:this.containerParser.parseFeedableSegmentChunk(E);$!=null&&$.byteLength&&(h.status=ue.PARTIALLY_FED,c.feedingBytes+=$.byteLength,this.sourceBufferTaskQueue.append($,a).then(L=>{if(a.aborted)n();else if(L)c.fedBytes+=$.byteLength,c.fedBytes===p&&o(c);else{if(c.feedingBytes<p)return;n()}}))}}}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===ue.PARTIALLY_FED||e.status===ue.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=ue.NONE),e.status=ue.PARTIALLY_EJECTED):e.status=ue.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=Mr(()=>Ks(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return ee(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?fe(this.destroyAbortController.signal,function(){return pe(this,arguments,function*(){const o=Ls(this.failedDownloads,this.tuning.downloadBackoff);yield yield _(new Promise(u=>setTimeout(u,o)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(o=>ee(this,void 0,void 0,function*(){if(!o)return;const{init:u,dataView:d,segments:l}=o,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c),this.segments.set(e.id,this.isLive?vr(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:I.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}pruneBuffer(e,t,i=!1){return ee(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||W(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===ue.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===ue.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===ue.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===ue.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=Mr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:I.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(W(this.sourceBuffer)||W(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!==ue.FED&&a!==ue.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=ue.PARTIALLY_EJECTED:r.status=ue.NONE)}}};var Zi;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(Zi||(Zi={}));let e0=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 St,this.subscription=new ce,this.fetchManifest=fe(this.abortAllController.signal,function(r){return pe(this,arguments,function*(){let a=r;this.requestQuic&&(a=li(a));const n=yield yield _(Ci(a,{signal:this.abortAllController.signal}).catch(ks));return n?(this.onHeadersReceived(n.headers),yield _(n.text())):yield _(null)})}.bind(this)),this.fetch=fe(this.abortAllController.signal,function(r,{rangeMethod:a=this.compatibilityMode?Zi.HEADER:Zi.PARAM,range:n,onProgress:o,priority:u="auto",signal:d,measureThroughput:l=!0}={}){var c,h,f,p;return pe(this,arguments,function*(){let S=r;const b=new Headers;if(n)switch(a){case Zi.HEADER:{b.append("Range",`bytes=${n.from}-${n.to}`);break}case Zi.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=li(S));let v=this.abortAllController.signal,y;if(d){const Y=new St;if(y=G(V(this.abortAllController.signal,"abort"),V(d,"abort")).subscribe(()=>{try{Y.abort()}catch(se){ks(se)}}),this.abortAllController.signal.aborted||d.aborted)try{Y.abort()}catch(se){ks(se)}v=Y.signal}const g=he(),E=yield yield _(Ci(S,{priority:u,headers:b,signal:v}).catch(ks)),$=he();if((c=this.throughputEstimator)===null||c===void 0||c.addRawRtt($-g),!E)return y==null||y.unsubscribe(),yield _(null);if(!E.ok||!E.body)return y==null||y.unsubscribe(),yield _(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 yield _(E.arrayBuffer());return(f=this.throughputEstimator)===null||f===void 0||f.addRawSpeed(Y.byteLength,he()-$),o==null||o(new DataView(Y),Y.byteLength),y==null||y.unsubscribe(),yield _(Y)}if(!o&&!l)return y==null||y.unsubscribe(),yield _(E.arrayBuffer());const[j,K]=E.body.tee(),H=j.getReader();l&&((p=this.throughputEstimator)===null||p===void 0||p.trackStream(K));let q=0;const Q=new ArrayBuffer(L),B=new Uint8Array(Q),M=new DataView(Q);let J=!1;const N=Y=>{y==null||y.unsubscribe(),J=!0,ks(Y)},C=fe(v,function({done:Y,value:se}){return pe(this,arguments,function*(){if(q===0&&this.lastRequestFirstBytes$.next(he()-g),v.aborted)return y==null||y.unsubscribe(),yield _(void 0);!Y&&se&&(B.set(se,q),q+=se.byteLength,o==null||o(M,q),yield yield _(H==null?void 0:H.read().then(C,N)))})}.bind(this));return yield yield _(H==null?void 0:H.read().then(C,N)),y==null||y.unsubscribe(),yield _(J?null:Q)})}.bind(this)),this.fetchByteRangeRepresentation=fe(this.abortAllController.signal,function(r,a,n){var o;return pe(this,arguments,function*(){if(r.type!==vt.BYTE_RANGE)return yield _(null);const{from:u,to:d}=r.initRange;let l=u,c=d,h=!1,f,p;r.indexRange&&(f=r.indexRange.from,p=r.indexRange.to,h=d+1===f,h&&(l=Math.min(f,u),c=Math.max(p,d))),l=Math.min(l,0);const S=yield yield _(this.fetch(r.url,{range:{from:l,to:c},priority:n,measureThroughput:!1}));if(!S)return yield _(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 yield _(this.fetch(r.url,{range:y,priority:n,measureThroughput:!1}));if(!$)return yield _(null);g=new DataView($)}const E=a.parseSegments(g,v,y);return yield _({init:v,dataView:new DataView(S),segments:E})})}.bind(this)),this.fetchTemplateRepresentation=fe(this.abortAllController.signal,function(r,a){return pe(this,arguments,function*(){if(r.type!==vt.TEMPLATE)return yield _(null);const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield yield _(this.fetch(n,{priority:a,measureThroughput:!1}));if(!o)return yield _(null);const u=r.segments.map(d=>Object.assign(Object.assign({},d),{status:ue.NONE,size:void 0}));return yield _({init:null,segments:u,dataView:new DataView(o)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=_o(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){var r,a;return ee(this,void 0,void 0,function*(){const{type:n}=e;switch(n){case vt.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case vt.TEMPLATE:return(a=yield this.fetchTemplateRepresentation(e,i))!==null&&a!==void 0?a:null;default:z(n)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}};const ks=s=>{if(!(s instanceof DOMException)||!(s.name==="AbortError"||s.code===20))throw s};var t0=ei,i0=Hs,s0=Ke,r0=s0("match"),a0=function(s){var e;return t0(s)&&((e=s[r0])!==void 0?!!e:i0(s)=="RegExp")},n0=qs,o0=String,d0=function(s){if(n0(s)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return o0(s)},u0=ti,l0=function(){var s=u0(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},c0=ht,h0=Mt,f0=Kr,p0=l0,eu=RegExp.prototype,m0=function(s){var e=s.flags;return e===void 0&&!("flags"in eu)&&!h0(s,"flags")&&f0(eu,s)?c0(p0,s):e},Po=yt,v0=ea,g0=Math.floor,nn=Po("".charAt),S0=Po("".replace),on=Po("".slice),b0=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,y0=/\$([$&'`]|\d{1,2})/g,T0=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=y0;return r!==void 0&&(r=v0(r),u=b0),S0(a,u,function(d,l){var c;switch(nn(l,0)){case"$":return"$";case"&":return s;case"`":return on(e,0,t);case"'":return on(e,n);case"<":c=r[on(l,1,-1)];break;default:var h=+l;if(h===0)return d;if(h>o){var f=g0(h/10);return f===0?d:f<=o?i[f-1]===void 0?nn(l,1):i[f-1]+nn(l,1):d}c=i[h-1]}return c===void 0?"":c})},E0=_t,$0=ht,Do=yt,tu=to,A0=Ie,w0=Gs,k0=a0,zi=d0,_0=Zr,P0=m0,D0=T0,R0=Ke,I0=R0("replace"),x0=TypeError,Zl=Do("".indexOf),L0=Do("".replace),iu=Do("".slice),C0=Math.max,su=function(s,e,t){return t>s.length?-1:e===""?t:Zl(s,e,t)};E0({target:"String",proto:!0},{replaceAll:function(e,t){var i=tu(this),r,a,n,o,u,d,l,c,h,f=0,p=0,S="";if(!w0(e)){if(r=k0(e),r&&(a=zi(tu(P0(e))),!~Zl(a,"g")))throw x0("`.replaceAll` does not allow non-global regexes");if(n=_0(e,I0),n)return $0(n,e,i,t);if(r)return L0(zi(i),e,t)}for(o=zi(i),u=zi(e),d=A0(t),d||(t=zi(t)),l=u.length,c=C0(1,l),f=su(o,u,0);f!==-1;)h=d?zi(t(u,f,o)):D0(u,o,f,[],void 0,t),S+=iu(o,p,f)+h,p=f+l,f=su(o,u,f+c);return p<o.length&&(S+=iu(o,p)),S}});var O0=Ao,B0=O0("String","replaceAll"),M0=B0,N0=M0,F0=N0,U0=F0,Ur=Wr(U0);const ru=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},dn=(s,e)=>{let t=s;t=Ur(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=Ur(t,n,(o,u)=>W(a)?o:W(u)?a:a.padStart(parseInt(u,10),"0"))}return t},V0=(s,e)=>{var t,i,r,a,n,o,u,d,l,c,h,f,p,S,b,v,y,g,E,$,L,j,K,H,q,Q,B,M,J,N,C,Y,se,ve,Ee,xe,Je,ft,re;const Xe=new DOMParser().parseFromString(s,"application/xml"),Le={video:[],audio:[],text:[]},Pe=Xe.children[0],Gt=Pe.getElementsByTagName("Period")[0],jt=Gt.children,ai=Pe.getAttribute("type")==="dynamic",Yt=Pe.getAttribute("availabilityStartTime"),Fi=Yt?new Date(Yt).getTime():void 0;let Ge;const ps=Pe.getAttribute("mediaPresentationDuration"),ms=Gt.getAttribute("duration"),mi=Pe.getElementsByTagName("vk:Attrs")[0],vs=mi==null?void 0:mi.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(ps)Ge=ru(ps);else if(ms){const $e=ru(ms);D($e)&&(Ge=$e)}else vs&&(Ge=parseInt(vs,10));let ua=0;const vi=(i=(t=Pe.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],la=vi.includes(Or.WEBM_AS_IN_FFMPEG)||vi.includes(Or.WEBM_AS_IN_SPEC)?rs.WEBM:rs.MP4;for(const $e of jt){const zt=$e.getAttribute("mimeType"),ca=$e.getAttribute("codecs"),gs=(r=$e.getAttribute("contentType"))!==null&&r!==void 0?r:zt==null?void 0:zt.split("/")[0],ha=(n=(a=$e.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],Ss=$e.querySelectorAll("Representation"),fa=$e.querySelector("SegmentTemplate");if(gs===Fe.TEXT){for(const X of Ss){const Ce=X.getAttribute("id")||"",qt=$e.getAttribute("lang"),it=(d=(u=(o=X.querySelector("BaseURL"))===null||o===void 0?void 0:o.textContent)===null||u===void 0?void 0:u.trim())!==null&&d!==void 0?d:"",gi=new URL(it,e).toString(),Si=Ce.includes("_auto");Le[Fe.TEXT].push({id:Ce,lang:qt,isAuto:Si,kind:Fe.TEXT,url:gi})}continue}for(const X of Ss){const Ce=(l=X.getAttribute("mimeType"))!==null&&l!==void 0?l:zt,qt=(h=(c=X.getAttribute("codecs"))!==null&&c!==void 0?c:ca)!==null&&h!==void 0?h:"",it=(p=(f=X.getAttribute("contentType"))!==null&&f!==void 0?f:Ce==null?void 0:Ce.split("/")[0])!==null&&p!==void 0?p:gs,gi=(b=(S=$e.getAttribute("profiles"))===null||S===void 0?void 0:S.split(","))!==null&&b!==void 0?b:[],Si=parseInt((v=X.getAttribute("width"))!==null&&v!==void 0?v:"",10),bs=parseInt((y=X.getAttribute("height"))!==null&&y!==void 0?y:"",10),ys=parseInt((g=X.getAttribute("bandwidth"))!==null&&g!==void 0?g:"",10)/1e3,Ts=(E=X.getAttribute("frameRate"))!==null&&E!==void 0?E:"",pa=($=X.getAttribute("quality"))!==null&&$!==void 0?$:void 0,ma=Ts?aa(Ts):void 0,va=(L=X.getAttribute("id"))!==null&&L!==void 0?L:(ua++).toString(10),ga=it==="video"?`${bs}p`:it==="audio"?`${ys}Kbps`:qt,Sa=`${va}@${ga}`,ba=(H=(K=(j=X.querySelector("BaseURL"))===null||j===void 0?void 0:j.textContent)===null||K===void 0?void 0:K.trim())!==null&&H!==void 0?H:"",Es=new URL(ba,e).toString(),ya=[...vi,...ha,...gi];let bi;const Ta=X.querySelector("SegmentBase"),je=(q=X.querySelector("SegmentTemplate"))!==null&&q!==void 0?q:fa;if(Ta){const st=(B=(Q=X.querySelector("SegmentBase Initialization"))===null||Q===void 0?void 0:Q.getAttribute("range"))!==null&&B!==void 0?B:"",[rt,Ti]=st.split("-").map(at=>parseInt(at,10)),Ze={from:rt,to:Ti},Et=(M=X.querySelector("SegmentBase"))===null||M===void 0?void 0:M.getAttribute("indexRange"),[Ei,Wt]=Et?Et.split("-").map(at=>parseInt(at,10)):[],$t=Et?{from:Ei,to:Wt}:void 0;bi={type:vt.BYTE_RANGE,url:Es,initRange:Ze,indexRange:$t}}else if(je){const st={representationId:(J=X.getAttribute("id"))!==null&&J!==void 0?J:void 0,bandwidth:(N=X.getAttribute("bandwidth"))!==null&&N!==void 0?N:void 0},rt=parseInt((C=je.getAttribute("timescale"))!==null&&C!==void 0?C:"",10),Ti=(Y=je.getAttribute("initialization"))!==null&&Y!==void 0?Y:"",Ze=je.getAttribute("media"),Et=(ve=parseInt((se=je.getAttribute("startNumber"))!==null&&se!==void 0?se:"",10))!==null&&ve!==void 0?ve:1,Ei=dn(Ti,st);if(!Ze)throw new ReferenceError("No media attribute in SegmentTemplate");const Wt=(Ee=je.querySelectorAll("SegmentTimeline S"))!==null&&Ee!==void 0?Ee:[],$t=[];let at=0;if(Wt.length){let $i=Et,nt=0;for(const Ai of Wt){const ot=parseInt((xe=Ai.getAttribute("d"))!==null&&xe!==void 0?xe:"",10),De=parseInt((Je=Ai.getAttribute("r"))!==null&&Je!==void 0?Je:"",10)||0,At=parseInt((ft=Ai.getAttribute("t"))!==null&&ft!==void 0?ft:"",10);nt=Number.isFinite(At)?At:nt;const et=ot/rt*1e3,Dt=nt/rt*1e3;for(let Qt=0;Qt<De+1;Qt++){const $s=dn(Ze,Object.assign(Object.assign({},st),{segmentNumber:$i.toString(10),segmentTime:(nt+Qt*ot).toString(10)})),Ui=(Dt||0)+Qt*et,Vi=Ui+et;$i++,$t.push({time:{from:Ui,to:Vi},url:$s})}nt+=(De+1)*ot,at+=(De+1)*et}}else if(D(Ge)){const nt=parseInt((re=je.getAttribute("duration"))!==null&&re!==void 0?re:"",10)/rt*1e3,Ai=Math.ceil(Ge/nt);let ot=0;for(let De=1;De<Ai;De++){const At=dn(Ze,Object.assign(Object.assign({},st),{segmentNumber:De.toString(10),segmentTime:ot.toString(10)}));$t.push({time:{from:ot,to:ot+nt},url:At}),ot+=nt}}bi={type:vt.TEMPLATE,baseUrl:Es,initUrl:Ei,totalSegmentsDurationMs:at,segments:$t}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!it||!Ce)continue;const yi={video:Fe.VIDEO,audio:Fe.AUDIO,text:Fe.TEXT}[it];yi&&Le[yi].push({id:Sa,kind:yi,segmentReference:bi,profiles:ya,duration:Ge,bitrate:ys,mime:Ce,codecs:qt,width:Si,height:bs,fps:ma,quality:pa})}}return{dynamic:ai,liveAvailabilityStartTime:Fi,duration:Ge,container:la,representations:Le}},Wn=1e3,au=["timeupdate","progress","play","seeked","stalled","waiting"];var pt;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(pt||(pt={}));let H0=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new ce,this.representationSubscription=new ce,this.state$=new me(pt.NONE),this.currentVideoRepresentation$=new T(void 0),this.currentVideoRepresentationInit$=new T(void 0),this.error$=new O,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 O,this.gapWatchdogStarted=!1,this.destroyController=new St,this.initManifest=fe(this.destroyController.signal,function(t,i,r){var a;return pe(this,arguments,function*(){this.element=t,this.manifestUrlString=qe(i,r,Te.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(pt.MANIFEST_READY),this.manifest=yield yield _(this.updateManifest()),!((a=this.manifest)===null||a===void 0)&&a.representations.video.length?this.state$.setState(pt.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:I.PARSER,message:"No playable video representations"})})}.bind(this)),this.updateManifest=fe(this.destroyController.signal,function(){var t;return pe(this,arguments,function*(){const i=yield yield _(this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:I.NETWORK,message:"Failed to load manifest",thrown:n})}));if(!i)return yield _(this.manifest);let r;try{r=V0(i!=null?i:"",this.manifestUrlString)}catch(n){this.error$.next({id:"ManifestParsing",category:I.PARSER,message:"Failed to parse MPD manifest",thrown:n})}if(!r)return yield _(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===Fe.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)),yield _(Object.assign(Object.assign({},r),{representations:xi(Object.entries(r.representations).map(([n,o])=>[n,o.filter(a)]))}))})}.bind(this)),this.initRepresentations=fe(this.destroyController.signal,function(t,i){return pe(this,arguments,function*(){R(this.manifest),R(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(pt.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 Zd(Fe.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],D(i)&&(this.audioBufferManager=new Zd(Fe.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(Ii(Wn).subscribe(o=>{var u;if(!((u=this.element)===null||u===void 0)&&u.paused){const d=Lr(this.manifestUrlString,Te.DASH_CMAF_OFFSET_P);this.manifestUrlString=qe(this.manifestUrlString,d+1e3,Te.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(G(...au.map(o=>V(this.element,o))).pipe(Sc(Wn),P(o=>this.element?tt(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(p=>{var S,b;return(b=(S=p.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(u=>ee(this,void 0,void 0,function*(){R(this.element);const d=this.element.playbackRate,l=Lr(this.manifestUrlString,Te.DASH_CMAF_OFFSET_P),c=qy*d,h=Qy*d,f=Wy*d;o=u>o?u:o;const p=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=qe(this.manifestUrlString,g,Te.DASH_CMAF_OFFSET_P)}(p||b||S)&&(yield this.updateLive(),o=0)})))}const a=G(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(P(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=G(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(P(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.representationSubscription.add(G(this.forceEnded$,Be({allBuffersFull:a,someBufferEnded:n}).pipe(oe(({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:I.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:u})}})),this.representationSubscription.add(G(...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 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 yield _(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)])):yield yield _(this.videoBufferManager.startWith(t)),this.state$.setState(pt.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=Ii(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:I.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new e0({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}seekLive(e){var t,i,r,a;return ee(this,void 0,void 0,function*(){R(this.element),this.manifestUrlString=qe(this.manifestUrlString,e,Te.DASH_CMAF_OFFSET_P),this.manifest=yield this.updateManifest(),yield(t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((i=this.manifest)===null||i===void 0?void 0:i.representations.video),yield(r=this.audioBufferManager)===null||r===void 0?void 0:r.seekLive((a=this.manifest)===null||a===void 0?void 0:a.representations.audio)})}initBuffer(){R(this.element),this.state$.setState(pt.RUNNING),this.subscription.add(G(...au.map(e=>V(this.element,e)),V(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:I.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(V(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(V(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&as(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}switchRepresentation(e,t){return ee(this,void 0,void 0,function*(){const i={[Fe.VIDEO]:this.videoBufferManager,[Fe.AUDIO]:this.audioBufferManager,[Fe.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)})}seek(e,t){var i,r,a,n,o;R(this.element),R(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),as(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(pt.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}updateLive(){var e;return ee(this,void 0,void 0,function*(){this.manifest=yield 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 G0{constructor(e,t){this.fov=e,this.orientation=t}}class j0{constructor(e,t){this.rotating=!1,this.fading=!1,this.lastTickTS=0,this.lastCameraTurnTS=0,this.fadeStartSpeed=null,this.fadeTime=0,this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/Math.pow(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,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=Object.assign({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}const t=e-this.lastTickTS,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*Math.pow(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*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 Y0=`#define GLSLIFY 1
|
|
38
|
-
attribute vec2 a_vertex;attribute vec2 a_texel;varying vec2 v_texel;void main(void){gl_Position=vec4(a_vertex,0.0,1.0);v_texel=a_texel;}`,
|
|
37
|
+
`}),N}return d==null||d.recordSwitch(M),M};var Qe=s=>new URL(s).hostname;const jb=300,Us=(s,e=jb)=>new Yr(t=>{const{width:i,height:r}=s.getBoundingClientRect();if(t.next({width:i,height:r}),!window.ResizeObserver)return;const a=new ResizeObserver(vc(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),I(u)&&I(d)&&t.next({width:u,height:d})},e));return a.observe(s),()=>a.disconnect()});class Xs{constructor(){this.onDroopedVideoFramesLimit$=new O,this.subscription=new ce,this.playing=!1,this.tracks=[],this.forceChecker$=new O,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&&!Ii(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&&ts(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(V(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=Ri(this.droppedFramesChecker.checkTime).pipe(oe(()=>this.playing),oe(()=>{const r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(lt(this.droppedFramesChecker.checkTime)),i=G(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])=>$r(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 ws={};var ne;(function(s){s.DOWNLOADING_LIB="downloading_lib",s.STOPPED="stopped",s.STREAM_INITIALIZED="stream_initialized",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(ne||(ne={}));const Ie=(s,e)=>new Yr(t=>{const i=r=>t.next(r);return s.on(e,i),()=>s.off(e,i)});class zd{constructor(e){this.subscription=new ce,this.videoState=new me(ne.DOWNLOADING_LIB),this.textTracksManager=new Pt,this.droppedFramesManager=new Xs,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 Js,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===ne.DOWNLOADING_LIB||t===ne.STREAM_INITIALIZED))switch((r==null?void 0:r.to)!==m.PAUSED&&a.state===ie.Requested&&t!==ne.STOPPED&&i!==m.STOPPED&&(n?this.seek(a.position-this.liveOffset.getTotalPausedTime()):this.seek(a.position)),i){case m.STOPPED:{switch(t){case ne.STOPPED:break;case ne.PLAYING:case ne.PAUSED:case ne.READY:this.stop();break;default:z(t)}break}case m.READY:{switch(t){case ne.STOPPED:this.prepare();break;case ne.PLAYING:case ne.PAUSED:case ne.READY:break;default:z(t)}break}case m.PLAYING:{switch(t){case ne.PLAYING:break;case ne.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 ne.READY:this.play();break;case ne.STOPPED:this.prepare();break;default:z(t)}break}case m.PAUSED:{switch(t){case ne.PLAYING:this.pause(),this.liveOffset.pause();break;case ne.PAUSED:break;case ne.READY:this.videoState.setState(ne.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED);break;case ne.STOPPED:this.prepare();break;default:z(t)}break}default:z(i)}},this.video=Ft(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(Qe(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);Ks(import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(ws.MediaPlayer=r.MediaPlayer,ws.Debug=r.Debug,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){D(ws.MediaPlayer,"dashjs not loaded"),D(ws.Debug,"dashjs not loaded"),this.player=ws.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?sa(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&Tb(this.player),Sb(this.player),this.params.tuning.requestQuick&&yb(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(ne.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(Us(this.video),this.elementSize$),r(Ie(this.player,"error").pipe(P(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(Ie(this.player,"playbackError").pipe(P(v=>({id:"DashJSPlayback",message:v.error}))),e.error$);const a=Ie(this.player,"qualityChangeRendered").pipe(oe(({mediaType:v})=>v==="video"),P(({newQuality:v})=>{var E;return(E=this.videoTracks$.getValue().find(({bitrateInfo:$})=>$.qualityIndex===v))===null||E===void 0?void 0:E.track}));a.pipe(oe(I)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(oe(({to:v})=>v===ne.STREAM_INITIALIZED),_e()).subscribe(()=>{this.subscription.add(kt(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(W(v))return;const $=(E=this.videoTracks$.getValue().find(({track:x})=>x.id===v.id))===null||E===void 0?void 0:E.bitrateInfo;$&&this.player.setQualityFor("video",$.qualityIndex)},{changed$:a,onError:i}))},i)),this.subscription.add(kt(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(Ie(this.player,"bufferStateChanged").pipe(oe(({mediaType:v})=>v==="video"),P(({state:v})=>v==="bufferStalled")),e.isBuffering$),r(Ie(this.player,"fragmentLoadingStarted"),({mediaType:v,request:{url:E}})=>{var $,x;const j=this.player.getDashMetrics(),K=j.getLatestFragmentRequestHeaderValueByID(v,"X-Reused"),H=($=j.getLatestFragmentRequestHeaderValueByID(v,"X-Delivery-Type"))!==null&&$!==void 0?$:Ms.HTTP1,q=(x={1:!0,0:!1}[K])!==null&&x!==void 0?x:void 0;this.params.output.httpConnectionType$.next(H),this.params.output.httpConnectionReused$.next(q),e.hostname$.next(Qe(E))}),r(Ie(this.player,"streamInitialized"),({streamInfo:{duration:v,manifestInfo:{isDynamic:E,availableFrom:$}}})=>{this.isLive$.next(E),this.availableFrom$.next($.getTime()),E||e.duration$.next(v);const x=[],j=this.player.getQualityFor("video");let K;for(const H of this.player.getBitrateInfoListFor("video")){const q=H.qualityIndex.toString(10),Q=ci(H),B=H.bitrate/1e3,M={width:H.width,height:H.height},X=this.frameRatesByFrameHeight[H.height];if(Q){const N={id:q,quality:Q,bitrate:B,size:M,fps:X};x.push({track:N,bitrateInfo:H}),H.qualityIndex===j&&(K=N)}}this.videoTracks$.next(x),e.availableVideoTracks$.next(x.map(({track:H})=>H)),K&&e.currentVideoTrack$.next(K),this.videoState.setState(ne.STREAM_INITIALIZED),this.videoState.startTransitionTo(ne.READY)}),r(Ie(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(G(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=Ni(this.videoTracks$.getValue().map(({track:j})=>j),{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 x=this.videoTracks$.getValue().find(({track:j})=>j===E);x!=null&&x.bitrateInfo&&this.player.setQualityFor("video",x==null?void 0:x.bitrateInfo.qualityIndex,!1)}),r(Be({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(oe(I))}).pipe(oe(({isLive:v})=>v),P(({maxSeekBackTime:v})=>-v/1e3)),this.params.output.duration$);const n=Ie(this.player,"playbackTimeUpdated").pipe(P(({time:v})=>v!=null?v:0));r(Be({availableFrom:this.availableFrom$.pipe(oe(I)),currentTime:n}),({availableFrom:v,currentTime:E})=>this.params.output.liveTime$.next(v+E*1e3)),r(n.pipe(oe(()=>this.isLive$.getValue()===!1)),e.position$),r(Ie(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),r(Ie(this.player,"playbackEnded"),e.endedEvent$),r(Ie(this.player,"playbackProgress").pipe(P(()=>Fl(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(Ie(this.player,"playbackPlaying"),()=>{this.videoState.setState(ne.PLAYING),L(t.playbackState,m.PLAYING)}),r(Ie(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(ne.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(Ie(this.player,"playbackPaused"),()=>{this.videoState.setState(ne.PAUSED),L(t.playbackState,m.PAUSED)}),r(Ie(this.player,"canPlay"),()=>{var v;((v=this.videoState.getTransition())===null||v===void 0?void 0:v.to)===ne.READY&&this.videoState.setState(ne.READY)}),r(this.isLive$,e.isLive$),r(Us(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=G(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,We(["init"])).pipe(lt(0));r(o,this.syncPlayback);const{playbackDuration$:u,ping$:d,connectionType$:l,connectionReused$:c}=bb(this.player);r(l,this.params.output.httpConnectionType$),r(c,this.params.output.httpConnectionReused$),r(u,this.maxSeekBackTime$),r(d.pipe(_e()),e.firstBytesEvent$),r(Ie(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(Be({isLive:this.isLive$,isShort:e.duration$.pipe(P(v=>v<60))}),({isLive:v,isShort:E})=>{const $=!v&&E;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:$}}})}),r(n.pipe(oe(v=>v>this.params.tuning.insufficientBufferRuleMargin),_e()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(Ie(this.player,"manifestLoaded").pipe(_e()).subscribe(()=>{this.subscription.add(Ie(this.player,"playbackPlaying").pipe(_e(),ss(void 0)).subscribe(e.firstFrameEvent$,i))},i)),r(Ie(this.player,"manifestLoaded"),v=>{var E,$,x,j,K,H,q;if(!(($=(E=v.data)===null||E===void 0?void 0:E.Period)===null||$===void 0)&&$.AdaptationSet){const Q=[];for(const B of(j=(x=v.data)===null||x===void 0?void 0:x.Period)===null||j===void 0?void 0:j.AdaptationSet)if(B.contentType==="text"){const M=(K=B.Representation)===null||K===void 0?void 0:K.id,X=new URL((H=B.Representation)===null||H===void 0?void 0:H.BaseURL,(q=v.data)===null||q===void 0?void 0:q.baseUri).toString(),N="internal",C=B.lang;Q.push({id:M,url:X,type:N,language:C})}t.internalTextTracks.startTransitionTo(Q)}}),this.subscription.add(fi(this.video,t.isLooped,i));const{volumeState$:h,looped$:f,playbackRateState$:p,inPiP$:S,inFullscreen$:b,pause$:g,playing$:y}=Vt(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(P(v=>v.map(({track:E})=>E)))}),this.subscription.add(Nt(this.video,t.volume,h,i)),this.subscription.add(h.subscribe(e.volume$,i)),this.subscription.add(f.subscribe(e.loopedEvent$)),this.subscription.add(ii(this.video,t.playbackRate,p,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(ne.STOPPED),L(this.params.desiredState.playbackState,m.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(ne.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=qe(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Te.PLAYBACK_SHIFT);this.player.attachSource(r)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(ne.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(ne.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){}Ut(this.video),this.params.output.element$.next(void 0)}}var hs=s=>{switch(s){case"mobile":return ft.Q_144P;case"lowest":return ft.Q_240P;case"low":return ft.Q_360P;case"sd":case"medium":return ft.Q_480P;case"hd":case"high":return ft.Q_720P;case"fullhd":case"full":return ft.Q_1080P;case"quadhd":case"quad":return ft.Q_1440P;case"ultrahd":case"ultra":return ft.Q_2160P}};const qd=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 si=s=>J(void 0,void 0,void 0,function*(){const e=s.muted;try{yield s.play()}catch(t){if(!qd(t))return!1;if(e)return console.warn(t),!1;s.muted=!0;try{yield s.play()}catch(i){return qd(i)&&(s.muted=!1,console.warn(i)),!1}}return!0});function ze(){return he()}function Vl(s){return ze()-s}function Wd(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 Yb(s,e,t){const i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function _r(s,e,t,i){const r=window.XMLHttpRequest;let a,n,o,u=!1,d=0,l,c,h=!1,f="arraybuffer",p=7e3,S=2e3,b=()=>{if(u)return;D(l);const B=Vl(l);let M;if(B<S){M=S-B,setTimeout(b,M);return}S*=2,S>p&&(S=p),n&&n.abort(),n=new r,x()};const g=B=>(a=B,Q),y=B=>(c=B,Q),v=()=>(f="json",Q),E=()=>{if(!u){if(--d>=0){b(),i&&i();return}u=!0,c&&c(),t&&t()}},$=B=>(h=B,Q),x=()=>{l=ze(),n=new r,n.open("get",s);let B=0,M,X=0;const N=()=>(D(l),Math.max(l,Math.max(M||0,X||0)));if(a&&n.addEventListener("progress",C=>{const Y=ze();a.updateChunk&&C.loaded>B&&(a.updateChunk(N(),C.loaded-B),B=C.loaded,M=Y)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(u)return;D(n);const C=n.status;if(C>=200&&C<300){if(n.response.byteLength&&a){const Y=n.response.byteLength-B;Y&&a.updateChunk&&a.updateChunk(N(),Y)}c&&c(),n&&e(n.response)}else E()}),n.addEventListener("error",()=>{E()}),h){const C=()=>{D(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(X=ze(),n.removeEventListener("readystatechange",C))};n.addEventListener("readystatechange",C)}return n.responseType=f,n.send(),Q},Q={withBitrateReporting:g,withParallel:$,withJSONResponse:v,withRetryCount:B=>(d=B,Q),withRetryInterval:(B,M)=>(I(B)&&(S=B),I(M)&&(p=M),Q),withTimeout:B=>(o=B,Q),withFinally:y,send:x,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return Q}const zb=100,qb=2e3,Wb=500;let Qb=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-Wb;if(t-e>qb){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>zb&&(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 Kb{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=ze(),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=ze()-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=_r(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=ze()}_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=ze();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 pr=1e4,mr=3,Jb=300,Xb=2e3,Zb=6e4,ey=10,ty=1,iy=500;class sy{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 Qb(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Wd(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=Wd(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||I(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=()=>{Yb(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 Kb(mr,pr,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,$,x)=>{u&&u.abort(),u=_r(this.urlResolver.resolve(E,!1),$,x,()=>this._retryCallback()).withTimeout(pr).withBitrateReporting(this.bitrateSwitcher).withRetryCount(mr).withFinally(()=>{u=null}).send()},f=(E,$,x)=>{D(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),$,x,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},p=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)p(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){p(1);return}const x=ze()-1e4;let j=0;for(let H=0;H<this.bufferStates.length;H++){const q=this.bufferStates[H];E=Math.min(E,q.buf),q.ts<x&&j++}this.bufferStates.splice(0,j),t(`update playback rate; minBuffer=${E} drop=${j} jitter=${this.sourceJitter}`);let K=E-ty;this.sourceJitter>=0?K-=this.sourceJitter/2:this.sourceJitter-=1,K>3?p(1.15):K>1?p(1.1):K>.3?p(1.05):p(1)}},g=E=>{let $;const x=()=>$&&$.start?$.start.length:0,j=C=>$.start[C]/1e3,K=C=>$.dur[C]/1e3,H=C=>$.fragIndex+C,q=(C,Y)=>({chunkIdx:H(C),startTS:j(C),dur:K(C),discontinuity:Y}),Q=()=>{let C=0;if($&&$.dur){let Y=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,se=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ve=Y;this.sourceJitter>1&&(ve+=this.sourceJitter-1);let Ee=$.dur.length-1;for(;Ee>=0&&(ve-=$.dur[Ee],!(ve<=0));--Ee);C=Math.min(Ee,$.dur.length-1-se),C=Math.max(C,0)}return q(C,!0)},B=C=>{const Y=x();if(!(Y<=0)){if(I(C)){for(let se=0;se<Y;se++)if(j(se)>C)return q(se)}return Q()}},M=C=>{const Y=x(),se=C?C.chunkIdx+1:0,ve=se-$.fragIndex;if(!(Y<=0)){if(!C||ve<0||ve-Y>ey)return t(`Resync: offset=${ve} bChunks=${Y} chunk=`+JSON.stringify(C)),Q();if(!(ve>=Y))return q(se-$.fragIndex,!1)}},X=(C,Y,se)=>{d&&d.abort(),d=_r(this.urlResolver.resolve(C,!0,this.lowLatency),Y,se,()=>this._retryCallback()).withTimeout(pr).withRetryCount(mr).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(C,Y)=>{X(E,se=>{if(!c())return;$=se;const ve=!!$.lowLatency;ve!==this.lowLatency&&S(ve);let Ee=0;for(let Le=0;Le<$.dur.length;++Le)Ee+=$.dur[Le];Ee>0&&(D(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Ee/$.dur.length)),r({name:"index",zeroTime:$.zeroTime,shiftDuration:$.shiftDuration}),this.sourceJitter=$.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,$.jitter/1e3)):1,C(B(Y))},()=>this._handleNetworkError())},nextChunk:M}},y=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),D(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:E=>{const{videoElement:$,logger:x}=this.params;let j=g(e.jidxUrl),K,H,q,Q,B=0,M,X,N;const C=()=>{M&&(clearTimeout(M),M=void 0);const re=Math.max(iy,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),He=B+re,Xe=ze(),xe=Math.min(1e4,He-Xe);B=Xe;const Pe=()=>{d||c()&&j.seek(()=>{c()&&(B=ze(),Y(),C())})};xe>0?M=window.setTimeout(()=>{this.paused?C():Pe()},xe):Pe()},Y=()=>{let re;for(;re=j.nextChunk(Q);)Q=re,Je(re);const He=j.nextChunk(q);if(He){if(q&&He.discontinuity){x("Detected discontinuity; restarting playback"),this.paused?C():(y(),this._initPlayerWith(e));return}Le(He)}else C()},se=(re,He)=>{if(!c()||!this.sourceBuffer)return;let Xe,xe,Pe;const Gt=jt=>{window.setTimeout(()=>{c()&&se(re,He)},jt)};if(this.sourceBuffer.updating)x("Source buffer is updating; delaying appendBuffer"),Gt(100);else{const jt=ze(),ai=$.currentTime;!this.paused&&$.buffered.length>1&&X===ai&&jt-N>500&&(x("Stall suspected; trying to fix"),this._fixupStall()),X!==ai&&(X=ai,N=jt);const Yt=this._getBufferSizeSec();if(Yt>30)x(`Buffered ${Yt} seconds; delaying appendBuffer`),Gt(2e3);else try{this.sourceBuffer.appendBuffer(re),this.videoPlayStarted?(this.bufferStates.push({ts:jt,buf:Yt}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),He&&He()}catch(Fi){if(Fi.name==="QuotaExceededError")x("QuotaExceededError; delaying appendBuffer"),Pe=this.sourceBuffer.buffered.length,Pe!==0&&(Xe=this.sourceBuffer.buffered.start(0),xe=ai,xe-Xe>4&&this.sourceBuffer.remove(Xe,xe-3)),Gt(1e3);else throw Fi}}},ve=()=>{H&&K&&(x([`Appending chunk, sz=${H.byteLength}:`,JSON.stringify(q)]),se(H,function(){H=null,Y()}))},Ee=re=>e.fragUrlTemplate.replace("%%id%%",re.chunkIdx),Le=re=>{c()&&f(Ee(re),(He,Xe)=>{if(c()){if(Xe/=1e3,H=He,q=re,n=re.startTS,Xe){const xe=Math.min(10,re.dur/Xe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*xe:xe}ve()}},()=>this._handleNetworkError())},Je=re=>{c()&&(D(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Ee(re),!1)))},ht=re=>{c()&&(e.cachedHeader=re,se(re,()=>{K=!0,ve()}))};a=!0,j.seek(re=>{if(c()){if(B=ze(),!re){C();return}Q=re,!W(E)||re.startTS>E?Le(re):(q=re,Y())}},E),e.cachedHeader?ht(e.cachedHeader):h(e.headerUrl,ht,()=>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(),I(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,D(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return I(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let h,f,p;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(f=this._getBufferSizeSec(),p=c/this.bitrate,f>10&&p>.8||f>15&&p>.5||f>20&&p>.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 p=ze();if(this.chunkRateEstimator.addInterval(h,p,f)){const b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:p-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&&Vl(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=ze();c<o&&(n=h),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=_r(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(pr).withRetryCount(mr).withRetryInterval(Jb,Xb).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;si(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))},Zb))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var ae;(function(s){s.STOPPED="stopped",s.MANIFEST_READY="manifest_ready",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(ae||(ae={}));const ry=[ae.PAUSED,ae.PLAYING,ae.READY],ay=[ae.PAUSED,ae.PLAYING,ae.READY];class ny{constructor(e){this.subscription=new ce,this.videoState=new me(ae.STOPPED),this.representations$=new T([]),this.textTracksManager=new Pt,this.droppedFramesManager=new Xs,this.maxSeekBackTime$=new T(1/0),this.zeroTime$=new T(void 0),this.liveOffset=new Js,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=hs(c.name))!==null&&n!==void 0?n:ci(c.video),p=c.bitrate/1e3,S=Object.assign({},c.video);if(!f)continue;const b={id:h,quality:f,bitrate:p,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)===ae.MANIFEST_READY&&this.videoState.setState(ae.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),I(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===m.STOPPED){r!==ae.STOPPED&&(this.videoState.startTransitionTo(ae.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(ae.STOPPED));return}if(a)return;const d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(ay.includes(r)&&(d||l)){this.prepare();return}if((o==null?void 0:o.to)!==m.PAUSED&&u.state===ie.Requested&&ry.includes(r)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(r){case ae.STOPPED:this.videoState.startTransitionTo(ae.MANIFEST_READY),this.dash.attachSource(qe(this.params.source.url));return;case ae.MANIFEST_READY:this.videoState.startTransitionTo(ae.READY),this.prepare();break;case ae.READY:if(n===m.PAUSED)this.videoState.setState(ae.PAUSED);else if(n===m.PLAYING){this.videoState.startTransitionTo(ae.PLAYING);const c=o==null?void 0:o.from;c&&c===m.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(ae.PAUSED)})}return;case ae.PLAYING:n===m.PAUSED&&(this.videoState.startTransitionTo(ae.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case ae.PAUSED:if(n===m.PLAYING)if(this.videoState.startTransitionTo(ae.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(ae.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(qe(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})};G(this.videoState.stateChangeStarted$.pipe(P(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(P(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=Ft(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(Qe(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=Vt(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(P(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)===ae.READY&&this.videoState.setState(ae.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(ae.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===ie.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(ae.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(ye(),P(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Be({zeroTime:this.zeroTime$.pipe(oe(I)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(fi(this.video,this.params.desiredState.isLooped,t)).add(Nt(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(ii(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&&gc(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case ae.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(m.STOPPED);break;case ae.MANIFEST_READY:case ae.READY:((a=this.params.desiredState.playbackState.getTransition())===null||a===void 0?void 0:a.to)===m.READY&&this.params.desiredState.playbackState.setState(m.READY);break;case ae.PAUSED:this.params.desiredState.playbackState.setState(m.PAUSED);break;case ae.PLAYING:this.params.desiredState.playbackState.setState(m.PLAYING);break;default:return z(r.to)}},t)).add(G(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,We(["init"])).pipe(lt(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),Ut(this.video)}createLiveDashPlayer(){const e=new sy({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&&I(u)?u:Ni(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,p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l&&(h||c!==f)&&this.setVideoTrack(l),p&&this.setAutoQuality(d),h||p||c!==f){const S=(n=o.find(({track:b})=>b.id===c))===null||n===void 0?void 0:n.representation;D(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;D(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===m.PAUSED&&i===ae.PAUSED,a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(qe(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}}var wo=s=>{var e,t;const i=s.get("X-Delivery-Type"),r=s.get("X-Reused"),a=i===null?Ms.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}},tt=(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 oy=s=>{const e=document.createElement("a");return e.href=s,e.origin},dy=s=>{const e=document.createElement("a");return e.href=s,e.host};class Hl{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=Li(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(dy(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 xr{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(xr._str2ua(S.substr(u))),u=S.length};let p=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(p=li(p)),this._lastXhr=new Hl(p,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=xr._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 uy{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=li(i)),new Hl(i,t,r=>{this.attachManifest(r,t,oy(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,p,S,b,g,y,v,E,$,x,j,K,H,q,Q,B;const M=d.getElementsByTagName("SegmentBase")[0],X=M&&n(M,"indexRange").split("-"),N=M&&M.getElementsByTagName("Initialization")[0],C=N&&n(N,"range").split("-");if(!C||!X){const Je=d.parentElement;if((Je==null?void 0:Je.getAttribute("contentType"))==="text"){const ht=(l=d.getAttribute("id"))!==null&&l!==void 0?l:void 0,re=(i?i+"/":"")+((p=(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||p===void 0?void 0:p.data),He=(S=Je.getAttribute("lang"))!==null&&S!==void 0?S:void 0;re&&u.push({id:ht,url:re,language:He})}return}const Y=.1,se=Number((b=d.attributes.getNamedItem("bandwidth"))===null||b===void 0?void 0:b.value),ve=(i?i+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let Ee;const Le=(y=(g=d.attributes.getNamedItem("frameRate"))===null||g===void 0?void 0:g.value)!==null&&y!==void 0?y:void 0;Ee=Le?sa(Le):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:se,baseURL:ve,failoverHosts:t,indexFrom:Number(X[0]),indexTo:Number(X[1]),initFrom:Number(C[0]),initTo:Number(C[1]),codecs:(x=($=d.attributes.getNamedItem("codecs"))===null||$===void 0?void 0:$.value)!==null&&x!==void 0?x:void 0,mimeType:(K=(j=d.attributes.getNamedItem("mimeType"))===null||j===void 0?void 0:j.value)!==null&&K!==void 0?K:void 0,fps:Ee,bufferSize:Y*se/8,bufferLength:Y,name:(q=(H=d.attributes.getNamedItem("okQuality"))===null||H===void 0?void 0:H.value)!==null&&q!==void 0?q:void 0,id:(B=(Q=d.attributes.getNamedItem("id"))===null||Q===void 0?void 0:Q.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),p=u+n.getUint32(a+4,!1);a+=12,e.refs.push({fromTime:u/o,toTime:p/o,fromOffset:d,toOffset:f-1}),d=f,u=p}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 p=this._buffer.getNextWithGap(f);p&&(this._video.currentTime=p.from)}catch(p){throw this._params.onError("GapSyncError",`Seek Error ${String(p)}`,p),p}},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 xr({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||W(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 de;(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"})(de||(de={}));const ly=[de.PAUSED,de.PLAYING];class cy{constructor(e){this.videoState=new me(de.STOPPED),this.subscription=new ce,this.representations$=new T([]),this.currentRepresentation$=new T(void 0),this.textTracksManager=new Pt,this.droppedFramesManager=new Xs,this.elementSize$=new T(void 0),this.dashLiteEvents={idxRequestPing$:new O,responseHeaders$:new O,manifestReady$:new O,representationPlay$:new O,error$:new O},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&&hs(u.name))!==null&&n!==void 0?n:ci(u),c=u.bandwidth/1e3,h={width:u.width,height:u.height},f=u.fps;if(!l)continue;const p={id:d,quality:l,bitrate:c,size:h,fps:f};o.push({track:p,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(de.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 D(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===m.STOPPED){t!==de.STOPPED&&(this.videoState.startTransitionTo(de.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(de.STOPPED),L(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(!i)switch((a==null?void 0:a.to)!==m.PAUSED&&n.state===ie.Requested&&ly.includes(t)&&this.seek(n.position,n.forcePrecise),t){case de.STOPPED:this.videoState.startTransitionTo(de.MANIFEST_LOADED),this.prepare();return;case de.MANIFEST_LOADED:this.videoState.startTransitionTo(de.INITIAL_REPRESENTATION_SELECTED);return;case de.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(de.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case de.METADATA_LOADED:this.videoState.startTransitionTo(de.READY),this.dash.updateRefsForCurrentTime();return;case de.READY:r===m.READY?L(this.params.desiredState.playbackState,m.READY):r===m.PAUSED?(this.videoState.setState(de.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED)):r===m.PLAYING&&(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed());return;case de.PLAYING:r===m.PAUSED?(this.videoState.startTransitionTo(de.PAUSED),this.video.pause()):(a==null?void 0:a.to)===m.PLAYING&&L(this.params.desiredState.playbackState,m.PLAYING);return;case de.PAUSED:r===m.PLAYING?(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===m.PAUSED&&L(this.params.desiredState.playbackState,m.PAUSED);return;default:return z(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),G(this.videoState.stateChangeStarted$.pipe(P(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(P(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=Ft(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(Qe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new _b(this.video),this.dash=new uy({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=Vt(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(()=>{W(this.params.desiredState.seekState.getState().state!==ie.Applying)&&(this.videoState.getState()===de.PLAYING||this.videoState.getState()===de.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(fi(this.video,t.isLooped,i)),this.subscription.add(Nt(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ii(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(P(o=>o.map(({track:u})=>u)))}),n(Us(this.video),this.elementSize$),this.subscription.add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===de.READY&&this.videoState.setState(de.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED)})).add(a.playing$.subscribe(()=>{this.videoState.setState(de.PLAYING),L(this.params.desiredState.playbackState,m.PLAYING)},i)).add(a.loadedMetadata$.subscribe(()=>{this.videoState.setState(de.METADATA_LOADED)},i)).add(a.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},i)).add(this.dashLiteEvents.error$.pipe(P(({id:o,message:u,thrown:d})=>({id:`DashLite_${o}`,category:R.WTF,message:u,thrown:d}))).subscribe(this.params.output.error$)).add(G(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$,V(this.video,"progress")).pipe(P(()=>{var o,u,d,l;const c=this.currentRepresentation$.getValue(),h=this.representations$.getValue(),f=this.params.desiredState.autoVideoTrackSwitching.getTransition(),p=(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&&I(p))y=p;else{const v=tt(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=Ni(h.map(({track:j})=>j),{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:j})=>j===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 x=t.autoVideoTrackLimits.getTransition();x&&e.autoVideoTrackLimits$.next(x.to)}return I(y)?(l=h.find(({track:v})=>v.id===y))===null||l===void 0?void 0:l.representation:void 0}),ye()).subscribe(this.currentRepresentation$,i)).add(Be({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(oe(o=>o.to===de.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(oe(I))}).pipe(_e()).subscribe(()=>this.videoState.setState(de.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(oe(I),ye((o,u)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?o.height<=u.height:o===u)).subscribe(o=>{const u=tt(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(Qe(o.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:u,reused:d}=wo(o);this.params.output.httpConnectionType$.next(u),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(_e(),ss(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(oe(I)).subscribe(this.handleRepresentationPlay,i)).add(G(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,We(["init"])).pipe(lt(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),Ut(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(){si(this.video).then(e=>{e||(this.videoState.setState(de.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:R.DOM,thrown:e}))}}var Fe;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(Fe||(Fe={}));var Cr;(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"})(Cr||(Cr={}));var vt;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(vt||(vt={}));var ue;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(ue||(ue={}));var rs;(function(s){s.MP4="mp4",s.WEBM="webm"})(rs||(rs={}));var Or;(function(s){s[s.RECTANGULAR=0]="RECTANGULAR",s[s.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",s[s.CUBEMAP=2]="CUBEMAP",s[s.MESH=3]="MESH"})(Or||(Or={}));var Ae;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Ae||(Ae={}));class Qd{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 Gl extends Qd{constructor(){super(),this.listeners||Qd.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 jl=class{constructor(){Object.defineProperty(this,"signal",{value:new Gl,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&&(jl.prototype[Symbol.toStringTag]="AbortController",Gl.prototype[Symbol.toStringTag]="AbortSignal");function Yl(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 hy(s){typeof s=="function"&&(s={fetch:s});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!Yl({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,p)=>{l.addEventListener("abort",()=>p(c),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([h,n(u,d)])}return n(u,d)},Request:a}}const ra=Yl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),zl=ra?hy({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ci=ra?zl.fetch:window.fetch;ra?zl.Request:window.Request;const St=ra?jl:window.AbortController;var as=(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 fy=(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)},py=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Br=py?fy:window.requestIdleCallback;var tn,sn;const my=16;let ql=!1;try{ql=jr().browser===Xn.Safari&&parseInt((sn=(tn=navigator.userAgent.match(/Version\/(\d+)/))===null||tn===void 0?void 0:tn[1])!==null&&sn!==void 0?sn:"",10)<=my}catch(s){console.error(s)}let vy=class{constructor(e){this.bufferFull$=new O,this.error$=new O,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)}append(e,t){return J(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(i=>{const r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return J(this,void 0,void 0,function*(){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()})})}abort(e){return J(this,void 0,void 0,function*(){return new Promise(t=>{let i;ql&&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 Mr=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};let Ht=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}},Wl=class extends Ht{},gy=class 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}}},Sy=class extends Ht{parseChildrenBoxes(){return fs(this.content)}},by=class extends Ht{constructor(e){super(e),this.data=this.content}},Zs=class extends Ht{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}},yy=class extends Zs{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})}}},Ty=class extends Ht{parseChildrenBoxes(){return fs(this.content)}},Ey=class extends Ht{parseChildrenBoxes(){return fs(this.content)}};var Pi;(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"})(Pi||(Pi={}));let $y=class extends Zs{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=Pi.MONOSCOPIC;break;case 1:this.stereoMode=Pi.TOP_BOTTOM;break;case 2:this.stereoMode=Pi.LEFT_RIGHT;break;case 3:this.stereoMode=Pi.STEREO_CUSTOM;break;case 4:this.stereoMode=Pi.RIGHT_LEFT;break}this.cursor+=1}},Ay=class extends Zs{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}},wy=class extends Zs{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}},ky=class extends Ht{parseChildrenBoxes(){return fs(this.content)}},_y=class extends Zs{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()}},Py=class extends Ht{parseChildrenBoxes(){return fs(this.content)}},Dy=class extends Ht{parseChildrenBoxes(){return fs(this.content)}};const Iy={ftyp:gy,moov:Sy,mdat:by,sidx:yy,trak:Ty,mdia:ky,tkhd:_y,minf:Py,sv3d:Ey,st3d:$y,prhd:Ay,proj:Dy,equi:wy,unknown:Wl};let Ry=class{createBox(e,t){const i=Iy[e];return i?new i(t):new Wl(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return aa.createBox(i,new DataView(e.buffer,e.byteOffset))}};const aa=new Ry;function Is(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:aa.createBox(e,new DataView(s.buffer,i-7))}i++}return null}function Ly(s,e){const t=[];let i=0;for(;i<s.byteLength;){const r=Is(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 fs(s){const e=[];let t=0;for(;t<s.byteLength;){const i=aa.createFromView(new DataView(s.buffer,s.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const xy=new TextDecoder("ascii"),Cy=s=>xy.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",Oy=s=>{const e=aa.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:ue.NONE,time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},By=s=>{const e=Ly(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},My=s=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Or.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(Is(s,"sv3d")){e.is3dVideo=!0;const i=Is(s,"st3d");i&&(e.stereoMode=i.stereoMode);const r=Is(s,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const a=Is(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},Ny={validateData:Cy,parseInit:My,getIndexRange:()=>{},parseSegments:Oy,parseFeedableSegmentChunk:By};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 Kd={[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}},Ql=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 Kd,a=r?Kd[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=Nr(u),c=d*Math.pow(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)*Math.pow(2,16)+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*Math.pow(2,32)+s.getUint32(1);case 6:return s.getUint16(0)*Math.pow(2,32)+s.getUint32(2);case 7:{const t=s.getUint8(0)*Math.pow(2,48)+s.getUint16(1)*Math.pow(2,32)+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ct=(s,e)=>{switch(e){case F.SignedInteger:return s.getInt8(0);case F.UnsignedInteger:return Nr(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)}},ns=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=Ql(i);if(!e(r))return;r.type===F.Master&&ns(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},Fy=s=>{if(s.getUint32(0)!==w.EBML)return!1;let e,t,i;const r=Ql(s);return ns(r.value,({tag:a,type:n,value:o})=>(a===w.EBMLReadVersion?e=Ct(o,n):a===w.DocType?t=Ct(o,n):a===w.DocTypeReadVersion&&(i=Ct(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Kl=[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],Uy=[w.Timestamp,w.SilentTracks,w.SilentTrackNumber,w.Position,w.PrevSize,w.SimpleBlock,w.BlockGroup,w.EncryptedBlock],Vy=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,d,l=!1;const c=0;return ns(s,({tag:h,type:f,value:p,valueSize:S})=>{if(h===w.SeekID){const b=Ct(p,f);d=Nr(b)}else h!==w.SeekPosition&&(d=void 0);return h===w.Segment?(e=p.byteOffset,t=p.byteOffset+S):h===w.Info?a=!0:h===w.SeekHead?n=!0:h===w.TimestampScale?i=Ct(p,f):h===w.Duration?r=Ct(p,f):h===w.SeekPosition&&d===w.Cues?u=Ct(p,f):h===w.Tracks?ns(p,({tag:b,type:g,value:y})=>b===w.ProjectionType?(l=Ct(y,g)===1,!1):!0):a&&n&&Kl.includes(h)&&(o=!0),!o}),D(e,"Failed to parse webm Segment start"),D(t,"Failed to parse webm Segment end"),D(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:Or.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Hy=s=>{if(W(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Gy=(s,e)=>{let t=!1,i=!1;const r=o=>I(o.time)&&I(o.position),a=[];let n;return ns(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=Ct(d,u));break;case w.CueTrackPositions:break;case w.CueClusterPosition:n&&(n.position=Ct(d,u));break;default:t&&Kl.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:ue.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}}})},jy=s=>{let e=0,t=!1;try{ns(s,i=>i.tag===w.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Uy.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},Yy={validateData:Fy,parseInit:Vy,getIndexRange:Hy,parseSegments:Gy,parseFeedableSegmentChunk:jy},Jl=1e4,zy=3e4,qy=5e3,Wy=Jl,Qy=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a})=>{var n;const o=(n=a?hs(a):void 0)!==null&&n!==void 0?n:ci({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r}},Ky=({id:s,bitrate:e})=>({id:s,bitrate:e}),Jy=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=Oe(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:Oe(s,-1)},Xy=({id:s,lang:e,url:t,isAuto:i})=>({id:s,url:t,isAuto:i,type:"internal",language:e}),vr=s=>{const e=[];let t=0,i=s.length-1;for(;t<Jl&&i>=0;)e.unshift(s[i]),t+=s[i].time.to-s[i].time.from,i--;return e};let Jd=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 O,this.gaps=[],this.isSeekingLive=!1,this.subscription=new ce,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new St,this.destroyAbortController=new St,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.startWith=fe(this.destroyAbortController.signal,function(l){return pe(this,arguments,function*(){const c=this.representations.get(l);D(c,`Cannot find representation ${l}`),this.playingRepresentationId=l,this.downloadingRepresentationId=l,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${c.mime}; codecs="${c.codecs}"`),this.sourceBufferTaskQueue=new vy(this.sourceBuffer),this.subscription.add(V(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(V(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,Mr(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 yield _(this.loadInit(c,"high",!0));const h=this.initData.get(c.id),f=this.segments.get(c.id),p=this.parsedInitData.get(c.id);if(D(h,"No init buffer for starting representation"),D(f,"No segments for starting representation"),!(h instanceof ArrayBuffer))return yield _(void 0);this.searchGaps(f,c),yield yield _(this.sourceBufferTaskQueue.append(h,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(p)})}.bind(this)),this.switchTo=fe(this.destroyAbortController.signal,function(l){return pe(this,arguments,function*(){if(l===this.downloadingRepresentationId||l===this.switchingToRepresentationId)return yield _(void 0);this.switchingToRepresentationId=l;const c=this.representations.get(l);D(c,`No such representation ${l}`);let h=this.segments.get(l),f=this.initData.get(l);if(W(f)||W(h)?yield yield _(this.loadInit(c,"high",!1)):f instanceof Promise&&(yield yield _(f)),h=this.segments.get(l),D(h,"No segments for starting representation"),f=this.initData.get(l),!f||!(f instanceof ArrayBuffer)||!this.sourceBuffer)return yield _(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=l,this.abort(),yield yield _(this.sourceBufferTaskQueue.append(f,this.downloadAbortController.signal));const p=this.getCurrentPosition();I(p)&&(this.searchGaps(h,c),this.maintain(p))})}.bind(this)),this.seekLive=fe(this.destroyAbortController.signal,function(l){return pe(this,arguments,function*(){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!l)return yield _(void 0);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 yield _(void 0);const v=vr(y.segmentReference.segments);this.segments.set(y.id,v)}const c=this.switchingToRepresentationId?this.switchingToRepresentationId:this.downloadingRepresentationId,h=this.representations.get(c);D(h);const f=vr(h.segmentReference.segments),p=this.initData.get(h.id);if(D(p,"No init buffer for starting representation"),D(f,"No segments for starting representation"),!(p instanceof ArrayBuffer))return yield _(void 0);const S=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),S&&(yield yield _(this.sourceBufferTaskQueue.remove(S.from*1e3,S.to*1e3,this.destroyAbortController.signal))),this.searchGaps(f,h),yield yield _(this.sourceBufferTaskQueue.append(p,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 rs.MP4:this.containerParser=Ny;break;case rs.WEBM:this.containerParser=Yy;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 St,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(W(e)||W(this.downloadingRepresentationId)||W(this.playingRepresentationId)||W(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(D(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=tt(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)&&Mr(this.sourceBuffer.buffered)>=this.bufferLimit){const d=tt(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=Oe(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===ue.FED&&!o.length&&tt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const u=Oe(i,-1);u&&u.status===ue.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;I(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=>Object.assign(Object.assign({},c),{status:ue.NONE,size:void 0})),u=(i=this.segments.get(n.id))!==null&&i!==void 0?i:[],d=(a=(r=Oe(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=vr(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}},p)=>{const S=h<=i&&f>=i,b=h>i||S||p===0&&i===0,g=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&h<=i+g||f<=i+g;return(c===ue.NONE||c===ue.PARTIALLY_EJECTED&&b&&y&&this.sourceBuffer&&!as(this.sourceBuffer.buffered,i))&&b&&y});if(r===-1)return[];if(t!==vt.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===ue.NONE||h.status===ue.PARTIALLY_EJECTED)u.push(h);else break}return u}loadSegments(e,t,i="auto"){return J(this,void 0,void 0,function*(){if(!e.length)return;let r,a,n=e;const{type:o}=t.segmentReference;switch(o){case vt.BYTE_RANGE:{r=t.segmentReference.url,a={from:Oe(e,0).byte.from,to:Oe(e,-1).byte.to};break}case vt.TEMPLATE:{const d=Oe(e,0);r=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:z(o)}for(const d of n)d.status=ue.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:u}=this.downloadAbortController;if(this.failedDownloads&&(yield fe(u,function(){return pe(this,arguments,function*(){const d=Ls(this.failedDownloads,this.tuning.downloadBackoff);yield 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&&I(r)&&(i=tt((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=ue.FED,"size"in c.segment&&(c.segment.size=c.fedBytes);for(const f of this.representations.values())if(f.id!==t)for(const p of(h=this.segments.get(f.id))!==null&&h!==void 0?h:[])p.status===ue.FED&&p.time.from===c.segment.time.from&&p.time.to===c.segment.time.to&&(p.status=ue.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===vt.BYTE_RANGE,p=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===ue.DOWNLOADING&&y&&v){h.status=ue.DOWNLOADED,this.activeSegments.delete(c);const E=new DataView(e.buffer,e.byteOffset+b,p);this.sourceBufferTaskQueue.append(E,a).then($=>$&&!a.aborted?o(c):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&y&&(c.loadedBytes=Math.min(p,r-b),c.loadedBytes>c.feedingBytes)){const E=new DataView(e.buffer,e.byteOffset+b+c.feedingBytes,c.loadedBytes-c.feedingBytes),$=c.loadedBytes===p?E:this.containerParser.parseFeedableSegmentChunk(E);$!=null&&$.byteLength&&(h.status=ue.PARTIALLY_FED,c.feedingBytes+=$.byteLength,this.sourceBufferTaskQueue.append($,a).then(x=>{if(a.aborted)n();else if(x)c.fedBytes+=$.byteLength,c.fedBytes===p&&o(c);else{if(c.feedingBytes<p)return;n()}}))}}}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===ue.PARTIALLY_FED||e.status===ue.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=ue.NONE),e.status=ue.PARTIALLY_EJECTED):e.status=ue.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=Br(()=>Ks(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return J(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?fe(this.destroyAbortController.signal,function(){return pe(this,arguments,function*(){const o=Ls(this.failedDownloads,this.tuning.downloadBackoff);yield yield _(new Promise(u=>setTimeout(u,o)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(o=>J(this,void 0,void 0,function*(){if(!o)return;const{init:u,dataView:d,segments:l}=o,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c),this.segments.set(e.id,this.isLive?vr(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})}pruneBuffer(e,t,i=!1){return J(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||W(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===ue.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===ue.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===ue.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===ue.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=Br(()=>{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(W(this.sourceBuffer)||W(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!==ue.FED&&a!==ue.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=ue.PARTIALLY_EJECTED:r.status=ue.NONE)}}};var Zi;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(Zi||(Zi={}));let Zy=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 St,this.subscription=new ce,this.fetchManifest=fe(this.abortAllController.signal,function(r){return pe(this,arguments,function*(){let a=r;this.requestQuic&&(a=li(a));const n=yield yield _(Ci(a,{signal:this.abortAllController.signal}).catch(ks));return n?(this.onHeadersReceived(n.headers),yield _(n.text())):yield _(null)})}.bind(this)),this.fetch=fe(this.abortAllController.signal,function(r,{rangeMethod:a=this.compatibilityMode?Zi.HEADER:Zi.PARAM,range:n,onProgress:o,priority:u="auto",signal:d,measureThroughput:l=!0}={}){var c,h,f,p;return pe(this,arguments,function*(){let S=r;const b=new Headers;if(n)switch(a){case Zi.HEADER:{b.append("Range",`bytes=${n.from}-${n.to}`);break}case Zi.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=li(S));let g=this.abortAllController.signal,y;if(d){const Y=new St;if(y=G(V(this.abortAllController.signal,"abort"),V(d,"abort")).subscribe(()=>{try{Y.abort()}catch(se){ks(se)}}),this.abortAllController.signal.aborted||d.aborted)try{Y.abort()}catch(se){ks(se)}g=Y.signal}const v=he(),E=yield yield _(Ci(S,{priority:u,headers:b,signal:g}).catch(ks)),$=he();if((c=this.throughputEstimator)===null||c===void 0||c.addRawRtt($-v),!E)return y==null||y.unsubscribe(),yield _(null);if(!E.ok||!E.body)return y==null||y.unsubscribe(),yield _(Promise.reject(new Error(`Fetch error ${E.status}: ${E.statusText}`)));this.onHeadersReceived(E.headers);const x=parseInt((h=E.headers.get("Content-Length"))!==null&&h!==void 0?h:"",10)||n&&n.to-n.from+1||NaN;if(!x){const Y=yield yield _(E.arrayBuffer());return(f=this.throughputEstimator)===null||f===void 0||f.addRawSpeed(Y.byteLength,he()-$),o==null||o(new DataView(Y),Y.byteLength),y==null||y.unsubscribe(),yield _(Y)}if(!o&&!l)return y==null||y.unsubscribe(),yield _(E.arrayBuffer());const[j,K]=E.body.tee(),H=j.getReader();l&&((p=this.throughputEstimator)===null||p===void 0||p.trackStream(K));let q=0;const Q=new ArrayBuffer(x),B=new Uint8Array(Q),M=new DataView(Q);let X=!1;const N=Y=>{y==null||y.unsubscribe(),X=!0,ks(Y)},C=fe(g,function({done:Y,value:se}){return pe(this,arguments,function*(){if(q===0&&this.lastRequestFirstBytes$.next(he()-v),g.aborted)return y==null||y.unsubscribe(),yield _(void 0);!Y&&se&&(B.set(se,q),q+=se.byteLength,o==null||o(M,q),yield yield _(H==null?void 0:H.read().then(C,N)))})}.bind(this));return yield yield _(H==null?void 0:H.read().then(C,N)),y==null||y.unsubscribe(),yield _(X?null:Q)})}.bind(this)),this.fetchByteRangeRepresentation=fe(this.abortAllController.signal,function(r,a,n){var o;return pe(this,arguments,function*(){if(r.type!==vt.BYTE_RANGE)return yield _(null);const{from:u,to:d}=r.initRange;let l=u,c=d,h=!1,f,p;r.indexRange&&(f=r.indexRange.from,p=r.indexRange.to,h=d+1===f,h&&(l=Math.min(f,u),c=Math.max(p,d))),l=Math.min(l,0);const S=yield yield _(this.fetch(r.url,{range:{from:l,to:c},priority:n,measureThroughput:!1}));if(!S)return yield _(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 yield _(this.fetch(r.url,{range:y,priority:n,measureThroughput:!1}));if(!$)return yield _(null);v=new DataView($)}const E=a.parseSegments(v,g,y);return yield _({init:g,dataView:new DataView(S),segments:E})})}.bind(this)),this.fetchTemplateRepresentation=fe(this.abortAllController.signal,function(r,a){return pe(this,arguments,function*(){if(r.type!==vt.TEMPLATE)return yield _(null);const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield yield _(this.fetch(n,{priority:a,measureThroughput:!1}));if(!o)return yield _(null);const u=r.segments.map(d=>Object.assign(Object.assign({},d),{status:ue.NONE,size:void 0}));return yield _({init:null,segments:u,dataView:new DataView(o)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=wo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){var r,a;return J(this,void 0,void 0,function*(){const{type:n}=e;switch(n){case vt.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case vt.TEMPLATE:return(a=yield this.fetchTemplateRepresentation(e,i))!==null&&a!==void 0?a:null;default:z(n)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}};const ks=s=>{if(!(s instanceof DOMException)||!(s.name==="AbortError"||s.code===20))throw s};var e0=ei,t0=Hs,i0=Ke,s0=i0("match"),r0=function(s){var e;return e0(s)&&((e=s[s0])!==void 0?!!e:t0(s)=="RegExp")},a0=qs,n0=String,o0=function(s){if(a0(s)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return n0(s)},d0=ti,u0=function(){var s=d0(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},l0=ct,c0=Mt,h0=Wr,f0=u0,Xd=RegExp.prototype,p0=function(s){var e=s.flags;return e===void 0&&!("flags"in Xd)&&!c0(s,"flags")&&h0(Xd,s)?l0(f0,s):e},ko=yt,m0=Xr,v0=Math.floor,rn=ko("".charAt),g0=ko("".replace),an=ko("".slice),S0=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,b0=/\$([$&'`]|\d{1,2})/g,y0=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=b0;return r!==void 0&&(r=m0(r),u=S0),g0(a,u,function(d,l){var c;switch(rn(l,0)){case"$":return"$";case"&":return s;case"`":return an(e,0,t);case"'":return an(e,n);case"<":c=r[an(l,1,-1)];break;default:var h=+l;if(h===0)return d;if(h>o){var f=v0(h/10);return f===0?d:f<=o?i[f-1]===void 0?rn(l,1):i[f-1]+rn(l,1):d}c=i[h-1]}return c===void 0?"":c})},T0=_t,E0=ct,_o=yt,Zd=Zn,$0=Re,A0=Gs,w0=r0,zi=o0,k0=Jr,_0=p0,P0=y0,D0=Ke,I0=D0("replace"),R0=TypeError,Xl=_o("".indexOf),L0=_o("".replace),eu=_o("".slice),x0=Math.max,tu=function(s,e,t){return t>s.length?-1:e===""?t:Xl(s,e,t)};T0({target:"String",proto:!0},{replaceAll:function(e,t){var i=Zd(this),r,a,n,o,u,d,l,c,h,f=0,p=0,S="";if(!A0(e)){if(r=w0(e),r&&(a=zi(Zd(_0(e))),!~Xl(a,"g")))throw R0("`.replaceAll` does not allow non-global regexes");if(n=k0(e,I0),n)return E0(n,e,i,t);if(r)return L0(zi(i),e,t)}for(o=zi(i),u=zi(e),d=$0(t),d||(t=zi(t)),l=u.length,c=x0(1,l),f=tu(o,u,0);f!==-1;)h=d?zi(t(u,f,o)):P0(u,o,f,[],void 0,t),S+=eu(o,p,f)+h,p=f+l,f=tu(o,u,f+c);return p<o.length&&(S+=eu(o,p)),S}});var C0=Eo,O0=C0("String","replaceAll"),B0=O0,M0=B0,N0=M0,F0=N0,Fr=zr(F0);const iu=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},nn=(s,e)=>{let t=s;t=Fr(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=Fr(t,n,(o,u)=>W(a)?o:W(u)?a:a.padStart(parseInt(u,10),"0"))}return t},U0=(s,e)=>{var t,i,r,a,n,o,u,d,l,c,h,f,p,S,b,g,y,v,E,$,x,j,K,H,q,Q,B,M,X,N,C,Y,se,ve,Ee,Le,Je,ht,re;const Xe=new DOMParser().parseFromString(s,"application/xml"),xe={video:[],audio:[],text:[]},Pe=Xe.children[0],Gt=Pe.getElementsByTagName("Period")[0],jt=Gt.children,ai=Pe.getAttribute("type")==="dynamic",Yt=Pe.getAttribute("availabilityStartTime"),Fi=Yt?new Date(Yt).getTime():void 0;let Ge;const ps=Pe.getAttribute("mediaPresentationDuration"),ms=Gt.getAttribute("duration"),mi=Pe.getElementsByTagName("vk:Attrs")[0],vs=mi==null?void 0:mi.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(ps)Ge=iu(ps);else if(ms){const $e=iu(ms);I($e)&&(Ge=$e)}else vs&&(Ge=parseInt(vs,10));let oa=0;const vi=(i=(t=Pe.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],da=vi.includes(Cr.WEBM_AS_IN_FFMPEG)||vi.includes(Cr.WEBM_AS_IN_SPEC)?rs.WEBM:rs.MP4;for(const $e of jt){const zt=$e.getAttribute("mimeType"),ua=$e.getAttribute("codecs"),gs=(r=$e.getAttribute("contentType"))!==null&&r!==void 0?r:zt==null?void 0:zt.split("/")[0],la=(n=(a=$e.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],Ss=$e.querySelectorAll("Representation"),ca=$e.querySelector("SegmentTemplate");if(gs===Fe.TEXT){for(const Z of Ss){const Ce=Z.getAttribute("id")||"",qt=$e.getAttribute("lang"),it=(d=(u=(o=Z.querySelector("BaseURL"))===null||o===void 0?void 0:o.textContent)===null||u===void 0?void 0:u.trim())!==null&&d!==void 0?d:"",gi=new URL(it,e).toString(),Si=Ce.includes("_auto");xe[Fe.TEXT].push({id:Ce,lang:qt,isAuto:Si,kind:Fe.TEXT,url:gi})}continue}for(const Z of Ss){const Ce=(l=Z.getAttribute("mimeType"))!==null&&l!==void 0?l:zt,qt=(h=(c=Z.getAttribute("codecs"))!==null&&c!==void 0?c:ua)!==null&&h!==void 0?h:"",it=(p=(f=Z.getAttribute("contentType"))!==null&&f!==void 0?f:Ce==null?void 0:Ce.split("/")[0])!==null&&p!==void 0?p:gs,gi=(b=(S=$e.getAttribute("profiles"))===null||S===void 0?void 0:S.split(","))!==null&&b!==void 0?b:[],Si=parseInt((g=Z.getAttribute("width"))!==null&&g!==void 0?g:"",10),bs=parseInt((y=Z.getAttribute("height"))!==null&&y!==void 0?y:"",10),ys=parseInt((v=Z.getAttribute("bandwidth"))!==null&&v!==void 0?v:"",10)/1e3,Ts=(E=Z.getAttribute("frameRate"))!==null&&E!==void 0?E:"",ha=($=Z.getAttribute("quality"))!==null&&$!==void 0?$:void 0,fa=Ts?sa(Ts):void 0,pa=(x=Z.getAttribute("id"))!==null&&x!==void 0?x:(oa++).toString(10),ma=it==="video"?`${bs}p`:it==="audio"?`${ys}Kbps`:qt,va=`${pa}@${ma}`,ga=(H=(K=(j=Z.querySelector("BaseURL"))===null||j===void 0?void 0:j.textContent)===null||K===void 0?void 0:K.trim())!==null&&H!==void 0?H:"",Es=new URL(ga,e).toString(),Sa=[...vi,...la,...gi];let bi;const ba=Z.querySelector("SegmentBase"),je=(q=Z.querySelector("SegmentTemplate"))!==null&&q!==void 0?q:ca;if(ba){const st=(B=(Q=Z.querySelector("SegmentBase Initialization"))===null||Q===void 0?void 0:Q.getAttribute("range"))!==null&&B!==void 0?B:"",[rt,Ti]=st.split("-").map(at=>parseInt(at,10)),Ze={from:rt,to:Ti},Et=(M=Z.querySelector("SegmentBase"))===null||M===void 0?void 0:M.getAttribute("indexRange"),[Ei,Wt]=Et?Et.split("-").map(at=>parseInt(at,10)):[],$t=Et?{from:Ei,to:Wt}:void 0;bi={type:vt.BYTE_RANGE,url:Es,initRange:Ze,indexRange:$t}}else if(je){const st={representationId:(X=Z.getAttribute("id"))!==null&&X!==void 0?X:void 0,bandwidth:(N=Z.getAttribute("bandwidth"))!==null&&N!==void 0?N:void 0},rt=parseInt((C=je.getAttribute("timescale"))!==null&&C!==void 0?C:"",10),Ti=(Y=je.getAttribute("initialization"))!==null&&Y!==void 0?Y:"",Ze=je.getAttribute("media"),Et=(ve=parseInt((se=je.getAttribute("startNumber"))!==null&&se!==void 0?se:"",10))!==null&&ve!==void 0?ve:1,Ei=nn(Ti,st);if(!Ze)throw new ReferenceError("No media attribute in SegmentTemplate");const Wt=(Ee=je.querySelectorAll("SegmentTimeline S"))!==null&&Ee!==void 0?Ee:[],$t=[];let at=0;if(Wt.length){let $i=Et,nt=0;for(const Ai of Wt){const ot=parseInt((Le=Ai.getAttribute("d"))!==null&&Le!==void 0?Le:"",10),De=parseInt((Je=Ai.getAttribute("r"))!==null&&Je!==void 0?Je:"",10)||0,At=parseInt((ht=Ai.getAttribute("t"))!==null&&ht!==void 0?ht:"",10);nt=Number.isFinite(At)?At:nt;const et=ot/rt*1e3,Dt=nt/rt*1e3;for(let Qt=0;Qt<De+1;Qt++){const $s=nn(Ze,Object.assign(Object.assign({},st),{segmentNumber:$i.toString(10),segmentTime:(nt+Qt*ot).toString(10)})),Ui=(Dt||0)+Qt*et,Vi=Ui+et;$i++,$t.push({time:{from:Ui,to:Vi},url:$s})}nt+=(De+1)*ot,at+=(De+1)*et}}else if(I(Ge)){const nt=parseInt((re=je.getAttribute("duration"))!==null&&re!==void 0?re:"",10)/rt*1e3,Ai=Math.ceil(Ge/nt);let ot=0;for(let De=1;De<Ai;De++){const At=nn(Ze,Object.assign(Object.assign({},st),{segmentNumber:De.toString(10),segmentTime:ot.toString(10)}));$t.push({time:{from:ot,to:ot+nt},url:At}),ot+=nt}}bi={type:vt.TEMPLATE,baseUrl:Es,initUrl:Ei,totalSegmentsDurationMs:at,segments:$t}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!it||!Ce)continue;const yi={video:Fe.VIDEO,audio:Fe.AUDIO,text:Fe.TEXT}[it];yi&&xe[yi].push({id:va,kind:yi,segmentReference:bi,profiles:Sa,duration:Ge,bitrate:ys,mime:Ce,codecs:qt,width:Si,height:bs,fps:fa,quality:ha})}}return{dynamic:ai,liveAvailabilityStartTime:Fi,duration:Ge,container:da,representations:xe}},qn=1e3,su=["timeupdate","progress","play","seeked","stalled","waiting"];var pt;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(pt||(pt={}));let V0=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new ce,this.representationSubscription=new ce,this.state$=new me(pt.NONE),this.currentVideoRepresentation$=new T(void 0),this.currentVideoRepresentationInit$=new T(void 0),this.error$=new O,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 O,this.gapWatchdogStarted=!1,this.destroyController=new St,this.initManifest=fe(this.destroyController.signal,function(t,i,r){var a;return pe(this,arguments,function*(){this.element=t,this.manifestUrlString=qe(i,r,Te.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(pt.MANIFEST_READY),this.manifest=yield yield _(this.updateManifest()),!((a=this.manifest)===null||a===void 0)&&a.representations.video.length?this.state$.setState(pt.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:R.PARSER,message:"No playable video representations"})})}.bind(this)),this.updateManifest=fe(this.destroyController.signal,function(){var t;return pe(this,arguments,function*(){const i=yield 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 yield _(this.manifest);let r;try{r=U0(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 yield _(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===Fe.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)),yield _(Object.assign(Object.assign({},r),{representations:Li(Object.entries(r.representations).map(([n,o])=>[n,o.filter(a)]))}))})}.bind(this)),this.initRepresentations=fe(this.destroyController.signal,function(t,i){return pe(this,arguments,function*(){D(this.manifest),D(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(pt.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 Jd(Fe.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],I(i)&&(this.audioBufferManager=new Jd(Fe.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(Ri(qn).subscribe(o=>{var u;if(!((u=this.element)===null||u===void 0)&&u.paused){const d=Lr(this.manifestUrlString,Te.DASH_CMAF_OFFSET_P);this.manifestUrlString=qe(this.manifestUrlString,d+1e3,Te.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(G(...su.map(o=>V(this.element,o))).pipe(Sc(qn),P(o=>this.element?tt(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(p=>{var S,b;return(b=(S=p.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(u=>J(this,void 0,void 0,function*(){D(this.element);const d=this.element.playbackRate,l=Lr(this.manifestUrlString,Te.DASH_CMAF_OFFSET_P),c=zy*d,h=Wy*d,f=qy*d;o=u>o?u:o;const p=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=qe(this.manifestUrlString,v,Te.DASH_CMAF_OFFSET_P)}(p||b||S)&&(yield this.updateLive(),o=0)})))}const a=G(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(P(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=G(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(P(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.representationSubscription.add(G(this.forceEnded$,Be({allBuffersFull:a,someBufferEnded:n}).pipe(oe(({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(G(...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 yield _(new Promise(o=>{var u;return(u=this.source)===null||u===void 0?void 0:u.addEventListener("sourceopen",o)}))),I(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&I(i)?yield yield _(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)])):yield yield _(this.videoBufferManager.startWith(t)),this.state$.setState(pt.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=Ri(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 Zy({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}seekLive(e){var t,i,r,a;return J(this,void 0,void 0,function*(){D(this.element),this.manifestUrlString=qe(this.manifestUrlString,e,Te.DASH_CMAF_OFFSET_P),this.manifest=yield this.updateManifest(),yield(t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((i=this.manifest)===null||i===void 0?void 0:i.representations.video),yield(r=this.audioBufferManager)===null||r===void 0?void 0:r.seekLive((a=this.manifest)===null||a===void 0?void 0:a.representations.audio)})}initBuffer(){D(this.element),this.state$.setState(pt.RUNNING),this.subscription.add(G(...su.map(e=>V(this.element,e)),V(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:R.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(V(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(V(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&as(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}switchRepresentation(e,t){return J(this,void 0,void 0,function*(){const i={[Fe.VIDEO]:this.videoBufferManager,[Fe.AUDIO]:this.audioBufferManager,[Fe.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)})}seek(e,t){var i,r,a,n,o;D(this.element),D(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),as(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(pt.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}updateLive(){var e;return J(this,void 0,void 0,function*(){this.manifest=yield 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 H0{constructor(e,t){this.fov=e,this.orientation=t}}class G0{constructor(e,t){this.rotating=!1,this.fading=!1,this.lastTickTS=0,this.lastCameraTurnTS=0,this.fadeStartSpeed=null,this.fadeTime=0,this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/Math.pow(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,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=Object.assign({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}const t=e-this.lastTickTS,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*Math.pow(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*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 j0=`#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;}`,Y0=`#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 ec{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 G0(this.params.fov,this.params.orientation),this.cameraRotationManager=new j0(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(Y0,this.gl.VERTEX_SHADER),i=this.createShader(z0,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 tc=class{constructor(e){this.subscription=new ce,this.videoState=new me(Ae.STOPPED),this.elementSize$=new T(void 0),this.textTracksManager=new Pt,this.droppedFramesManager=new Xs,this.videoTracks$=new T([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Vl,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===ie.Requested&&(o==null?void 0:o.to)!==m.PAUSED&&a!==Ae.STOPPED&&n!==m.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===m.STOPPED){a!==Ae.STOPPED&&(this.videoState.startTransitionTo(Ae.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Ae.STOPPED),x(this.params.desiredState.playbackState,m.STOPPED,!0));return}switch(a){case Ae.STOPPED:this.videoState.startTransitionTo(Ae.READY),this.prepare();return;case Ae.READY:n===m.PAUSED?(this.videoState.setState(Ae.PAUSED),x(this.params.desiredState.playbackState,m.PAUSED)):n===m.PLAYING?(this.videoState.startTransitionTo(Ae.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===m.READY&&x(this.params.desiredState.playbackState,m.READY);return;case Ae.PLAYING:n===m.PAUSED?(this.videoState.startTransitionTo(Ae.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(o==null?void 0:o.to)===m.PLAYING&&x(this.params.desiredState.playbackState,m.PLAYING);return;case Ae.PAUSED:n===m.PLAYING?(this.videoState.startTransitionTo(Ae.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(o==null?void 0:o.to)===m.PAUSED&&x(this.params.desiredState.playbackState,m.PAUSED);return;default:return z(a)}}},this.init3DScene=t=>{var i,r,a;if(this.scene3D)return;this.scene3D=new ec(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=Ft(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(Qe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new H0({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=Vt(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:I.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo: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(P(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(oe(D),_e()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(fi(this.video,t.isLooped,r)),this.subscription.add(Nt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ii(this.video,t.playbackRate,i.playbackRateState$,r)),a(Us(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(Ae.PLAYING),x(t.playbackState,m.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(Ae.PAUSED),x(t.playbackState,m.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===Ae.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d===pt.MANIFEST_READY){const c=[];this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();R(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((v,y)=>y.bitrate-v.bitrate),p=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=Jy(v);y&&this.audioTracks.push({track:y,representation:v})}for(const v of p){const y=Ky(v);if(y){c.push({track:y,representation:v});const g=!this.params.tuning.isAudioDisabled&&Xy(f,p,v);g&&this.audioRepresentations.set(v.id,g)}}this.videoTracks$.next(c);for(const v of S){const y=Zy(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();R(b),this.player.initRepresentations(b.id,(l=this.audioRepresentations.get(b.id))===null||l===void 0?void 0:l.id)}else d===pt.REPRESENTATIOS_READY&&(this.videoState.setState(Ae.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:I.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(G(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,V(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!==pt.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(Fe.VIDEO,c.id).catch(n);const f=this.audioRepresentations.get(c.id);f&&this.player.switchRepresentation(Fe.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(ye(),P(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(P(({to:d})=>d===m.READY),ye());this.subscription.add(G(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===m.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(G(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===m.READY)));const u=G(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,We(["init"])).pipe(ct(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=tt(this.video.buffered,this.video.currentTime*1e3),f=u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=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=Ni(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:p,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(){si(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(Ae.PAUSED),x(this.params.desiredState.playbackState,m.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:I.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Ut(this.video)}},q0=class extends tc{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 Ue;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(Ue||(Ue={}));var xt;(function(s){s[s.ActiveLowLatency=0]="ActiveLowLatency",s[s.LiveWithTargetOffset=1]="LiveWithTargetOffset",s[s.LiveForwardBuffering=2]="LiveForwardBuffering",s[s.None=3]="None"})(xt||(xt={}));var Vr;(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"})(Vr||(Vr={}));var gt;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(gt||(gt={}));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 os;(function(s){s.MP4="mp4",s.WEBM="webm"})(os||(os={}));var Hr;(function(s){s[s.RECTANGULAR=0]="RECTANGULAR",s[s.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",s[s.CUBEMAP=2]="CUBEMAP",s[s.MESH=3]="MESH"})(Hr||(Hr={}));var we;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(we||(we={}));var un,ln;let ic=!1;try{ic=zr().browser===Zn.Safari&&parseInt((ln=(un=navigator.userAgent.match(/Version\/(\d+)/))===null||un===void 0?void 0:un[1])!==null&&ln!==void 0?ln:"",10)<16}catch(s){console.error(s)}class W0{constructor(e){this.bufferFull$=new O,this.error$=new O,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:I.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return ee(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(i=>{const r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return ee(this,void 0,void 0,function*(){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()})})}abort(e){return ee(this,void 0,void 0,function*(){return new Promise(t=>{let i;ic&&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:I.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:z(t)}}}class Tt{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 sc extends Tt{}class Q0 extends Tt{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 K0 extends Tt{parseChildrenBoxes(){return pi(this.content)}}class J0 extends Tt{parseChildrenBoxes(){return pi(this.content)}}class X0 extends Tt{constructor(e){super(e),this.data=this.content}}class ri extends Tt{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class Z0 extends ri{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 eT extends Tt{parseChildrenBoxes(){return pi(this.content)}}class tT extends Tt{parseChildrenBoxes(){return pi(this.content)}}var Di;(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"})(Di||(Di={}));class iT extends ri{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=Di.MONOSCOPIC;break;case 1:this.stereoMode=Di.TOP_BOTTOM;break;case 2:this.stereoMode=Di.LEFT_RIGHT;break;case 3:this.stereoMode=Di.STEREO_CUSTOM;break;case 4:this.stereoMode=Di.RIGHT_LEFT;break}this.cursor+=1}}class sT extends ri{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class rT extends ri{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class aT extends Tt{parseChildrenBoxes(){return pi(this.content)}}class nT extends ri{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 oT extends Tt{parseChildrenBoxes(){return pi(this.content)}}class dT extends Tt{parseChildrenBoxes(){return pi(this.content)}}class uT extends ri{constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class lT extends Tt{parseChildrenBoxes(){return pi(this.content)}}class cT extends ri{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 hT extends ri{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 fT extends ri{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 pT={ftyp:Q0,moov:K0,moof:J0,mdat:X0,sidx:Z0,trak:eT,mdia:aT,mfhd:uT,tkhd:nT,traf:lT,tfhd:cT,tfdt:hT,trun:fT,minf:oT,sv3d:tT,st3d:iT,prhd:sT,proj:dT,equi:rT,unknown:sc};class mT{createBox(e,t){const i=pT[e];return i?new i(t):new sc(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return da.createBox(i,new DataView(e.buffer,e.byteOffset))}}const da=new mT;function Is(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:da.createBox(e,new DataView(s.buffer,r-7))}r++}return null}function Qn(s,e){const t=[];let i=s.byteOffset;for(;i<s.buffer.byteLength;){const r=Is(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 pi(s){const e=[];let t=0;for(;t<s.byteLength;){const i=da.createFromView(new DataView(s.buffer,s.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const vT=new TextDecoder("ascii"),gT=s=>vT.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",ST=s=>{const e=da.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})},bT=s=>{const e=Qn(s,"mdat"),t=Qn(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)},yT=(s,e)=>{const t=Qn(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},TT=s=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Hr.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(Is(s,"sv3d")){e.is3dVideo=!0;const i=Is(s,"st3d");i&&(e.stereoMode=i.stereoMode);const r=Is(s,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const a=Is(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},ET={validateData:gT,parseInit:TT,getIndexRange:()=>{},parseSegments:ST,parseFeedableSegmentChunk:bT,getSegmentEndTime:yT};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 U;(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"})(U||(U={}));const nu={[k.EBML]:{type:U.Master},[k.EBMLVersion]:{type:U.UnsignedInteger},[k.EBMLReadVersion]:{type:U.UnsignedInteger},[k.EBMLMaxIDLength]:{type:U.UnsignedInteger},[k.EBMLMaxSizeLength]:{type:U.UnsignedInteger},[k.DocType]:{type:U.String},[k.DocTypeVersion]:{type:U.UnsignedInteger},[k.DocTypeReadVersion]:{type:U.UnsignedInteger},[k.Void]:{type:U.Binary},[k.Segment]:{type:U.Master},[k.SeekHead]:{type:U.Master},[k.Seek]:{type:U.Master},[k.SeekID]:{type:U.Binary},[k.SeekPosition]:{type:U.UnsignedInteger},[k.Info]:{type:U.Master},[k.TimestampScale]:{type:U.UnsignedInteger},[k.Duration]:{type:U.Float},[k.Tracks]:{type:U.Master},[k.TrackEntry]:{type:U.Master},[k.Video]:{type:U.Master},[k.Projection]:{type:U.Master},[k.ProjectionType]:{type:U.UnsignedInteger},[k.ProjectionPrivate]:{type:U.Master},[k.Chapters]:{type:U.Master},[k.Cluster]:{type:U.Master},[k.Timestamp]:{type:U.UnsignedInteger},[k.SilentTracks]:{type:U.Master},[k.SilentTrackNumber]:{type:U.UnsignedInteger},[k.Position]:{type:U.UnsignedInteger},[k.PrevSize]:{type:U.UnsignedInteger},[k.SimpleBlock]:{type:U.Binary},[k.BlockGroup]:{type:U.Master},[k.EncryptedBlock]:{type:U.Binary},[k.Attachments]:{type:U.Master},[k.Tags]:{type:U.Master},[k.Cues]:{type:U.Master},[k.CuePoint]:{type:U.Master},[k.CueTime]:{type:U.UnsignedInteger},[k.CueTrackPositions]:{type:U.Master},[k.CueTrack]:{type:U.UnsignedInteger},[k.CueClusterPosition]:{type:U.UnsignedInteger},[k.CueRelativePosition]:{type:U.UnsignedInteger},[k.CueDuration]:{type:U.UnsignedInteger},[k.CueBlockNumber]:{type:U.UnsignedInteger},[k.CueCodecState]:{type:U.UnsignedInteger},[k.CueReference]:{type:U.Master},[k.CueRefTime]:{type:U.UnsignedInteger}},rc=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=Gr(s,t),r=i in nu,a=r?nu[i].type:U.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=Gr(u),c=d*Math.pow(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}},Gr=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*Math.pow(2,16)+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*Math.pow(2,32)+s.getUint32(1);case 6:return s.getUint16(0)*Math.pow(2,32)+s.getUint32(2);case 7:{const t=s.getUint8(0)*Math.pow(2,48)+s.getUint16(1)*Math.pow(2,32)+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ot=(s,e)=>{switch(e){case U.SignedInteger:return s.getInt8(0);case U.UnsignedInteger:return Gr(s);case U.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case U.String:return new TextDecoder("ascii").decode(s);case U.UTF8:return new TextDecoder("utf-8").decode(s);case U.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case U.Master:return s;case U.Binary:return s;default:z(e)}},ds=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=rc(i);if(!e(r))return;r.type===U.Master&&ds(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},$T=s=>{if(s.getUint32(0)!==k.EBML)return!1;let e,t,i;const r=rc(s);return ds(r.value,({tag:a,type:n,value:o})=>(a===k.EBMLReadVersion?e=Ot(o,n):a===k.DocType?t=Ot(o,n):a===k.DocTypeReadVersion&&(i=Ot(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},ac=[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],AT=[k.Timestamp,k.SilentTracks,k.SilentTrackNumber,k.Position,k.PrevSize,k.SimpleBlock,k.BlockGroup,k.EncryptedBlock],wT=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,d,l=!1;const c=0;return ds(s,({tag:h,type:f,value:p,valueSize:S})=>{if(h===k.SeekID){const b=Ot(p,f);d=Gr(b)}else h!==k.SeekPosition&&(d=void 0);return h===k.Segment?(e=p.byteOffset,t=p.byteOffset+S):h===k.Info?a=!0:h===k.SeekHead?n=!0:h===k.TimestampScale?i=Ot(p,f):h===k.Duration?r=Ot(p,f):h===k.SeekPosition&&d===k.Cues?u=Ot(p,f):h===k.Tracks?ds(p,({tag:b,type:v,value:y})=>b===k.ProjectionType?(l=Ot(y,v)===1,!1):!0):a&&n&&ac.includes(h)&&(o=!0),!o}),R(e,"Failed to parse webm Segment start"),R(t,"Failed to parse webm Segment end"),R(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:Hr.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},kT=s=>{if(W(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},_T=(s,e)=>{let t=!1,i=!1;const r=o=>D(o.time)&&D(o.position),a=[];let n;return ds(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=Ot(d,u));break;case k.CueTrackPositions:break;case k.CueClusterPosition:n&&(n.position=Ot(d,u));break;default:t&&ac.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}}})},PT=s=>{let e=0,t=!1;try{ds(s,i=>i.tag===k.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):AT.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},DT={validateData:$T,parseInit:wT,getIndexRange:kT,parseSegments:_T,parseFeedableSegmentChunk:PT},ou=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},Qi=(s,e)=>{let t=s;t=Ur(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=Ur(t,n,(o,u)=>W(a)?o:W(u)?a:a.padStart(parseInt(u,10),"0"))}return t},RT=(s,e)=>{var t,i,r,a,n,o,u,d,l,c,h,f,p,S,b,v,y,g,E,$,L,j,K,H,q,Q,B,M,J,N,C,Y,se,ve,Ee,xe,Je,ft,re;const Xe=new DOMParser().parseFromString(s,"application/xml"),Le={video:[],audio:[],text:[]},Pe=Xe.children[0],Gt=Pe.getElementsByTagName("Period")[0],jt=Gt.children,ai=Pe.getAttribute("type")==="dynamic",Yt=Pe.getAttribute("availabilityStartTime"),Fi=Yt?new Date(Yt).getTime():void 0;let Ge;const ps=Pe.getAttribute("mediaPresentationDuration"),ms=Gt.getAttribute("duration"),mi=Pe.getElementsByTagName("vk:Attrs")[0],vs=mi==null?void 0:mi.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(ps)Ge=ou(ps);else if(ms){const $e=ou(ms);D($e)&&(Ge=$e)}else vs&&(Ge=parseInt(vs,10));let ua=0;const vi=(i=(t=Pe.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],la=vi.includes(Vr.WEBM_AS_IN_FFMPEG)||vi.includes(Vr.WEBM_AS_IN_SPEC)?os.WEBM:os.MP4;for(const $e of jt){const zt=$e.getAttribute("mimeType"),ca=$e.getAttribute("codecs"),gs=(r=$e.getAttribute("contentType"))!==null&&r!==void 0?r:zt==null?void 0:zt.split("/")[0],ha=(n=(a=$e.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],Ss=$e.querySelectorAll("Representation"),fa=$e.querySelector("SegmentTemplate");if(gs===Ue.TEXT){for(const X of Ss){const Ce=X.getAttribute("id")||"",qt=$e.getAttribute("lang"),it=(d=(u=(o=X.querySelector("BaseURL"))===null||o===void 0?void 0:o.textContent)===null||u===void 0?void 0:u.trim())!==null&&d!==void 0?d:"",gi=new URL(it,e).toString(),Si=Ce.includes("_auto");Le[Ue.TEXT].push({id:Ce,lang:qt,isAuto:Si,kind:Ue.TEXT,url:gi})}continue}for(const X of Ss){const Ce=(l=X.getAttribute("mimeType"))!==null&&l!==void 0?l:zt,qt=(h=(c=X.getAttribute("codecs"))!==null&&c!==void 0?c:ca)!==null&&h!==void 0?h:"",it=(p=(f=X.getAttribute("contentType"))!==null&&f!==void 0?f:Ce==null?void 0:Ce.split("/")[0])!==null&&p!==void 0?p:gs,gi=(b=(S=$e.getAttribute("profiles"))===null||S===void 0?void 0:S.split(","))!==null&&b!==void 0?b:[],Si=parseInt((v=X.getAttribute("width"))!==null&&v!==void 0?v:"",10),bs=parseInt((y=X.getAttribute("height"))!==null&&y!==void 0?y:"",10),ys=parseInt((g=X.getAttribute("bandwidth"))!==null&&g!==void 0?g:"",10)/1e3,Ts=(E=X.getAttribute("frameRate"))!==null&&E!==void 0?E:"",pa=($=X.getAttribute("quality"))!==null&&$!==void 0?$:void 0,ma=Ts?aa(Ts):void 0,va=(L=X.getAttribute("id"))!==null&&L!==void 0?L:(ua++).toString(10),ga=it==="video"?`${bs}p`:it==="audio"?`${ys}Kbps`:qt,Sa=`${va}@${ga}`,ba=(H=(K=(j=X.querySelector("BaseURL"))===null||j===void 0?void 0:j.textContent)===null||K===void 0?void 0:K.trim())!==null&&H!==void 0?H:"",Es=new URL(ba,e).toString(),ya=[...vi,...ha,...gi];let bi;const Ta=X.querySelector("SegmentBase"),je=(q=X.querySelector("SegmentTemplate"))!==null&&q!==void 0?q:fa;if(Ta){const st=(B=(Q=X.querySelector("SegmentBase Initialization"))===null||Q===void 0?void 0:Q.getAttribute("range"))!==null&&B!==void 0?B:"",[rt,Ti]=st.split("-").map(at=>parseInt(at,10)),Ze={from:rt,to:Ti},Et=(M=X.querySelector("SegmentBase"))===null||M===void 0?void 0:M.getAttribute("indexRange"),[Ei,Wt]=Et?Et.split("-").map(at=>parseInt(at,10)):[],$t=Et?{from:Ei,to:Wt}:void 0;bi={type:gt.BYTE_RANGE,url:Es,initRange:Ze,indexRange:$t}}else if(je){const st={representationId:(J=X.getAttribute("id"))!==null&&J!==void 0?J:void 0,bandwidth:(N=X.getAttribute("bandwidth"))!==null&&N!==void 0?N:void 0},rt=parseInt((C=je.getAttribute("timescale"))!==null&&C!==void 0?C:"",10),Ti=(Y=je.getAttribute("initialization"))!==null&&Y!==void 0?Y:"",Ze=je.getAttribute("media"),Et=(ve=parseInt((se=je.getAttribute("startNumber"))!==null&&se!==void 0?se:"",10))!==null&&ve!==void 0?ve:1,Ei=Qi(Ti,st);if(!Ze)throw new ReferenceError("No media attribute in SegmentTemplate");const Wt=(Ee=je.querySelectorAll("SegmentTimeline S"))!==null&&Ee!==void 0?Ee:[],$t=[];let at=0,$i="",nt=0;if(Wt.length){let ot=Et,De=0;for(const At of Wt){const et=parseInt((xe=At.getAttribute("d"))!==null&&xe!==void 0?xe:"",10),Dt=parseInt((Je=At.getAttribute("r"))!==null&&Je!==void 0?Je:"",10)||0,Qt=parseInt((ft=At.getAttribute("t"))!==null&&ft!==void 0?ft:"",10);De=Number.isFinite(Qt)?Qt:De;const $s=et/rt*1e3,Ui=De/rt*1e3;for(let Vi=0;Vi<Dt+1;Vi++){const hc=Qi(Ze,Object.assign(Object.assign({},st),{segmentNumber:ot.toString(10),segmentTime:(De+Vi*et).toString(10)})),Io=(Ui!=null?Ui:0)+Vi*$s,fc=Io+$s;ot++,$t.push({time:{from:Io,to:fc},url:hc})}De+=(Dt+1)*et,at+=(Dt+1)*$s}nt=De/rt*1e3,$i=Qi(Ze,Object.assign(Object.assign({},st),{segmentNumber:ot.toString(10),segmentTime:De.toString(10)}))}else if(D(Ge)){const De=parseInt((re=je.getAttribute("duration"))!==null&&re!==void 0?re:"",10)/rt*1e3,At=Math.ceil(Ge/De);let et=0;for(let Dt=1;Dt<At;Dt++){const Qt=Qi(Ze,Object.assign(Object.assign({},st),{segmentNumber:Dt.toString(10),segmentTime:et.toString(10)}));$t.push({time:{from:et,to:et+De},url:Qt}),et+=De}nt=et,$i=Qi(Ze,Object.assign(Object.assign({},st),{segmentNumber:At.toString(10),segmentTime:et.toString(10)}))}const Ai={time:{from:nt,to:1/0},url:$i};bi={type:gt.TEMPLATE,baseUrl:Es,segmentTemplateUrl:Ze,initUrl:Ei,totalSegmentsDurationMs:at,segments:$t,nextSegmentBeyondManifest:Ai,timescale:rt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!it||!Ce)continue;const yi={video:Ue.VIDEO,audio:Ue.AUDIO,text:Ue.TEXT}[it];yi&&Le[yi].push({id:Sa,kind:yi,segmentReference:bi,profiles:ya,duration:Ge,bitrate:ys,mime:Ce,codecs:qt,width:Si,height:bs,fps:ma,quality:pa})}}return{dynamic:ai,liveAvailabilityStartTime:Fi,duration:Ge,container:la,representations:Le}},IT=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a})=>{var n;const o=(n=a?hs(a):void 0)!==null&&n!==void 0?n:ci({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r}},xT=({id:s,bitrate:e})=>({id:s,bitrate:e}),LT=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=Oe(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:Oe(s,-1)},CT=({id:s,lang:e,url:t,isAuto:i})=>({id:s,url:t,isAuto:i,type:"internal",language:e}),du=s=>"size"in s,qi=s=>s.type===gt.TEMPLATE,Kn=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);class uu{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 O,this.gaps=[],this.subscription=new ce,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new St,this.destroyAbortController=new St,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.liveInitialAdditionalOffset=0,this.isSeekingLive=!1,this.index=0,this.startWith=fe(this.destroyAbortController.signal,function(c){return pe(this,arguments,function*(){const h=this.representations.get(c);R(h,`Cannot find representation ${c}`),this.playingRepresentationId=c,this.downloadingRepresentationId=c,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${h.mime}; codecs="${h.codecs}"`),this.sourceBufferTaskQueue=new W0(this.sourceBuffer),this.subscription.add(V(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},b=>this.error$.next({id:"SegmentEjection",category:I.WTF,message:"Error when trying to clear segments ejected by browser",thrown:b}))),this.subscription.add(V(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:I.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(b=>{if(!this.sourceBuffer)return;const v=Math.min(this.bufferLimit,Nr(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 yield _(this.loadInit(h,"high",!0));const f=this.initData.get(h.id),p=this.segments.get(h.id),S=this.parsedInitData.get(h.id);if(R(f,"No init buffer for starting representation"),R(p,"No segments for starting representation"),!(f instanceof ArrayBuffer))return yield _(void 0);this.searchGaps(p,h),yield yield _(this.sourceBufferTaskQueue.append(f,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(S)})}.bind(this)),this.switchTo=fe(this.destroyAbortController.signal,function(c){return pe(this,arguments,function*(){if(c===this.downloadingRepresentationId||c===this.switchingToRepresentationId)return yield _(void 0);this.switchingToRepresentationId=c;const h=this.representations.get(c);R(h,`No such representation ${c}`);let f=this.segments.get(c),p=this.initData.get(c);if(W(p)||W(f)?yield yield _(this.loadInit(h,"high",!1)):p instanceof Promise&&(yield yield _(p)),f=this.segments.get(c),R(f,"No segments for starting representation"),p=this.initData.get(c),!p||!(p instanceof ArrayBuffer)||!this.sourceBuffer)return yield _(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=c,this.abort(),yield yield _(this.sourceBufferTaskQueue.append(p,this.downloadAbortController.signal));const S=this.getCurrentPosition();D(S)&&(f.forEach(b=>b.status=Z.NONE),this.pruneBuffer(S,1/0,!0),this.maintain(S))})}.bind(this)),this.seekLive=fe(this.destroyAbortController.signal,function(c){var h;return pe(this,arguments,function*(){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!c)return yield _(void 0);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||!qi(E.segmentReference))return yield _(void 0);const $=this.getActualLiveStartingSegments(E.segmentReference);this.segments.set(E.id,$)}const f=(h=this.switchingToRepresentationId)!==null&&h!==void 0?h:this.downloadingRepresentationId,p=this.representations.get(f);R(p);const S=this.segments.get(f);R(S,"No segments for starting representation");const b=this.initData.get(f);if(R(b,"No init buffer for starting representation"),!(b instanceof ArrayBuffer))return yield _(void 0);const v=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),v&&(yield yield _(this.sourceBufferTaskQueue.remove(v.from*1e3,v.to*1e3,this.destroyAbortController.signal))),this.searchGaps(S,p),yield 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 os.MP4:this.containerParser=ET;break;case os.WEBM:this.containerParser=DT;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 St,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(W(e)||W(this.downloadingRepresentationId)||W(this.playingRepresentationId)||W(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(R(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=tt(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)&&Nr(this.sourceBuffer.buffered)>=this.bufferLimit){const d=tt(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=Oe(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&&tt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const u=Oe(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||!qi(n.segmentReference))return;const o=n.segmentReference.segments.map(c=>Object.assign(Object.assign({},c),{status:Z.NONE,size:void 0})),u=(i=this.segments.get(n.id))!==null&&i!==void 0?i:[],d=(a=(r=Oe(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(!qi(r))return;const a=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),n=Qi(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}},p)=>{const S=h<=i&&f>=i,b=h>i||S||p===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&&!as(this.sourceBuffer.buffered,i))&&b&&y});if(r===-1)return[];if(t!==gt.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}loadSegments(e,t,i="auto"){return ee(this,void 0,void 0,function*(){t.segmentReference.type===gt.TEMPLATE?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return ee(this,void 0,void 0,function*(){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}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield fe(o,function(){return pe(this,arguments,function*(){const d=Ls(this.failedDownloads,this.tuning.downloadBackoff);yield yield _(new Promise(l=>setTimeout(l,d)))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{const d=yield this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority:i,isLowLatency:this.isActiveLowLatency()});if(!d)return;const l=new DataView(d);if(this.isActiveLowLatency()){const c=t.segmentReference.timescale;r.segment.time.to=this.containerParser.getSegmentEndTime(l,c)}u&&r.feedingBytes?r.segment.status=Z.DOWNLOADED:this.sourceBufferTaskQueue.append(l,o).then(c=>{this.onSegmentFullyAppended(r,t.id)}),this.failedDownloads=0}catch(d){if(!Kn(d))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(d)}})}loadByteRangeSegments(e,t,i="auto"){return ee(this,void 0,void 0,function*(){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&&(yield fe(n,function(){return pe(this,arguments,function*(){const u=Ls(this.failedDownloads,this.tuning.downloadBackoff);yield yield _(new Promise(d=>setTimeout(d,u)))})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.failedDownloads=0}catch(u){if(!Kn(u))return;this.abortActiveSegments(e),this.onSegmentDownloadError(u)}})}prepareByteRangeFetchSegmentParams(e,t){if(qi(t.segmentReference))throw new Error("Representation is not byte range type");const i=t.segmentReference.url,r={from:Oe(e,0).byte.from,to:Oe(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:I.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}}}prepareTemplateFetchSegmentParams(e,t){if(!qi(t.segmentReference))throw new Error("Representation is not template type");const i=new URL(e.url,t.segmentReference.baseUrl).toString(),{signal:r}=this.downloadAbortController,a=()=>{this.abort()},o=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(u,d)=>{if(!r.aborted)try{this.onSomeTemplateDataLoaded({dataView:u,loaded:d,signal:r,onSegmentAppendFailed:a,representationId:t.id})}catch(l){this.error$.next({id:"SegmentFeeding",category:I.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:l})}}:void 0;return{url:i,signal:r,onProgress: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=tt((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:I.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){if(!this.activeSegments.size)return;const n=this.representations.get(t);if(n)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,this.sourceBufferTaskQueue.append(l).then(c=>{o.fedBytes+=l.byteLength,u.status===Z.DOWNLOADED&&this.onSegmentFullyAppended(o,n.id)}))}}}}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===gt.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,du(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=Mr(()=>Ks(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return ee(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?fe(this.destroyAbortController.signal,function(){return pe(this,arguments,function*(){const o=Ls(this.failedDownloads,this.tuning.downloadBackoff);yield yield _(new Promise(u=>setTimeout(u,o)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(o=>ee(this,void 0,void 0,function*(){if(!o)return;const{init:u,dataView:d,segments:l}=o,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c);let h=l;this.isLive&&qi(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:I.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}pruneBuffer(e,t,i=!1){return ee(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||W(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=du(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=Mr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:I.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(W(this.sourceBuffer)||W(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 es;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(es||(es={}));class OT{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 St,this.subscription=new ce,this.fetchManifest=fe(this.abortAllController.signal,function(r){return pe(this,arguments,function*(){let a=r;this.requestQuic&&(a=li(a));const n=yield yield _(Ci(a,{signal:this.abortAllController.signal}).catch(_s));return n?(this.onHeadersReceived(n.headers),yield _(n.text())):yield _(null)})}.bind(this)),this.fetch=fe(this.abortAllController.signal,function(r,{rangeMethod:a=this.compatibilityMode?es.HEADER:es.PARAM,range:n,onProgress:o,priority:u="auto",signal:d,measureThroughput:l=!0,isLowLatency:c=!1}={}){var h,f;return pe(this,arguments,function*(){let p=r;const S=new Headers;if(n)switch(a){case es.HEADER:{S.append("Range",`bytes=${n.from}-${n.to}`);break}case es.PARAM:{const M=new URL(p,location.href);M.searchParams.append("bytes",`${n.from}-${n.to}`),p=M.toString();break}default:z(a)}this.requestQuic&&(p=li(p));let b=this.abortAllController.signal,v;if(d){const M=new St;if(v=G(V(this.abortAllController.signal,"abort"),V(d,"abort")).subscribe(()=>{try{M.abort()}catch(J){_s(J)}}),this.abortAllController.signal.aborted||d.aborted)try{M.abort()}catch(J){_s(J)}b=M.signal}const y=he(),g=yield yield _(Ci(p,{priority:u,headers:S,signal:b}).catch(_s)),E=he();if(!g)return v==null||v.unsubscribe(),yield _(null);if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(E-y),!g.ok||!g.body)return v==null||v.unsubscribe(),yield _(Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`)));if(this.onHeadersReceived(g.headers),!o&&!l)return v==null||v.unsubscribe(),yield _(g.arrayBuffer());const[$,L]=g.body.tee(),j=$.getReader();l&&((f=this.throughputEstimator)===null||f===void 0||f.trackStream(L,c));let K=0,H=new Uint8Array(0),q=!1;const Q=M=>{v==null||v.unsubscribe(),q=!0,_s(M)},B=fe(b,function({done:M,value:J}){return pe(this,arguments,function*(){if(K===0&&this.lastRequestFirstBytes$.next(he()-y),b.aborted)return v==null||v.unsubscribe(),yield _(void 0);if(!M&&J){const N=new Uint8Array(H.length+J.length);N.set(H),N.set(J,H.length),H=N,K+=J.byteLength,o==null||o(new DataView(H.buffer),K),yield yield _(j==null?void 0:j.read().then(B,Q))}})}.bind(this));return yield yield _(j==null?void 0:j.read().then(B,Q)),v==null||v.unsubscribe(),yield _(q?null:H.buffer)})}.bind(this)),this.fetchByteRangeRepresentation=fe(this.abortAllController.signal,function(r,a,n){var o;return pe(this,arguments,function*(){if(r.type!==gt.BYTE_RANGE)return yield _(null);const{from:u,to:d}=r.initRange;let l=u,c=d,h=!1,f,p;r.indexRange&&(f=r.indexRange.from,p=r.indexRange.to,h=d+1===f,h&&(l=Math.min(f,u),c=Math.max(p,d))),l=Math.min(l,0);const S=yield yield _(this.fetch(r.url,{range:{from:l,to:c},priority:n,measureThroughput:!1}));if(!S)return yield _(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 yield _(this.fetch(r.url,{range:y,priority:n,measureThroughput:!1}));if(!$)return yield _(null);g=new DataView($)}const E=a.parseSegments(g,v,y);return yield _({init:v,dataView:new DataView(S),segments:E})})}.bind(this)),this.fetchTemplateRepresentation=fe(this.abortAllController.signal,function(r,a){return pe(this,arguments,function*(){if(r.type!==gt.TEMPLATE)return yield _(null);const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield yield _(this.fetch(n,{priority:a,measureThroughput:!1}));if(!o)return yield _(null);const u=r.segments.map(d=>Object.assign(Object.assign({},d),{status:Z.NONE,size:void 0}));return yield _({init:null,segments:u,dataView:new DataView(o)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=_o(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){var r,a;return ee(this,void 0,void 0,function*(){const{type:n}=e;switch(n){case gt.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case gt.TEMPLATE:return(a=yield this.fetchTemplateRepresentation(e,i))!==null&&a!==void 0?a:null;default:z(n)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const _s=s=>{if(!Kn(s))throw s},Jn=1e3,jr=(s,e,t)=>t*e+(1-t)*s,nc=(s,e)=>s.reduce((t,i)=>t+i,0)/e,BT=(s,e,t,i)=>{let r=0,a=t;const n=nc(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 Ro{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 Lt(`raw_${i}`),this.smoothedSeries$=new Lt(`smoothed_${i}`),this.reportedSeries$=new Lt(`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+=Math.pow(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)&&(W(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 MT extends Ro{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=jr(this.slow,e,this.params.emaAlphaSlow),this.fast=jr(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class NT extends Ro{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=nc(this.pastMeasures,this.takenMeasures);this.emaSmoothed=jr(this.emaSmoothed,e,this.params.emaAlpha);const i=BT(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class FT extends Ro{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?jr(this.smoothed,e,this.params.emaAlpha):e}}class Xn{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new MT({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new NT({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 FT(Object.assign({initial:e,label:"liveEdgeDelay"},t))}}const UT=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)},lu=["timeupdate","progress","play","seeked","stalled","waiting"];var mt;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(mt||(mt={}));let VT=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new ce,this.representationSubscription=new ce,this.state$=new me(mt.NONE),this.currentVideoRepresentation$=new T(void 0),this.currentVideoRepresentationInit$=new T(void 0),this.error$=new O,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.forceEnded$=new O,this.gapWatchdogStarted=!1,this.destroyController=new St,this.initManifest=fe(this.destroyController.signal,function(t,i,r){var a;return pe(this,arguments,function*(){this.element=t,this.manifestUrlString=qe(i,r,Te.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(mt.MANIFEST_READY),this.manifest=yield yield _(this.updateManifest()),!((a=this.manifest)===null||a===void 0)&&a.representations.video.length?this.state$.setState(mt.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:I.PARSER,message:"No playable video representations"})})}.bind(this)),this.updateManifest=fe(this.destroyController.signal,function(){var t;return pe(this,arguments,function*(){const i=yield yield _(this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:I.NETWORK,message:"Failed to load manifest",thrown:n})}));if(!i)return yield _(this.manifest);let r;try{r=RT(i!=null?i:"",this.manifestUrlString)}catch(n){this.error$.next({id:"ManifestParsing",category:I.PARSER,message:"Failed to parse MPD manifest",thrown:n})}if(!r)return yield _(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===Ue.TEXT)};return r.dynamic&&this.isLive$.getValue()!==r.dynamic&&(this.isLive$.next(r.dynamic),this.liveDuration$.getValue()!==r.duration&&this.liveDuration$.next(-1*((t=r.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==r.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(r.liveAvailabilityStartTime)),yield _(Object.assign(Object.assign({},r),{representations:xi(Object.entries(r.representations).map(([n,o])=>[n,o.filter(a)]))}))})}.bind(this)),this.initRepresentations=fe(this.destroyController.signal,function(t,i){return pe(this,arguments,function*(){R(this.manifest),R(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(mt.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 uu(Ue.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],D(i)&&(this.audioBufferManager=new uu(Ue.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(Ii(Jn).subscribe(o=>{var u;if(!((u=this.element)===null||u===void 0)&&u.paused){const d=Lr(this.manifestUrlString,Te.DASH_CMAF_OFFSET_P);this.manifestUrlString=qe(this.manifestUrlString,d+Jn,Te.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(G(...lu.map(o=>V(this.element,o))).pipe(P(o=>this.element?tt(this.element.buffered,this.element.currentTime*1e3):0),ye(),oe(o=>!!o)).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(oe(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),UT(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(p=>{var S,b;return(b=(S=p.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(Be({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).subscribe(({liveLoadBufferLength:u,bufferLength:d})=>ee(this,void 0,void 0,function*(){if(R(this.element),this.isUpdatingLive)return;const l=this.element.playbackRate,c=Lr(this.manifestUrlString,Te.DASH_CMAF_OFFSET_P),h=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,f=Math.min(h,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*l),p=this.tuning.dashCmafLive.normalizedActualBufferOffset*l,S=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*l,b=this.isActiveLowLatency?d:u;let v=xt.None;if(this.isActiveLowLatency?v=xt.ActiveLowLatency:b<f+S&&b>=f?v=xt.LiveWithTargetOffset:c!==0&&b<f&&(v=xt.LiveForwardBuffering),isFinite(u)&&(o=u>o?u:o),v===xt.LiveForwardBuffering||v===xt.LiveWithTargetOffset){const y=o-(f+p),g=Math.trunc(c+y/l);let E;u?g>0?E=g:E=0:E=c,this.manifestUrlString=qe(this.manifestUrlString,E,Te.DASH_CMAF_OFFSET_P)}v!==xt.None&&v!==xt.ActiveLowLatency&&(o=0,this.updateLive())})))}const a=G(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(P(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=G(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(P(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.representationSubscription.add(G(this.forceEnded$,Be({allBuffersFull:a,someBufferEnded:n}).pipe(oe(({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:I.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:u})}})),this.representationSubscription.add(G(...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 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 yield _(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)])):yield yield _(this.videoBufferManager.startWith(t)),this.state$.setState(mt.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=Ii(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:I.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new OT({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Xn.getLiveEstimatedDelaySmoothedValue(0,Object.assign({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){var t,i,r,a;return ee(this,void 0,void 0,function*(){R(this.element),this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&e===0,this.manifestUrlString=qe(this.manifestUrlString,e,Te.DASH_CMAF_OFFSET_P),this.manifest=yield this.updateManifest(),yield(t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((i=this.manifest)===null||i===void 0?void 0:i.representations.video),yield(r=this.audioBufferManager)===null||r===void 0?void 0:r.seekLive((a=this.manifest)===null||a===void 0?void 0:a.representations.audio)})}initBuffer(){R(this.element),this.state$.setState(mt.RUNNING),this.subscription.add(G(...lu.map(e=>V(this.element,e)),V(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:I.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(V(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(V(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&as(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}switchRepresentation(e,t){return ee(this,void 0,void 0,function*(){const i={[Ue.VIDEO]:this.videoBufferManager,[Ue.AUDIO]:this.audioBufferManager,[Ue.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)})}seek(e,t){var i,r,a,n,o;R(this.element),R(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),as(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(mt.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}updateLive(){var e;return ee(this,void 0,void 0,function*(){this.isUpdatingLive=!0,this.manifest=yield 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.isLive$.getValue()&&!this.isActiveLowLatency&&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):Math.trunc(this.element.currentTime*1e3)!==Math.trunc(r)&&(this.element.currentTime=r/1e3)}}};class oc{constructor(e){this.subscription=new ce,this.videoState=new me(we.STOPPED),this.elementSize$=new T(void 0),this.textTracksManager=new Pt,this.droppedFramesManager=new Xs,this.videoTracks$=new T([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Vl,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===ie.Requested&&(o==null?void 0:o.to)!==m.PAUSED&&a!==we.STOPPED&&n!==m.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===m.STOPPED){a!==we.STOPPED&&(this.videoState.startTransitionTo(we.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(we.STOPPED),x(this.params.desiredState.playbackState,m.STOPPED,!0));return}switch(a){case we.STOPPED:this.videoState.startTransitionTo(we.READY),this.prepare();return;case we.READY:n===m.PAUSED?(this.videoState.setState(we.PAUSED),x(this.params.desiredState.playbackState,m.PAUSED)):n===m.PLAYING?(this.videoState.startTransitionTo(we.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===m.READY&&x(this.params.desiredState.playbackState,m.READY);return;case we.PLAYING:n===m.PAUSED?(this.videoState.startTransitionTo(we.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(o==null?void 0:o.to)===m.PLAYING&&x(this.params.desiredState.playbackState,m.PLAYING);return;case we.PAUSED:n===m.PLAYING?(this.videoState.startTransitionTo(we.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)===m.PAUSED&&x(this.params.desiredState.playbackState,m.PAUSED);return;default:return z(a)}}},this.init3DScene=t=>{var i,r,a;if(this.scene3D)return;this.scene3D=new ec(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=Ft(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(Qe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new VT({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=Vt(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:I.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo: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(P(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(oe(D),_e()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(fi(this.video,t.isLooped,r)),this.subscription.add(Nt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ii(this.video,t.playbackRate,i.playbackRateState$,r)),a(Us(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(we.PLAYING),x(t.playbackState,m.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(we.PAUSED),x(t.playbackState,m.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===we.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d===mt.MANIFEST_READY){const c=[];this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();R(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((v,y)=>y.bitrate-v.bitrate),p=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=xT(v);y&&this.audioTracks.push({track:y,representation:v})}for(const v of p){const y=IT(v);if(y){c.push({track:y,representation:v});const g=!this.params.tuning.isAudioDisabled&<(f,p,v);g&&this.audioRepresentations.set(v.id,g)}}this.videoTracks$.next(c);for(const v of S){const y=CT(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();R(b),this.player.initRepresentations(b.id,(l=this.audioRepresentations.get(b.id))===null||l===void 0?void 0:l.id)}else d===mt.REPRESENTATIOS_READY&&(this.videoState.setState(we.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:I.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(G(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,V(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!==mt.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(Ue.VIDEO,c.id).catch(n);const f=this.audioRepresentations.get(c.id);f&&this.player.switchRepresentation(Ue.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(ye(),P(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(P(({to:d})=>d===m.READY),ye());this.subscription.add(G(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===m.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(G(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===m.READY)));const u=G(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,We(["init"])).pipe(ct(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=tt(this.video.buffered,this.video.currentTime*1e3),f=u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=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=Ni(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:p,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(){si(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(we.PAUSED),x(this.params.desiredState.playbackState,m.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:I.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Ut(this.video)}}class HT extends oc{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 GT=class extends tc{constructor(e){super(e),this.liveOffset=new Js}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(Be({interval:Ii(Wn),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()===Ae.PLAYING){const n=e.position$.getValue()+(r-1);e.position$.next(n),(a=this.liveOffset)===null||a===void 0||a.resetTo(-n*1e3)}})).add(Be({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(P(({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===m.PAUSED&&i===Ae.PAUSED,a=-e,n=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)===null||o===void 0||o.resetTo(n,r)})}};class jT extends oc{constructor(e){super(e),this.liveOffset=new Js}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(Be({interval:Ii(Jn),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()===we.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(Be({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(P(({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===m.PAUSED&&i===we.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 It={};var le;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(le||(le={}));const Ps=(s,e)=>new qr(t=>{const i=(r,a)=>t.next(a);return s.on(e,i),()=>s.off(e,i)});class YT{constructor(e){this.subscription=new ce,this.videoState=new me(le.INITIALIZING),this.textTracksManager=new Pt,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!==le.INITIALIZING)switch((r==null?void 0:r.to)!==m.PAUSED&&a.state===ie.Requested&&this.seek(a.position),i){case m.STOPPED:switch(t){case le.STOPPED:break;case le.READY:case le.PLAYING:case le.PAUSED:this.stop();break;default:z(t)}break;case m.READY:switch(t){case le.STOPPED:this.prepare();break;case le.READY:case le.PLAYING:case le.PAUSED:break;default:z(t)}break;case m.PLAYING:switch(t){case le.PLAYING:break;case le.STOPPED:this.prepare();break;case le.READY:case le.PAUSED:this.playIfAllowed();break;default:z(t)}break;case m.PAUSED:switch(t){case le.PAUSED:break;case le.STOPPED:this.prepare();break;case le.READY:this.videoState.setState(le.PAUSED),x(this.params.desiredState.playbackState,m.PAUSED);break;case le.PLAYING:this.pause();break;default:z(t)}break;default:z(i)}},this.video=Ft(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(Qe(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),Ut(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:I.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);Ks(import("hls.js").then(r=>{e||(It.Hls=r.default,It.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){R(It.Hls,"hls.js not loaded"),this.hls=new It.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(le.STOPPED)}subscribe(){R(It.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:I.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=Vt(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(fi(this.video,e.isLooped,i)),this.subscription.add(Nt(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ii(this.video,e.playbackRate,r.playbackRateState$,i)),this.subscription.add(Ps(this.hls,It.Events.ERROR).subscribe(d=>{var l;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:I.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(le.PLAYING),x(e.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(le.PAUSED),x(e.playbackState,m.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())===null||d===void 0?void 0:d.to)===le.READY&&this.videoState.setState(le.READY),this.videoState.getState()===le.PLAYING&&this.playIfAllowed()},i)),a(Ps(this.hls,It.Events.MANIFEST_PARSED).pipe(P(({levels:d})=>d.reduce((l,c)=>{var h,f;const p=c.name||c.height.toString(10),{width:S,height:b}=c,v=(f=hs((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:ci({width:S,height:b});if(!v)return l;const y=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,g={id:p.toString(),quality:v,bitrate:c.bitrate/1e3,size:{width:S,height:b},fps:y};return this.trackLevels.set(p,{track:g,level:c}),l.push(g),l},[]))),t.availableVideoTracks$),a(Ps(this.hls,It.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||"",p=c.lang,S="internal";l.push({id:h,url:f,language:p,type:S})}e.internalTextTracks.startTransitionTo(l)}}),a(Ps(this.hls,It.Events.LEVEL_LOADING).pipe(P(({url:d})=>Qe(d))),t.hostname$),this.subscription.add(kt(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=Ps(this.hls,It.Events.LEVEL_SWITCHED).pipe(P(({level:d})=>n(this.hls.levels[d])));o.pipe(oe(D)).subscribe(t.currentVideoTrack$,i),this.subscription.add(kt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),d=>{var l;if(W(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,p=this.hls.levels[f];!p||c.bitrate>p.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=G(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,We(["init"])).pipe(ct(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(le.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return ee(this,void 0,void 0,function*(){this.videoState.startTransitionTo(le.PLAYING),(yield si(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:I.DOM,thrown:t})))||(this.videoState.setState(le.PAUSED),x(this.params.desiredState.playbackState,m.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(le.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(le.STOPPED),x(this.params.desiredState.playbackState,m.STOPPED,!0)}}const cu="X-Playback-Duration";var hu=s=>ee(void 0,void 0,void 0,function*(){var e;const t=yield Ci(s),i=yield 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(cu)?parseInt(t.headers.get(cu),10):void 0});const zT=s=>{let e=null;if(s.QUALITY&&(e=hs(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=ci({width:t,height:i})}return e!=null?e:null},dc=(s,e=s)=>ee(void 0,void 0,void 0,function*(){var t,i;const n=(yield(yield Ci(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=xi(c[1].split(",").map(E=>E.split("="))),p=(t=f.QUALITY)!==null&&t!==void 0?t:`stream-${f.BANDWIDTH}`,S=zT(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:p,quality:S,url:g,bandwidth:b,size:y,fps:v})}if(h){const f=xi(h[1].split(",").map(v=>v.split("=")).map(([v,y])=>[v,y.replace(/^"|"$/g,"")])),p=(i=f.URI)===null||i===void 0?void 0:i.replace(/playlist$/,"subtitles.vtt"),S=f.LANGUAGE,b=f.NAME;p&&S&&u.push({type:"internal",id:S,label:b,language:S,url:p,isAuto:!1})}}}return{qualityManifests:o,textTracks:u}}),Yr=(s,e)=>{const t=W(e)||D(e.min)&&D(e.max)&&xs(e.max,e.min),i=D(s)&&s!==ut.INVARIANT;return t||i&&(W(e==null?void 0:e.min)||Pr(s,e==null?void 0:e.min))&&(W(e==null?void 0:e.max)||eo(s,e==null?void 0:e.max))};var ge;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(ge||(ge={}));class qT{constructor(e){var t;this.subscription=new ce,this.videoState=new me(ge.STOPPED),this.textTracksManager=new Pt,this.manifests$=new T([]),this.liveOffset=new Js,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();if(a===m.STOPPED){r!==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),x(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(r===ge.STOPPED){this.videoState.startTransitionTo(ge.READY),this.prepare();return}if(o||u){const c=this.videoState.getState();this.videoState.setState(ge.CHANGING_MANIFEST),this.videoState.startTransitionTo(c),this.prepare(),l.state===ie.None&&this.params.desiredState.seekState.setState({state:ie.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==m.PAUSED&&l.state===ie.Requested){this.videoState.startTransitionTo(ge.READY),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case ge.READY:a===m.READY?x(this.params.desiredState.playbackState,m.READY):a===m.PAUSED?(this.videoState.setState(ge.PAUSED),this.liveOffset.pause(),x(this.params.desiredState.playbackState,m.PAUSED)):a===m.PLAYING&&(this.videoState.startTransitionTo(ge.PLAYING),this.playIfAllowed());return;case ge.PLAYING:a===m.PAUSED?(this.videoState.startTransitionTo(ge.PAUSED),this.liveOffset.pause(),this.video.pause()):(n==null?void 0:n.to)===m.PLAYING&&x(this.params.desiredState.playbackState,m.PLAYING);return;case ge.PAUSED:if(a===m.PLAYING)if(this.videoState.startTransitionTo(ge.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 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.prepare()}else(n==null?void 0:n.to)===m.PAUSED&&(x(this.params.desiredState.playbackState,m.PAUSED),this.liveOffset.pause());return;case ge.CHANGING_MANIFEST:break;default:return z(r)}},this.params=e,this.video=Ft(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ut.INVARIANT,url:this.params.source.url},dc(qe(this.params.source.url),this.params.source.url).then(({qualityManifests:i})=>{this.allManifests=[...i];const r=this.params.desiredState.autoVideoTrackLimits.getState();this.manifests$.next([this.masterManifest,...this.allManifests.filter(({quality:a})=>Yr(a,r))])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:I.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(Qe(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;const{autoVideoTrackSwitching:i,videoTrack:r}=this.params.desiredState,a=i.getState(),n=r.getTransition(),o=(t=(e=n==null?void 0:n.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",u=this.manifests$.getValue();if(!u.length)return;const d=a?"master":o;return a&&!n&&r.startTransitionTo(this.masterManifest),u.find(l=>l.id===d)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:I.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=Vt(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(Nt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ii(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),x(t.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ge.PAUSED),x(t.playbackState,m.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)),this.subscription.add(this.maxSeekBackTime$.pipe(ye(),P(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(Qe(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===ge.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===ie.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(Be({startTime:this.manifestStartTime$.pipe(oe(D)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(P(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)),this.subscription.add(t.autoVideoTrackLimits.stateChangeStarted$.subscribe(o=>{const u=o.to;this.manifests$.next([this.masterManifest,...this.allManifests.filter(({quality:d})=>Yr(d,u))]),this.params.output.autoVideoTrackLimits$.next(o.to)}));const n=G(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.manifests$,We(["init"])).pipe(ct(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ut(this.video)}prepare(){const e=this.selectManifest();if(W(e))return;const t=this.params.format===A.HLS_LIVE_CMAF?Te.DASH_CMAF_OFFSET_P:Te.OFFSET_P,i=qe(e.url,this.liveOffset.getTotalOffset(),t);this.video.setAttribute("src",i),this.video.load(),hu(i).then(r=>{var a;if(!W(r))this.maxSeekBackTime$.next(r);else{const n=(a=this.params.source.maxSeekBackTime)!==null&&a!==void 0?a:this.maxSeekBackTime$.getValue();if(W(n)||!isFinite(n))try{Ci(i).then(o=>o.text()).then(o=>{var u;const d=(u=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(o))===null||u===void 0?void 0:u[1];if(d){const l=new URL(d,i).toString();hu(l).then(c=>{W(c)||this.maxSeekBackTime$.next(c)})}})}catch(o){}}})}playIfAllowed(){si(this.video).then(e=>{e||(this.videoState.setState(ge.PAUSED),this.liveOffset.pause(),x(this.params.desiredState.playbackState,m.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:I.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}var be;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(be||(be={}));class WT{constructor(e){this.subscription=new ce,this.videoState=new me(be.STOPPED),this.textTracksManager=new Pt,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();if(r===m.STOPPED){i!==be.STOPPED&&(this.videoState.startTransitionTo(be.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(be.STOPPED),x(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.seekState.getState();if(i===be.STOPPED){this.videoState.startTransitionTo(be.READY),this.prepare();return}if(n||o){const l=this.videoState.getState();this.videoState.setState(be.CHANGING_MANIFEST),this.videoState.startTransitionTo(l);const{currentTime:c}=this.video;this.prepare(),d.state===ie.None&&this.params.desiredState.seekState.setState({state:ie.Requested,position:c*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==m.PAUSED&&d.state===ie.Requested&&this.seek(d.position),i){case be.READY:r===m.READY?x(this.params.desiredState.playbackState,m.READY):r===m.PAUSED?(this.videoState.setState(be.PAUSED),x(this.params.desiredState.playbackState,m.PAUSED)):r===m.PLAYING&&(this.videoState.startTransitionTo(be.PLAYING),this.playIfAllowed());return;case be.PLAYING:r===m.PAUSED?(this.videoState.startTransitionTo(be.PAUSED),this.video.pause()):(a==null?void 0:a.to)===m.PLAYING&&x(this.params.desiredState.playbackState,m.PLAYING);return;case be.PAUSED:r===m.PLAYING?(this.videoState.startTransitionTo(be.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===m.PAUSED&&x(this.params.desiredState.playbackState,m.PAUSED);return;case be.CHANGING_MANIFEST:break;default:return z(i)}},this.params=e,this.video=Ft(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ut.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(Qe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),dc(this.params.source.url).then(({qualityManifests:t,textTracks:i})=>{this.allManifests=[...t];const r=this.params.desiredState.autoVideoTrackLimits.getState();this.manifests$.next([this.masterManifest,...this.allManifests.filter(({quality:a})=>Yr(a,r))]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:I.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:r}=this.params.desiredState,a=i.getState(),n=r.getTransition(),o=(t=(e=n==null?void 0:n.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",u=this.manifests$.getValue();if(!u.length)return;const d=a?"master":o;return a&&!n&&r.startTransitionTo(this.masterManifest),u.find(l=>l.id===d)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:I.WTF,message:"HlsProvider internal logic error",thrown:o})},r=Vt(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(fi(this.video,t.isLooped,i)),this.subscription.add(Nt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ii(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(be.PLAYING),x(t.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(be.PAUSED),x(t.playbackState,m.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===be.READY&&this.videoState.setState(be.READY),this.videoState.getState()===be.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(Qe(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===be.CHANGING_MANIFEST&&this.videoState.setState(u.to),o.state===ie.Requested&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(P(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)),this.subscription.add(t.autoVideoTrackLimits.stateChangeStarted$.subscribe(o=>{const u=o.to;this.manifests$.next([this.masterManifest,...this.allManifests.filter(({quality:d})=>Yr(d,u))]),this.params.output.autoVideoTrackLimits$.next(o.to)})),!bc()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:o}=this.video;this.subscription.add(G(V(o,"addtrack"),V(o,"removetrack"),V(o,"change"),We(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}const n=G(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,We(["init"])).pipe(ct(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ut(this.video)}prepare(){const e=this.selectManifest();W(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){si(this.video).then(e=>{e||(this.videoState.setState(be.PAUSED),x(this.params.desiredState.playbackState,m.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:I.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var ke;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(ke||(ke={}));class QT{constructor(e){this.subscription=new ce,this.videoState=new me(ke.STOPPED),this.trackUrls={},this.textTracksManager=new Pt,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===m.STOPPED){a!==ke.STOPPED&&(this.videoState.startTransitionTo(ke.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(ke.STOPPED),x(this.params.desiredState.playbackState,m.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!==ke.READY&&!l){this.handleQualityLimitTransition(d.to.max);return}if(a===ke.STOPPED){this.videoState.startTransitionTo(ke.READY),this.prepare();return}if(l){const{currentTime:h}=this.video;this.prepare(),c.state===ie.None&&this.params.desiredState.seekState.setState({state:ie.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)!==m.PAUSED&&c.state===ie.Requested&&this.seek(c.position),a){case ke.READY:n===m.READY?x(this.params.desiredState.playbackState,m.READY):n===m.PAUSED?(this.videoState.setState(ke.PAUSED),x(this.params.desiredState.playbackState,m.PAUSED)):n===m.PLAYING&&(this.videoState.startTransitionTo(ke.PLAYING),this.playIfAllowed());return;case ke.PLAYING:n===m.PAUSED?(this.videoState.startTransitionTo(ke.PAUSED),this.video.pause()):(o==null?void 0:o.to)===m.PLAYING&&x(this.params.desiredState.playbackState,m.PLAYING);return;case ke.PAUSED:n===m.PLAYING?(this.videoState.startTransitionTo(ke.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===m.PAUSED&&x(this.params.desiredState.playbackState,m.PAUSED);return;default:return z(a)}},this.params=e,this.video=Ft(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:I.WTF,message:"MpegProvider internal logic error",thrown:o})},r=Vt(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(fi(this.video,t.isLooped,i)),this.subscription.add(Nt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ii(this.video,t.playbackRate,r.playbackRateState$,i)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ke.PLAYING),x(t.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ke.PAUSED),x(t.playbackState,m.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ke.READY&&this.videoState.setState(ke.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()===ke.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const n=G(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,We(["init"])).pipe(ct(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),Ut(this.video)}prepare(){var e;const t=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id;R(t,"MpegProvider: track is not selected");let{url:i}=this.trackUrls[t];R(i,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(i=li(i)),this.video.setAttribute("src",i),this.video.load(),this.params.output.hostname$.next(Qe(i))}playIfAllowed(){si(this.video).then(e=>{e||(this.videoState.setState(ke.PAUSED),x(this.params.desiredState.playbackState,m.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:I.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,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=>!Ri(c.track.quality)&&eo(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&&Pr(l.quality,u.quality)&&(n=u),!n){const c=Object.values(this.trackUrls).filter(f=>!Ri(f.track.quality)&&ts(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=Ni(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 fu=["stun:videostun.mycdn.me:80"],KT=1e3,JT=3,cn=()=>null;class XT{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=cn,this.externalStopCallback=cn,this.externalErrorCallback=cn,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}}handleUpdateMessage(e){return ee(this,void 0,void 0,function*(){try{const t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return ee(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:fu}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return ee(this,void 0,void 0,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return ee(this,void 0,void 0,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:I.WTF,message:e.message})}onPeerConnectionStream(e){return ee(this,void 0,void 0,function*(){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return ee(this,void 0,void 0,function*(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=yield this.peerConnection.createOffer(e),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),KT)}normalizeOptions(e={}){const t={stunServerList:fu,maxRetryNumber:JT,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var Se;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Se||(Se={}));class ZT{constructor(e){this.videoState=new me(Se.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===m.STOPPED){t!==Se.STOPPED&&(this.videoState.startTransitionTo(Se.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Se.STOPPED),x(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===Se.STOPPED){this.videoState.startTransitionTo(Se.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case Se.READY:i===m.PAUSED?(this.videoState.setState(Se.PAUSED),x(this.params.desiredState.playbackState,m.PAUSED)):i===m.PLAYING&&(this.videoState.startTransitionTo(Se.PLAYING),this.playIfAllowed());return;case Se.PLAYING:i===m.PAUSED?(this.videoState.startTransitionTo(Se.PAUSED),this.video.pause()):(r==null?void 0:r.to)===m.PLAYING&&x(this.params.desiredState.playbackState,m.PLAYING);return;case Se.PAUSED:i===m.PLAYING?(this.videoState.startTransitionTo(Se.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===m.PAUSED&&x(this.params.desiredState.playbackState,m.PAUSED);return;default:return z(t)}},this.subscription=new ce,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ft(e.container),this.liveStreamClient=new XT(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),Ut(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:I.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};G(this.videoState.stateChangeStarted$.pipe(P(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(P(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const r=Vt(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)===Se.READY&&this.videoState.setState(Se.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(Se.PAUSED)},i)).add(r.playing$.subscribe(()=>{this.videoState.setState(Se.PLAYING)},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Nt(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case Se.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(m.STOPPED);break;case Se.READY:break;case Se.PAUSED:t.playbackState.setState(m.PAUSED);break;case Se.PLAYING:t.playbackState.setState(m.PLAYING);break;default:return z(n.to)}},i)).add(G(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,We(["init"])).pipe(ct(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(Qe(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:ut.INVARIANT}),this.video.srcObject=e,x(this.params.desiredState.playbackState,m.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(Se.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:I.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){si(this.video).then(e=>{e||(this.videoState.setState(Se.PAUSED),x(this.params.desiredState.playbackState,m.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:I.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class pu{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 hn,fn,pn,mn,vn,gn,Sn,bn,gr,yn,Sr,Tn,br,En,yr,$n,Tr,An,Er,wn;const uc=zr().device===yc.Android,di=document.createElement("video"),eE='video/mp4; codecs="avc1.42000a,mp4a.40.2"',tE='video/mp4; codecs="hev1.1.6.L93.B0"',lc='video/webm; codecs="vp09.00.10.08"',cc='video/webm; codecs="av01.0.00M.08"',iE='audio/mp4; codecs="mp4a.40.2"',sE='audio/webm; codecs="opus"',Me={mms:!!(window.ManagedMediaSource&&window.MediaStreamTrack&&(!((fn=(hn=window.SourceBuffer)===null||hn===void 0?void 0:hn.prototype)===null||fn===void 0)&&fn.appendBuffer)),mse:!!(window.MediaSource&&window.MediaStreamTrack&&(!((mn=(pn=window.SourceBuffer)===null||pn===void 0?void 0:pn.prototype)===null||mn===void 0)&&mn.appendBuffer)),hls:!!(!((vn=di.canPlayType)===null||vn===void 0)&&vn.call(di,"application/x-mpegurl")||!((gn=di.canPlayType)===null||gn===void 0)&&gn.call(di,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},dt={mp4:!!(!((Sn=di.canPlayType)===null||Sn===void 0)&&Sn.call(di,"video/mp4")),webm:!!(!((bn=di.canPlayType)===null||bn===void 0)&&bn.call(di,"video/webm")),cmaf:!0},Bt={h264:!!(!((yn=(gr=window.MediaSource)===null||gr===void 0?void 0:gr.isTypeSupported)===null||yn===void 0)&&yn.call(gr,eE)),h265:!!(!((Tn=(Sr=window.MediaSource)===null||Sr===void 0?void 0:Sr.isTypeSupported)===null||Tn===void 0)&&Tn.call(Sr,tE)),vp9:!!(!((En=(br=window.MediaSource)===null||br===void 0?void 0:br.isTypeSupported)===null||En===void 0)&&En.call(br,lc)),av1:!!(!(($n=(yr=window.MediaSource)===null||yr===void 0?void 0:yr.isTypeSupported)===null||$n===void 0)&&$n.call(yr,cc)),aac:!!(!((An=(Tr=window.MediaSource)===null||Tr===void 0?void 0:Tr.isTypeSupported)===null||An===void 0)&&An.call(Tr,iE)),opus:!!(!((wn=(Er=window.MediaSource)===null||Er===void 0?void 0:Er.isTypeSupported)===null||wn===void 0)&&wn.call(Er,sE))},Wi=(Bt.h264||Bt.h265)&&Bt.aac;var oi;(function(s){s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient"})(oi||(oi={}));var Xt;(function(s){s.DASH="dash",s.HLS="hls",s.MPEG="mpeg"})(Xt||(Xt={}));let ki;const rE=()=>ee(void 0,void 0,void 0,function*(){if(!window.navigator.mediaCapabilities)return;const s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},s),{video:Object.assign(Object.assign({},s.video),{contentType:cc})})),window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},s),{video:Object.assign(Object.assign({},s.video),{contentType:lc})}))]);ki={[A.DASH_WEBM_AV1]:e,[A.DASH_WEBM]:t}});try{rE()}catch(s){console.error(s)}const Vs=Me.hls&&dt.mp4,aE=()=>Object.keys(Bt).filter(s=>Bt[s]),nE=(s,e=!1)=>s.filter(t=>{switch(t){case A.DASH:return Me.mse&&dt.mp4&&Wi;case A.DASH_SEP:return(Me.mms||Me.mse)&&dt.mp4&&Wi;case A.DASH_WEBM:return(Me.mms||Me.mse)&&dt.webm&&Bt.vp9&&Bt.opus;case A.DASH_WEBM_AV1:return(Me.mms||Me.mse)&&dt.webm&&Bt.av1&&Bt.opus;case A.DASH_LIVE:return Me.mse&&dt.mp4&&Wi;case A.DASH_LIVE_CMAF:return(Me.mms||Me.mse)&&dt.mp4&&Wi&&dt.cmaf;case A.DASH_ONDEMAND:return(Me.mms||Me.mse)&&dt.mp4&&Wi;case A.HLS:case A.HLS_ONDEMAND:return Vs||e&&Me.mse&&dt.mp4&&Wi;case A.HLS_LIVE:case A.HLS_LIVE_CMAF:return Vs;case A.MPEG:return dt.mp4;case A.DASH_LIVE_WEBM:return!1;case A.WEB_RTC_LIVE:return Me.webrtc&&Me.ws&&Bt.h264&&(dt.mp4||dt.webm);default:return z(t)}}),Ds=s=>{const e=A.DASH_WEBM,t=A.DASH_WEBM_AV1;switch(s){case oi.VP9:return[e,t];case oi.AV1:return[t,e];case oi.NONE:return[];case oi.SMOOTH:return ki?ki[t].smooth?[t,e]:ki[e].smooth?[e,t]:[t,e]:[e,t];case oi.POWER_EFFICIENT:return ki?ki[t].powerEfficient?[t,e]:ki[e].powerEfficient?[e,t]:[t,e]:[e,t];default:z(s)}return[e,t]},oE=({webmCodec:s,androidPreferredFormat:e})=>{if(uc)switch(e){case Xt.MPEG:return[A.MPEG,...Ds(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND];case Xt.HLS:return[A.HLS,A.HLS_ONDEMAND,...Ds(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.MPEG];case Xt.DASH:return[...Ds(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG]}return Vs?[...Ds(s),A.DASH_SEP,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG,A.DASH]:[...Ds(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG]},dE=({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(uc)switch(s){case Xt.DASH:{o=a;break}case Xt.HLS:case Xt.MPEG:{o=n;break}}else Vs?o=n:o=a;return t?[A.WEB_RTC_LIVE,...o]:[...o,A.WEB_RTC_LIVE]},mu=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 uE=s=>new qr(e=>{const t=new ce,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(P(({from:d,to:l})=>`${d}-${l}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(P(({type:d})=>d!==void 0)),n=new O;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 lE={cacheDuration:12e4},cE={chunkDuration:5e3,maxParallelRequests:5};class hE{constructor(e){this.current$=new T({type:void 0}),this.providerError$=new O,this.noAvailableProvidersError$=new O,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 O,warning$:new O,willSeekEvent$:new O,seekedEvent$:new O,loopedEvent$:new O,endedEvent$:new O,firstBytesEvent$:new O,firstFrameEvent$:new O,canplay$:new O,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 ce,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=nE([...dE(this.params.tuning),...oE(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 pu(a);const n=[...mu(!0),...mu(!1)];this.chromecastFormatsIterator=new pu(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(W(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:I.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!==ie.None;if(this.params.desiredState.seekState.setState({state:ie.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 Ye.SCREEN:return this.createScreenProvider(t);case Ye.CHROMECAST:return this.createChromecastProvider(t);default:return z(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:r}=this.params,a=this.providerOutput,n={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case A.DASH:{const o=this.applyFailoverHost(t[e]);return R(o),new hy(Object.assign(Object.assign({},n),{source:o,config:lE}))}case A.DASH_SEP:case A.DASH_WEBM:case A.DASH_WEBM_AV1:case A.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return R(o),this.params.tuning.useDashJs?new Wd(Object.assign(Object.assign({},n),{source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}})):this.params.tuning.useNewDashVkProvider?new HT(Object.assign(Object.assign({},n),{source:o})):new q0(Object.assign(Object.assign({},n),{source:o}))}case A.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return R(o),this.params.tuning.useDashJsCMAF?new Wd(Object.assign(Object.assign({},n),{source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}})):this.params.tuning.useNewDashVkProvider?new jT(Object.assign(Object.assign({},n),{source:o})):new GT(Object.assign(Object.assign({},n),{source:o}))}case A.HLS:case A.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return R(o),Vs||!this.params.tuning.useHlsJs?new WT(Object.assign(Object.assign({},n),{source:o})):new YT(Object.assign(Object.assign({},n),{source:o}))}case A.HLS_LIVE:case A.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return R(o),new qT(Object.assign(Object.assign({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case A.MPEG:{const o=this.applyFailoverHost(t[e]);return R(o),new QT(Object.assign(Object.assign({},n),{source:o}))}case A.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return R(o),new oy(Object.assign(Object.assign({},n),{source:o,config:Object.assign(Object.assign({},cE),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case A.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return R(o),new ZT({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 R(o),new Sb({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()?Ye.CHROMECAST:Ye.SCREEN}chooseFormat(e){switch(e){case Ye.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case Ye.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return z(e)}}skipFormat(e){switch(e){case Ye.SCREEN:return this.screenFormatsIterator.next();case Ye.CHROMECAST:return this.chromecastFormatsIterator.next();default:return z(e)}}handleNoFormatsError(e){switch(e){case Ye.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case Ye.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return 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 Object.assign(Object.assign({},e),{url:i(e.url)})}return xi(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){const e=new ce;let t=!1,i=0;return e.add(G(this.providerOutput.error$,uE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(P(r=>({id:`ProviderHangup:${r}`,category:I.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const r=this.params.desiredState.playbackState.transitionEnded$.pipe(oe(({to:a})=>a===m.PLAYING),_e()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{const a=this.current$.getValue().destination;if(a===Ye.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(Ye.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=r.category===I.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:Ye.SCREEN)}})),e}}const fE=5e3,vu="one_video_throughput",gu="one_video_rtt",Zt=window.navigator.connection,Su=()=>{const s=Zt==null?void 0:Zt.downlink;if(D(s)&&s!==10)return s*1e3},bu=()=>{const s=Zt==null?void 0:Zt.rtt;if(D(s)&&s!==3e3)return s},yu=(s,e,t)=>{const i=t*8,r=i/s;return i/(r+e)};class Bs{constructor(e){var t,i;this.subscription=new ce,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=Bs.load(vu)||(e.useBrowserEstimation?Su():void 0)||fE,a=(i=(t=Bs.load(gu))!==null&&t!==void 0?t:e.useBrowserEstimation?bu():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new T(r),this.rtt$=new T(a),this.rttAdjustedThroughput$=new T(yu(r,a,e.rttPenaltyRequestSize)),this.throughput=Xn.getSmoothedValue(r,-1,e),this.rtt=Xn.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const u=Su();u&&this.throughput.next(u);const d=bu();D(d)&&this.rtt.next(d)};Zt&&"onchange"in Zt&&this.subscription.add(V(Zt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Ea.set(vu,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Ea.set(gu,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Be({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(P(({throughput:n,rtt:o})=>yu(n,o,e.rttPenaltyRequestSize)),oe(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=he();const r=new ce;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(V(e,"progress").pipe(_e()).subscribe(a=>{t=a.loaded,i=he()}));break;case 1:case 0:r.add(V(e,"loadstart").subscribe(()=>{t=0,i=he()}));break}r.add(V(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=he(),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=he(),n=0,o=he();const u=l=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${l}`).catch(()=>{})},d=({done:l,value:c})=>ee(this,void 0,void 0,function*(){l?(!t&&this.addRawSpeed(r,he()-a,1),this.concurrentDownloads.delete(e)):c&&(t?(he()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval&&he()-a<this.tuningConfig.lowLatency.separateByteSequenceInterval?n+=c.byteLength:(this.addRawSpeed(n,he()-a,this.concurrentDownloads.size,t),n=c.byteLength,a=he()),o=he()):(r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&he()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,he()-o,this.concurrentDownloads.size),n=0,o=he())),yield 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(r||Bs.sanityCheck(e,t)){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){const i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||e<10*1024||t<=20)}static load(e){var t;const i=Ea.get(e);if(D(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const Tu={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:5,separateByteSequenceInterval:100}},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:ut.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,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!0,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:oi.VP9,androidPreferredFormat:Xt.MPEG,preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,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}},pE=s=>{var e;return Object.assign(Object.assign({},Tc(s,Tu)),{configName:[...(e=s.configName)!==null&&e!==void 0?e:[],...Tu.configName]})};var Eu=({seekState:s,position$:e})=>G(s.stateChangeEnded$.pipe(P(({to:t})=>{var i;return t.state===ie.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),oe(D)),e.pipe(oe(()=>s.getState().state===ie.None))),mE=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return R(e,`Wrong container or containerId {${s.container}}`),e};const vE=(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(oe(r=>r.length>0),_e()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};class zE{constructor(e={configName:[]}){if(this.subscription=new ce,this.logger=new Ec,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.desiredState={playbackState:new me(m.STOPPED),seekState:new me({state:ie.None}),volume:new me({volume:1,muted:!1}),videoTrack:new me(void 0),autoVideoTrackSwitching:new me(!0),autoVideoTrackLimits:new me({}),isLooped:new me(!1),playbackRate:new me(1),externalTextTracks:new me([]),internalTextTracks:new me([]),currentTextTrack:new me(void 0),textTrackCuesSettings:new me({}),cameraOrientation:new me({x:0,y:0})},this.info={playbackState$:new T(m.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(ni.NONE),chromecastState$:new T(Ne.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 O,ready$:new O,started$:new O,playing$:new O,paused$:new O,stopped$:new O,willStart$:new O,willResume$:new O,willPause$:new O,willStop$:new O,willDestruct$:new O,watchCoverageRecord$:new O,watchCoverageLive$:new O,managedError$:new O,fatalError$:new O,ended$:new O,looped$:new O,seeked$:new O,willSeek$:new O,firstBytes$:new O,firstFrame$:new O,canplay$:new O,log$:new O},this.experimental={element$:new T(void 0),tuningConfigName$:new T([]),enableDebugTelemetry$:new T(!1),dumpTelemetry:Vb},this.initLogs(),this.tuning=pE(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new kc({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Bs(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 p=typeof f;return["number","string","boolean"].includes(p)?f:f===null?null:`<${p}>`})),d=`Player.${String(i)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:I.WTF,message:l,thrown:o}),o}}}})}initVideo(e){var t,i,r;return this.config=e,this.domContainer=mE(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new hE({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()===m.STOPPED&&e.startTransitionTo(m.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==m.PLAYING&&t.startTransitionTo(m.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?V(document,"visibilitychange").pipe(_e()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==m.PAUSED&&e.startTransitionTo(m.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==m.STOPPED&&e.startTransitionTo(m.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:ie.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()===Ne.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()===Ne.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){R(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(oe(i=>i.length>0),_e()).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;R(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=>Object.assign({type:"external"},t))),this}selectTextTrack(e){var t;return vE(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(){R(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(W(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===ie.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(G(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(P(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(P(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(P(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(P(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(P(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(oe(({from:e})=>e===m.STOPPED),_e()).subscribe(()=>{this.initedAt=he(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case m.READY:this.events.ready$.next();break;case m.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case m.PAUSED:this.events.paused$.next();break;case m.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case m.PAUSED:this.events.willPause$.next();break;case m.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case m.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===ie.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},n),{state:ie.Applying})):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:I.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===ie.Applying&&(this.desiredState.seekState.setState({state:ie.None}),this.events.seeked$.next())})).add(e.current$.pipe(P(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(P(n=>n.destination),ye()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(P(n=>n.map(({quality:o})=>o).sort((o,u)=>Ri(o)?1:Ri(u)?-1:ts(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(ye()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(ye()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(ye()).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(P(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(Be({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Eu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(P(({isLive:n,position:o,isLowLatency:u})=>{const d=u?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return n&&Math.abs(o)<d/1e3}),ye(),_r(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(Be({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(P(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),ye(),_r(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(P(n=>n.muted),ye()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(P(n=>n.volume),ye()).subscribe(this.info.volume$)).add(Eu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(G(e.providerOutput.endedEvent$.pipe(ss(!0)),e.providerOutput.seekedEvent$.pipe(ss(!1))).pipe(ye()).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(P(n=>({id:n?`No${n}`:"NoProviders",category:I.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(_e(),P(n=>n!=null?n:he()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(_e(),P(()=>he()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(_e(),P(()=>he()-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(oe(({to:n})=>n===m.PLAYING),_e()).subscribe(()=>i.next(!1)));let r=0;const a=G(e.providerOutput.isBuffering$,t,i).pipe(P(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),ye());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(G(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(G(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===Ne.CONNECTED?l=ni.SECOND_SCREEN:u?n?l=ni.PIP:o?l=ni.FULLSCREEN:l=ni.INLINE:l=ni.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(P(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 ce;this.subscription.add(t),this.subscription.add(e.current$.pipe(ye((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(oe(i=>i.length>0),_e()).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=Ni(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(G(this.desiredState.videoTrack.stateChangeStarted$.pipe(P(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(P(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(P(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(P(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(P(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(P(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(P(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(P(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(P(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;R(this.providerContainer),R(t),Ub(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Fb(i)),this.providerContainer.current$.subscribe(({type:i})=>fr("provider",i)),t.duration$.subscribe(i=>fr("duration",i)),t.availableVideoTracks$.pipe(oe(i=>!!i.length),_e()).subscribe(i=>fr("tracks",i)),this.events.fatalError$.subscribe(new Lt("fatalError")),this.events.managedError$.subscribe(new Lt("managedError")),t.position$.subscribe(new Lt("position")),t.currentVideoTrack$.pipe(P(i=>i==null?void 0:i.quality)).subscribe(new Lt("quality")),this.info.currentBuffer$.subscribe(new Lt("buffer")),t.isBuffering$.subscribe(new Lt("isBuffering"))].forEach(i=>this.subscription.add(i)),fr("codecs",aE())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},i=()=>ee(this,void 0,void 0,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:I.DOM,message:String(r)})})});this.subscription.add(G(V(document,"visibilitychange"),V(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===m.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 qE=`@vkontakte/videoplayer-core@${Ac}`;export{Ne as ChromecastState,Ms as HttpConnectionType,KE as Observable,m as PlaybackState,zE as Player,qE as SDK_VERSION,JE as Subject,XE as Subscription,ni as Surface,Ac as VERSION,ZE as ValueSubject,A as VideoFormat,e$ 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 Zl{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 H0(this.params.fov,this.params.orientation),this.cameraRotationManager=new G0(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(j0,this.gl.VERTEX_SHADER),i=this.createShader(Y0,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 ec=class{constructor(e){this.subscription=new ce,this.videoState=new me(Ae.STOPPED),this.elementSize$=new T(void 0),this.textTracksManager=new Pt,this.droppedFramesManager=new Xs,this.videoTracks$=new T([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Ul,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===ie.Requested&&(o==null?void 0:o.to)!==m.PAUSED&&a!==Ae.STOPPED&&n!==m.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===m.STOPPED){a!==Ae.STOPPED&&(this.videoState.startTransitionTo(Ae.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Ae.STOPPED),L(this.params.desiredState.playbackState,m.STOPPED,!0));return}switch(a){case Ae.STOPPED:this.videoState.startTransitionTo(Ae.READY),this.prepare();return;case Ae.READY:n===m.PAUSED?(this.videoState.setState(Ae.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED)):n===m.PLAYING?(this.videoState.startTransitionTo(Ae.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===m.READY&&L(this.params.desiredState.playbackState,m.READY);return;case Ae.PLAYING:n===m.PAUSED?(this.videoState.startTransitionTo(Ae.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(o==null?void 0:o.to)===m.PLAYING&&L(this.params.desiredState.playbackState,m.PLAYING);return;case Ae.PAUSED:n===m.PLAYING?(this.videoState.startTransitionTo(Ae.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(o==null?void 0:o.to)===m.PAUSED&&L(this.params.desiredState.playbackState,m.PAUSED);return;default:return z(a)}}},this.init3DScene=t=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Zl(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=Ft(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(Qe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new V0({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=Vt(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(P(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(oe(I),_e()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(fi(this.video,t.isLooped,r)),this.subscription.add(Nt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ii(this.video,t.playbackRate,i.playbackRateState$,r)),a(Us(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(Ae.PLAYING),L(t.playbackState,m.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(Ae.PAUSED),L(t.playbackState,m.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===Ae.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d===pt.MANIFEST_READY){const c=[];this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();D(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((g,y)=>y.bitrate-g.bitrate),p=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=Ky(g);y&&this.audioTracks.push({track:y,representation:g})}for(const g of p){const y=Qy(g);if(y){c.push({track:y,representation:g});const v=!this.params.tuning.isAudioDisabled&&Jy(f,p,g);v&&this.audioRepresentations.set(g.id,v)}}this.videoTracks$.next(c);for(const g of S){const y=Xy(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();D(b),this.player.initRepresentations(b.id,(l=this.audioRepresentations.get(b.id))===null||l===void 0?void 0:l.id)}else d===pt.REPRESENTATIOS_READY&&(this.videoState.setState(Ae.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(G(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,V(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!==pt.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(Fe.VIDEO,c.id).catch(n);const f=this.audioRepresentations.get(c.id);f&&this.player.switchRepresentation(Fe.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(ye(),P(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(P(({to:d})=>d===m.READY),ye());this.subscription.add(G(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===m.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(G(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===m.READY)));const u=G(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,We(["init"])).pipe(lt(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=tt(this.video.buffered,this.video.currentTime*1e3),f=u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=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=Ni(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:p,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(){si(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(Ae.PAUSED),L(this.params.desiredState.playbackState,m.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),Ut(this.video)}},z0=class extends ec{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 Ue;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(Ue||(Ue={}));var Lt;(function(s){s[s.ActiveLowLatency=0]="ActiveLowLatency",s[s.LiveWithTargetOffset=1]="LiveWithTargetOffset",s[s.LiveForwardBuffering=2]="LiveForwardBuffering",s[s.None=3]="None"})(Lt||(Lt={}));var Ur;(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"})(Ur||(Ur={}));var gt;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(gt||(gt={}));var te;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(te||(te={}));var os;(function(s){s.MP4="mp4",s.WEBM="webm"})(os||(os={}));var Vr;(function(s){s[s.RECTANGULAR=0]="RECTANGULAR",s[s.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",s[s.CUBEMAP=2]="CUBEMAP",s[s.MESH=3]="MESH"})(Vr||(Vr={}));var we;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(we||(we={}));var on,dn;let tc=!1;try{tc=jr().browser===Xn.Safari&&parseInt((dn=(on=navigator.userAgent.match(/Version\/(\d+)/))===null||on===void 0?void 0:on[1])!==null&&dn!==void 0?dn:"",10)<16}catch(s){console.error(s)}class q0{constructor(e){this.bufferFull$=new O,this.error$=new O,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)}append(e,t){return J(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(i=>{const r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return J(this,void 0,void 0,function*(){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()})})}abort(e){return J(this,void 0,void 0,function*(){return new Promise(t=>{let i;tc&&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 Tt{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 ic extends Tt{}class W0 extends Tt{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 Q0 extends Tt{parseChildrenBoxes(){return pi(this.content)}}class K0 extends Tt{parseChildrenBoxes(){return pi(this.content)}}class J0 extends Tt{constructor(e){super(e),this.data=this.content}}class ri extends Tt{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class X0 extends ri{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 Z0 extends Tt{parseChildrenBoxes(){return pi(this.content)}}class eT extends Tt{parseChildrenBoxes(){return pi(this.content)}}var Di;(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"})(Di||(Di={}));class tT extends ri{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=Di.MONOSCOPIC;break;case 1:this.stereoMode=Di.TOP_BOTTOM;break;case 2:this.stereoMode=Di.LEFT_RIGHT;break;case 3:this.stereoMode=Di.STEREO_CUSTOM;break;case 4:this.stereoMode=Di.RIGHT_LEFT;break}this.cursor+=1}}class iT extends ri{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class sT extends ri{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class rT extends Tt{parseChildrenBoxes(){return pi(this.content)}}class aT extends ri{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 nT extends Tt{parseChildrenBoxes(){return pi(this.content)}}class oT extends Tt{parseChildrenBoxes(){return pi(this.content)}}class dT extends ri{constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class uT extends Tt{parseChildrenBoxes(){return pi(this.content)}}class lT extends ri{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 cT extends ri{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 hT extends ri{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 fT={ftyp:W0,moov:Q0,moof:K0,mdat:J0,sidx:X0,trak:Z0,mdia:rT,mfhd:dT,tkhd:aT,traf:uT,tfhd:lT,tfdt:cT,trun:hT,minf:nT,sv3d:eT,st3d:tT,prhd:iT,proj:oT,equi:sT,unknown:ic};class pT{createBox(e,t){const i=fT[e];return i?new i(t):new ic(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return na.createBox(i,new DataView(e.buffer,e.byteOffset))}}const na=new pT;function Rs(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:na.createBox(e,new DataView(s.buffer,r-7))}r++}return null}function Wn(s,e){const t=[];let i=s.byteOffset;for(;i<s.buffer.byteLength;){const r=Rs(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 pi(s){const e=[];let t=0;for(;t<s.byteLength;){const i=na.createFromView(new DataView(s.buffer,s.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const mT=new TextDecoder("ascii"),vT=s=>mT.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",gT=s=>{const e=na.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:te.NONE,time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},ST=s=>{const e=Wn(s,"mdat"),t=Wn(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)},bT=(s,e)=>{const t=Wn(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},yT=s=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Vr.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(Rs(s,"sv3d")){e.is3dVideo=!0;const i=Rs(s,"st3d");i&&(e.stereoMode=i.stereoMode);const r=Rs(s,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const a=Rs(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},TT={validateData:vT,parseInit:yT,getIndexRange:()=>{},parseSegments:gT,parseFeedableSegmentChunk:ST,getSegmentEndTime:bT};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 U;(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"})(U||(U={}));const ru={[k.EBML]:{type:U.Master},[k.EBMLVersion]:{type:U.UnsignedInteger},[k.EBMLReadVersion]:{type:U.UnsignedInteger},[k.EBMLMaxIDLength]:{type:U.UnsignedInteger},[k.EBMLMaxSizeLength]:{type:U.UnsignedInteger},[k.DocType]:{type:U.String},[k.DocTypeVersion]:{type:U.UnsignedInteger},[k.DocTypeReadVersion]:{type:U.UnsignedInteger},[k.Void]:{type:U.Binary},[k.Segment]:{type:U.Master},[k.SeekHead]:{type:U.Master},[k.Seek]:{type:U.Master},[k.SeekID]:{type:U.Binary},[k.SeekPosition]:{type:U.UnsignedInteger},[k.Info]:{type:U.Master},[k.TimestampScale]:{type:U.UnsignedInteger},[k.Duration]:{type:U.Float},[k.Tracks]:{type:U.Master},[k.TrackEntry]:{type:U.Master},[k.Video]:{type:U.Master},[k.Projection]:{type:U.Master},[k.ProjectionType]:{type:U.UnsignedInteger},[k.ProjectionPrivate]:{type:U.Master},[k.Chapters]:{type:U.Master},[k.Cluster]:{type:U.Master},[k.Timestamp]:{type:U.UnsignedInteger},[k.SilentTracks]:{type:U.Master},[k.SilentTrackNumber]:{type:U.UnsignedInteger},[k.Position]:{type:U.UnsignedInteger},[k.PrevSize]:{type:U.UnsignedInteger},[k.SimpleBlock]:{type:U.Binary},[k.BlockGroup]:{type:U.Master},[k.EncryptedBlock]:{type:U.Binary},[k.Attachments]:{type:U.Master},[k.Tags]:{type:U.Master},[k.Cues]:{type:U.Master},[k.CuePoint]:{type:U.Master},[k.CueTime]:{type:U.UnsignedInteger},[k.CueTrackPositions]:{type:U.Master},[k.CueTrack]:{type:U.UnsignedInteger},[k.CueClusterPosition]:{type:U.UnsignedInteger},[k.CueRelativePosition]:{type:U.UnsignedInteger},[k.CueDuration]:{type:U.UnsignedInteger},[k.CueBlockNumber]:{type:U.UnsignedInteger},[k.CueCodecState]:{type:U.UnsignedInteger},[k.CueReference]:{type:U.Master},[k.CueRefTime]:{type:U.UnsignedInteger}},sc=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=Hr(s,t),r=i in ru,a=r?ru[i].type:U.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=Hr(u),c=d*Math.pow(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}},Hr=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*Math.pow(2,16)+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*Math.pow(2,32)+s.getUint32(1);case 6:return s.getUint16(0)*Math.pow(2,32)+s.getUint32(2);case 7:{const t=s.getUint8(0)*Math.pow(2,48)+s.getUint16(1)*Math.pow(2,32)+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ot=(s,e)=>{switch(e){case U.SignedInteger:return s.getInt8(0);case U.UnsignedInteger:return Hr(s);case U.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case U.String:return new TextDecoder("ascii").decode(s);case U.UTF8:return new TextDecoder("utf-8").decode(s);case U.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case U.Master:return s;case U.Binary:return s;default:z(e)}},ds=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=sc(i);if(!e(r))return;r.type===U.Master&&ds(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},ET=s=>{if(s.getUint32(0)!==k.EBML)return!1;let e,t,i;const r=sc(s);return ds(r.value,({tag:a,type:n,value:o})=>(a===k.EBMLReadVersion?e=Ot(o,n):a===k.DocType?t=Ot(o,n):a===k.DocTypeReadVersion&&(i=Ot(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},rc=[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],$T=[k.Timestamp,k.SilentTracks,k.SilentTrackNumber,k.Position,k.PrevSize,k.SimpleBlock,k.BlockGroup,k.EncryptedBlock],AT=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,d,l=!1;const c=0;return ds(s,({tag:h,type:f,value:p,valueSize:S})=>{if(h===k.SeekID){const b=Ot(p,f);d=Hr(b)}else h!==k.SeekPosition&&(d=void 0);return h===k.Segment?(e=p.byteOffset,t=p.byteOffset+S):h===k.Info?a=!0:h===k.SeekHead?n=!0:h===k.TimestampScale?i=Ot(p,f):h===k.Duration?r=Ot(p,f):h===k.SeekPosition&&d===k.Cues?u=Ot(p,f):h===k.Tracks?ds(p,({tag:b,type:g,value:y})=>b===k.ProjectionType?(l=Ot(y,g)===1,!1):!0):a&&n&&rc.includes(h)&&(o=!0),!o}),D(e,"Failed to parse webm Segment start"),D(t,"Failed to parse webm Segment end"),D(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:Vr.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},wT=s=>{if(W(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},kT=(s,e)=>{let t=!1,i=!1;const r=o=>I(o.time)&&I(o.position),a=[];let n;return ds(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=Ot(d,u));break;case k.CueTrackPositions:break;case k.CueClusterPosition:n&&(n.position=Ot(d,u));break;default:t&&rc.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:te.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}}})},_T=s=>{let e=0,t=!1;try{ds(s,i=>i.tag===k.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):$T.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},PT={validateData:ET,parseInit:AT,getIndexRange:wT,parseSegments:kT,parseFeedableSegmentChunk:_T},au=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},Qi=(s,e)=>{let t=s;t=Fr(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=Fr(t,n,(o,u)=>W(a)?o:W(u)?a:a.padStart(parseInt(u,10),"0"))}return t},DT=(s,e)=>{var t,i,r,a,n,o,u,d,l,c,h,f,p,S,b,g,y,v,E,$,x,j,K,H,q,Q,B,M,X,N,C,Y,se,ve,Ee,Le,Je,ht,re;const Xe=new DOMParser().parseFromString(s,"application/xml"),xe={video:[],audio:[],text:[]},Pe=Xe.children[0],Gt=Pe.getElementsByTagName("Period")[0],jt=Gt.children,ai=Pe.getAttribute("type")==="dynamic",Yt=Pe.getAttribute("availabilityStartTime"),Fi=Yt?new Date(Yt).getTime():void 0;let Ge;const ps=Pe.getAttribute("mediaPresentationDuration"),ms=Gt.getAttribute("duration"),mi=Pe.getElementsByTagName("vk:Attrs")[0],vs=mi==null?void 0:mi.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(ps)Ge=au(ps);else if(ms){const $e=au(ms);I($e)&&(Ge=$e)}else vs&&(Ge=parseInt(vs,10));let oa=0;const vi=(i=(t=Pe.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],da=vi.includes(Ur.WEBM_AS_IN_FFMPEG)||vi.includes(Ur.WEBM_AS_IN_SPEC)?os.WEBM:os.MP4;for(const $e of jt){const zt=$e.getAttribute("mimeType"),ua=$e.getAttribute("codecs"),gs=(r=$e.getAttribute("contentType"))!==null&&r!==void 0?r:zt==null?void 0:zt.split("/")[0],la=(n=(a=$e.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],Ss=$e.querySelectorAll("Representation"),ca=$e.querySelector("SegmentTemplate");if(gs===Ue.TEXT){for(const Z of Ss){const Ce=Z.getAttribute("id")||"",qt=$e.getAttribute("lang"),it=(d=(u=(o=Z.querySelector("BaseURL"))===null||o===void 0?void 0:o.textContent)===null||u===void 0?void 0:u.trim())!==null&&d!==void 0?d:"",gi=new URL(it,e).toString(),Si=Ce.includes("_auto");xe[Ue.TEXT].push({id:Ce,lang:qt,isAuto:Si,kind:Ue.TEXT,url:gi})}continue}for(const Z of Ss){const Ce=(l=Z.getAttribute("mimeType"))!==null&&l!==void 0?l:zt,qt=(h=(c=Z.getAttribute("codecs"))!==null&&c!==void 0?c:ua)!==null&&h!==void 0?h:"",it=(p=(f=Z.getAttribute("contentType"))!==null&&f!==void 0?f:Ce==null?void 0:Ce.split("/")[0])!==null&&p!==void 0?p:gs,gi=(b=(S=$e.getAttribute("profiles"))===null||S===void 0?void 0:S.split(","))!==null&&b!==void 0?b:[],Si=parseInt((g=Z.getAttribute("width"))!==null&&g!==void 0?g:"",10),bs=parseInt((y=Z.getAttribute("height"))!==null&&y!==void 0?y:"",10),ys=parseInt((v=Z.getAttribute("bandwidth"))!==null&&v!==void 0?v:"",10)/1e3,Ts=(E=Z.getAttribute("frameRate"))!==null&&E!==void 0?E:"",ha=($=Z.getAttribute("quality"))!==null&&$!==void 0?$:void 0,fa=Ts?sa(Ts):void 0,pa=(x=Z.getAttribute("id"))!==null&&x!==void 0?x:(oa++).toString(10),ma=it==="video"?`${bs}p`:it==="audio"?`${ys}Kbps`:qt,va=`${pa}@${ma}`,ga=(H=(K=(j=Z.querySelector("BaseURL"))===null||j===void 0?void 0:j.textContent)===null||K===void 0?void 0:K.trim())!==null&&H!==void 0?H:"",Es=new URL(ga,e).toString(),Sa=[...vi,...la,...gi];let bi;const ba=Z.querySelector("SegmentBase"),je=(q=Z.querySelector("SegmentTemplate"))!==null&&q!==void 0?q:ca;if(ba){const st=(B=(Q=Z.querySelector("SegmentBase Initialization"))===null||Q===void 0?void 0:Q.getAttribute("range"))!==null&&B!==void 0?B:"",[rt,Ti]=st.split("-").map(at=>parseInt(at,10)),Ze={from:rt,to:Ti},Et=(M=Z.querySelector("SegmentBase"))===null||M===void 0?void 0:M.getAttribute("indexRange"),[Ei,Wt]=Et?Et.split("-").map(at=>parseInt(at,10)):[],$t=Et?{from:Ei,to:Wt}:void 0;bi={type:gt.BYTE_RANGE,url:Es,initRange:Ze,indexRange:$t}}else if(je){const st={representationId:(X=Z.getAttribute("id"))!==null&&X!==void 0?X:void 0,bandwidth:(N=Z.getAttribute("bandwidth"))!==null&&N!==void 0?N:void 0},rt=parseInt((C=je.getAttribute("timescale"))!==null&&C!==void 0?C:"",10),Ti=(Y=je.getAttribute("initialization"))!==null&&Y!==void 0?Y:"",Ze=je.getAttribute("media"),Et=(ve=parseInt((se=je.getAttribute("startNumber"))!==null&&se!==void 0?se:"",10))!==null&&ve!==void 0?ve:1,Ei=Qi(Ti,st);if(!Ze)throw new ReferenceError("No media attribute in SegmentTemplate");const Wt=(Ee=je.querySelectorAll("SegmentTimeline S"))!==null&&Ee!==void 0?Ee:[],$t=[];let at=0,$i="",nt=0;if(Wt.length){let ot=Et,De=0;for(const At of Wt){const et=parseInt((Le=At.getAttribute("d"))!==null&&Le!==void 0?Le:"",10),Dt=parseInt((Je=At.getAttribute("r"))!==null&&Je!==void 0?Je:"",10)||0,Qt=parseInt((ht=At.getAttribute("t"))!==null&&ht!==void 0?ht:"",10);De=Number.isFinite(Qt)?Qt:De;const $s=et/rt*1e3,Ui=De/rt*1e3;for(let Vi=0;Vi<Dt+1;Vi++){const cc=Qi(Ze,Object.assign(Object.assign({},st),{segmentNumber:ot.toString(10),segmentTime:(De+Vi*et).toString(10)})),Do=(Ui!=null?Ui:0)+Vi*$s,hc=Do+$s;ot++,$t.push({time:{from:Do,to:hc},url:cc})}De+=(Dt+1)*et,at+=(Dt+1)*$s}nt=De/rt*1e3,$i=Qi(Ze,Object.assign(Object.assign({},st),{segmentNumber:ot.toString(10),segmentTime:De.toString(10)}))}else if(I(Ge)){const De=parseInt((re=je.getAttribute("duration"))!==null&&re!==void 0?re:"",10)/rt*1e3,At=Math.ceil(Ge/De);let et=0;for(let Dt=1;Dt<At;Dt++){const Qt=Qi(Ze,Object.assign(Object.assign({},st),{segmentNumber:Dt.toString(10),segmentTime:et.toString(10)}));$t.push({time:{from:et,to:et+De},url:Qt}),et+=De}nt=et,$i=Qi(Ze,Object.assign(Object.assign({},st),{segmentNumber:At.toString(10),segmentTime:et.toString(10)}))}const Ai={time:{from:nt,to:1/0},url:$i};bi={type:gt.TEMPLATE,baseUrl:Es,segmentTemplateUrl:Ze,initUrl:Ei,totalSegmentsDurationMs:at,segments:$t,nextSegmentBeyondManifest:Ai,timescale:rt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!it||!Ce)continue;const yi={video:Ue.VIDEO,audio:Ue.AUDIO,text:Ue.TEXT}[it];yi&&xe[yi].push({id:va,kind:yi,segmentReference:bi,profiles:Sa,duration:Ge,bitrate:ys,mime:Ce,codecs:qt,width:Si,height:bs,fps:fa,quality:ha})}}return{dynamic:ai,liveAvailabilityStartTime:Fi,duration:Ge,container:da,representations:xe}},IT=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a})=>{var n;const o=(n=a?hs(a):void 0)!==null&&n!==void 0?n:ci({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r}},RT=({id:s,bitrate:e})=>({id:s,bitrate:e}),LT=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=Oe(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:Oe(s,-1)},xT=({id:s,lang:e,url:t,isAuto:i})=>({id:s,url:t,isAuto:i,type:"internal",language:e}),nu=s=>"size"in s,qi=s=>s.type===gt.TEMPLATE,Qn=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);class ou{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 O,this.gaps=[],this.subscription=new ce,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new St,this.destroyAbortController=new St,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.liveInitialAdditionalOffset=0,this.isSeekingLive=!1,this.index=0,this.startWith=fe(this.destroyAbortController.signal,function(c){return pe(this,arguments,function*(){const h=this.representations.get(c);D(h,`Cannot find representation ${c}`),this.playingRepresentationId=c,this.downloadingRepresentationId=c,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${h.mime}; codecs="${h.codecs}"`),this.sourceBufferTaskQueue=new q0(this.sourceBuffer),this.subscription.add(V(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(V(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,Mr(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 yield _(this.loadInit(h,"high",!0));const f=this.initData.get(h.id),p=this.segments.get(h.id),S=this.parsedInitData.get(h.id);if(D(f,"No init buffer for starting representation"),D(p,"No segments for starting representation"),!(f instanceof ArrayBuffer))return yield _(void 0);this.searchGaps(p,h),yield yield _(this.sourceBufferTaskQueue.append(f,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(S)})}.bind(this)),this.switchTo=fe(this.destroyAbortController.signal,function(c){return pe(this,arguments,function*(){if(c===this.downloadingRepresentationId||c===this.switchingToRepresentationId)return yield _(void 0);this.switchingToRepresentationId=c;const h=this.representations.get(c);D(h,`No such representation ${c}`);let f=this.segments.get(c),p=this.initData.get(c);if(W(p)||W(f)?yield yield _(this.loadInit(h,"high",!1)):p instanceof Promise&&(yield yield _(p)),f=this.segments.get(c),D(f,"No segments for starting representation"),p=this.initData.get(c),!p||!(p instanceof ArrayBuffer)||!this.sourceBuffer)return yield _(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=c,this.abort(),yield yield _(this.sourceBufferTaskQueue.append(p,this.downloadAbortController.signal));const S=this.getCurrentPosition();I(S)&&(this.isLive||(f.forEach(b=>b.status=te.NONE),this.pruneBuffer(S,1/0,!0)),this.maintain(S))})}.bind(this)),this.seekLive=fe(this.destroyAbortController.signal,function(c){var h;return pe(this,arguments,function*(){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!c)return yield _(void 0);for(const y of this.representations.keys()){const v=c.find(x=>x.id===y);v&&this.representations.set(y,v);const E=this.representations.get(y);if(!E||!qi(E.segmentReference))return yield _(void 0);const $=this.getActualLiveStartingSegments(E.segmentReference);this.segments.set(E.id,$)}const f=(h=this.switchingToRepresentationId)!==null&&h!==void 0?h:this.downloadingRepresentationId,p=this.representations.get(f);D(p);const S=this.segments.get(f);D(S,"No segments for starting representation");const b=this.initData.get(f);if(D(b,"No init buffer for starting representation"),!(b instanceof ArrayBuffer))return yield _(void 0);const g=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),g&&(yield yield _(this.sourceBufferTaskQueue.remove(g.from*1e3,g.to*1e3,this.destroyAbortController.signal))),this.searchGaps(S,p),yield 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 os.MP4:this.containerParser=TT;break;case os.WEBM:this.containerParser=PT;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 St,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(W(e)||W(this.downloadingRepresentationId)||W(this.playingRepresentationId)||W(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(D(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=tt(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)&&Mr(this.sourceBuffer.buffered)>=this.bufferLimit){const d=tt(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=Oe(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===te.FED&&!o.length&&tt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const u=Oe(i,-1);u&&u.status===te.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;I(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||!qi(n.segmentReference))return;const o=n.segmentReference.segments.map(c=>Object.assign(Object.assign({},c),{status:te.NONE,size:void 0})),u=(i=this.segments.get(n.id))!==null&&i!==void 0?i:[],d=(a=(r=Oe(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(!qi(r))return;const a=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),n=Qi(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:te.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}},p)=>{const S=h<=i&&f>=i,b=h>i||S||p===0&&i===0,g=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&h<=i+g||f<=i+g;return(c===te.NONE||c===te.PARTIALLY_EJECTED&&b&&y&&this.sourceBuffer&&!as(this.sourceBuffer.buffered,i))&&b&&y});if(r===-1)return[];if(t!==gt.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===te.NONE||h.status===te.PARTIALLY_EJECTED)u.push(h);else break}return u}loadSegments(e,t,i="auto"){return J(this,void 0,void 0,function*(){t.segmentReference.type===gt.TEMPLATE?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return J(this,void 0,void 0,function*(){e.status=te.DOWNLOADING;const r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);const{range:a,url:n,signal:o,onProgress:u,onProgressTasks:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield fe(o,function(){return pe(this,arguments,function*(){const l=Ls(this.failedDownloads,this.tuning.downloadBackoff);yield yield _(new Promise(c=>setTimeout(c,l)))})}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{const l=yield this.fetcher.fetch(n,{range:a,signal:o,onProgress:u,priority: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?yield Promise.all(d):yield this.sourceBufferTaskQueue.append(c,o),r.segment.status=te.DOWNLOADED,this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(l){if(!Qn(l))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(l)}})}loadByteRangeSegments(e,t,i="auto"){return J(this,void 0,void 0,function*(){if(!e.length)return;for(const u of e)u.status=te.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(yield fe(n,function(){return pe(this,arguments,function*(){const u=Ls(this.failedDownloads,this.tuning.downloadBackoff);yield yield _(new Promise(d=>setTimeout(d,u)))})}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:i}),this.failedDownloads=0}catch(u){if(!Qn(u))return;this.abortActiveSegments(e),this.onSegmentDownloadError(u)}})}prepareByteRangeFetchSegmentParams(e,t){if(qi(t.segmentReference))throw new Error("Representation is not byte range type");const i=t.segmentReference.url,r={from:Oe(e,0).byte.from,to:Oe(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(!qi(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&&I(r)&&(i=tt((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})}onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:a}){return J(this,void 0,void 0,function*(){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const o of this.activeSegments){const{segment:u}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=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=te.PARTIALLY_FED,o.feedingBytes+=l.byteLength,yield 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===gt.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===te.DOWNLOADING&&g&&y){c.status=te.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=te.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=te.FED,nu(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===te.FED&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status=te.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===te.PARTIALLY_FED||e.status===te.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=te.NONE),e.status=te.PARTIALLY_EJECTED):e.status=te.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=Br(()=>Ks(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return J(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?fe(this.destroyAbortController.signal,function(){return pe(this,arguments,function*(){const o=Ls(this.failedDownloads,this.tuning.downloadBackoff);yield yield _(new Promise(u=>setTimeout(u,o)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(o=>J(this,void 0,void 0,function*(){if(!o)return;const{init:u,dataView:d,segments:l}=o,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c);let h=l;this.isLive&&qi(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})}pruneBuffer(e,t,i=!1){return J(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||W(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=nu(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===te.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===te.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===te.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===te.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=Br(()=>{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(W(this.sourceBuffer)||W(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!==te.FED&&a!==te.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=te.PARTIALLY_EJECTED:r.status=te.NONE)}}}var es;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(es||(es={}));class CT{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 St,this.subscription=new ce,this.fetchManifest=fe(this.abortAllController.signal,function(r){return pe(this,arguments,function*(){let a=r;this.requestQuic&&(a=li(a));const n=yield yield _(Ci(a,{signal:this.abortAllController.signal}).catch(_s));return n?(this.onHeadersReceived(n.headers),yield _(n.text())):yield _(null)})}.bind(this)),this.fetch=fe(this.abortAllController.signal,function(r,{rangeMethod:a=this.compatibilityMode?es.HEADER:es.PARAM,range:n,onProgress:o,priority:u="auto",signal:d,measureThroughput:l=!0,isLowLatency:c=!1}={}){var h,f;return pe(this,arguments,function*(){let p=r;const S=new Headers;if(n)switch(a){case es.HEADER:{S.append("Range",`bytes=${n.from}-${n.to}`);break}case es.PARAM:{const M=new URL(p,location.href);M.searchParams.append("bytes",`${n.from}-${n.to}`),p=M.toString();break}default:z(a)}this.requestQuic&&(p=li(p));let b=this.abortAllController.signal,g;if(d){const M=new St;if(g=G(V(this.abortAllController.signal,"abort"),V(d,"abort")).subscribe(()=>{try{M.abort()}catch(X){_s(X)}}),this.abortAllController.signal.aborted||d.aborted)try{M.abort()}catch(X){_s(X)}b=M.signal}const y=he(),v=yield yield _(Ci(p,{priority:u,headers:S,signal:b}).catch(_s)),E=he();if(!v)return g==null||g.unsubscribe(),yield _(null);if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(E-y),!v.ok||!v.body)return g==null||g.unsubscribe(),yield _(Promise.reject(new Error(`Fetch error ${v.status}: ${v.statusText}`)));if(this.onHeadersReceived(v.headers),!o&&!l)return g==null||g.unsubscribe(),yield _(v.arrayBuffer());const[$,x]=v.body.tee(),j=$.getReader();l&&((f=this.throughputEstimator)===null||f===void 0||f.trackStream(x,c));let K=0,H=new Uint8Array(0),q=!1;const Q=M=>{g==null||g.unsubscribe(),q=!0,_s(M)},B=fe(b,function({done:M,value:X}){return pe(this,arguments,function*(){if(K===0&&this.lastRequestFirstBytes$.next(he()-y),b.aborted)return g==null||g.unsubscribe(),yield _(void 0);if(!M&&X){const N=new Uint8Array(H.length+X.length);N.set(H),N.set(X,H.length),H=N,K+=X.byteLength,o==null||o(new DataView(H.buffer),K),yield yield _(j==null?void 0:j.read().then(B,Q))}})}.bind(this));return yield yield _(j==null?void 0:j.read().then(B,Q)),g==null||g.unsubscribe(),yield _(q?null:H.buffer)})}.bind(this)),this.fetchByteRangeRepresentation=fe(this.abortAllController.signal,function(r,a,n){var o;return pe(this,arguments,function*(){if(r.type!==gt.BYTE_RANGE)return yield _(null);const{from:u,to:d}=r.initRange;let l=u,c=d,h=!1,f,p;r.indexRange&&(f=r.indexRange.from,p=r.indexRange.to,h=d+1===f,h&&(l=Math.min(f,u),c=Math.max(p,d))),l=Math.min(l,0);const S=yield yield _(this.fetch(r.url,{range:{from:l,to:c},priority:n,measureThroughput:!1}));if(!S)return yield _(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 yield _(this.fetch(r.url,{range:y,priority:n,measureThroughput:!1}));if(!$)return yield _(null);v=new DataView($)}const E=a.parseSegments(v,g,y);return yield _({init:g,dataView:new DataView(S),segments:E})})}.bind(this)),this.fetchTemplateRepresentation=fe(this.abortAllController.signal,function(r,a){return pe(this,arguments,function*(){if(r.type!==gt.TEMPLATE)return yield _(null);const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield yield _(this.fetch(n,{priority:a,measureThroughput:!1}));if(!o)return yield _(null);const u=r.segments.map(d=>Object.assign(Object.assign({},d),{status:te.NONE,size:void 0}));return yield _({init:null,segments:u,dataView:new DataView(o)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=wo(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){var r,a;return J(this,void 0,void 0,function*(){const{type:n}=e;switch(n){case gt.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case gt.TEMPLATE:return(a=yield this.fetchTemplateRepresentation(e,i))!==null&&a!==void 0?a:null;default:z(n)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const _s=s=>{if(!Qn(s))throw s},Kn=1e3,Gr=(s,e,t)=>t*e+(1-t)*s,ac=(s,e)=>s.reduce((t,i)=>t+i,0)/e,OT=(s,e,t,i)=>{let r=0,a=t;const n=ac(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 Po{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 xt(`raw_${i}`),this.smoothedSeries$=new xt(`smoothed_${i}`),this.reportedSeries$=new xt(`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+=Math.pow(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)&&(W(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 BT extends Po{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Gr(this.slow,e,this.params.emaAlphaSlow),this.fast=Gr(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class MT extends Po{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=ac(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Gr(this.emaSmoothed,e,this.params.emaAlpha);const i=OT(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class NT extends Po{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?Gr(this.smoothed,e,this.params.emaAlpha):e}}class Jn{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new BT({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new MT({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 NT(Object.assign({initial:e,label:"liveEdgeDelay"},t))}}const FT=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)},du=["timeupdate","progress","play","seeked","stalled","waiting"];var mt;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(mt||(mt={}));let UT=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new ce,this.representationSubscription=new ce,this.state$=new me(mt.NONE),this.currentVideoRepresentation$=new T(void 0),this.currentVideoRepresentationInit$=new T(void 0),this.error$=new O,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 O,this.gapWatchdogStarted=!1,this.destroyController=new St,this.initManifest=fe(this.destroyController.signal,function(t,i,r){var a;return pe(this,arguments,function*(){this.element=t,this.manifestUrlString=qe(i,r,Te.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(mt.MANIFEST_READY),this.manifest=yield yield _(this.updateManifest()),!((a=this.manifest)===null||a===void 0)&&a.representations.video.length?this.state$.setState(mt.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:R.PARSER,message:"No playable video representations"})})}.bind(this)),this.updateManifest=fe(this.destroyController.signal,function(){var t;return pe(this,arguments,function*(){const i=yield 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 yield _(null);let r;try{r=DT(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 yield _(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===Ue.TEXT)};return r.dynamic&&this.isLive$.getValue()!==r.dynamic&&(this.isLive$.next(r.dynamic),this.liveDuration$.getValue()!==r.duration&&this.liveDuration$.next(-1*((t=r.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==r.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(r.liveAvailabilityStartTime)),yield _(Object.assign(Object.assign({},r),{representations:Li(Object.entries(r.representations).map(([n,o])=>[n,o.filter(a)]))}))})}.bind(this)),this.initRepresentations=fe(this.destroyController.signal,function(t,i){return pe(this,arguments,function*(){D(this.manifest),D(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(mt.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 ou(Ue.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],I(i)&&(this.audioBufferManager=new ou(Ue.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(Ri(Kn).subscribe(o=>{var u;if(!((u=this.element)===null||u===void 0)&&u.paused){const d=Lr(this.manifestUrlString,Te.DASH_CMAF_OFFSET_P);this.manifestUrlString=qe(this.manifestUrlString,d+Kn,Te.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(G(...du.map(o=>V(this.element,o))).pipe(P(o=>this.element?tt(this.element.buffered,this.element.currentTime*1e3):0),ye(),oe(o=>!!o),Bs(o=>{this.waitingEventInterval&&(window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=void 0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(oe(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),FT(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(p=>{var S,b;return(b=(S=p.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(Be({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).subscribe(({liveLoadBufferLength:u,bufferLength:d})=>J(this,void 0,void 0,function*(){if(D(this.element),this.isUpdatingLive)return;const l=this.element.playbackRate,c=Lr(this.manifestUrlString,Te.DASH_CMAF_OFFSET_P),h=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,f=Math.min(h,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*l),p=this.tuning.dashCmafLive.normalizedActualBufferOffset*l,S=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*l,b=this.isActiveLowLatency?d:u;let g=Lt.None;if(this.isActiveLowLatency?g=Lt.ActiveLowLatency:b<f+S&&b>=f?g=Lt.LiveWithTargetOffset:c!==0&&b<f&&(g=Lt.LiveForwardBuffering),isFinite(u)&&(o=u>o?u:o),g===Lt.LiveForwardBuffering||g===Lt.LiveWithTargetOffset){const y=o-(f+p),v=this.normolizeLiveOffset(Math.trunc(c+y/l)),E=Math.abs(v-c);let $;!u||E<=this.tuning.dashCmafLive.offsetCalculationError?$=c:v>0&&E>this.tuning.dashCmafLive.offsetCalculationError?$=v:$=0,this.manifestUrlString=qe(this.manifestUrlString,$,Te.DASH_CMAF_OFFSET_P)}g!==Lt.None&&g!==Lt.ActiveLowLatency&&(o=0,this.updateLive())})))}const a=G(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(P(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=G(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(P(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.representationSubscription.add(G(this.forceEnded$,Be({allBuffersFull:a,someBufferEnded:n}).pipe(oe(({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(G(...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 yield _(new Promise(o=>{var u;return(u=this.source)===null||u===void 0?void 0:u.addEventListener("sourceopen",o)}))),I(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&I(i)?yield yield _(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)])):yield yield _(this.videoBufferManager.startWith(t)),this.state$.setState(mt.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=Ri(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 CT({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Jn.getLiveEstimatedDelaySmoothedValue(0,Object.assign({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){var t,i,r,a;return J(this,void 0,void 0,function*(){D(this.element);const n=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&n===0,this.liveLastSeekOffset=n,this.isJumpGapAfterSeekLive=!0,this.manifestUrlString=qe(this.manifestUrlString,n,Te.DASH_CMAF_OFFSET_P),this.manifest=yield this.updateManifest(),this.manifest&&(yield(t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((i=this.manifest)===null||i===void 0?void 0:i.representations.video),yield(r=this.audioBufferManager)===null||r===void 0?void 0:r.seekLive((a=this.manifest)===null||a===void 0?void 0:a.representations.audio))})}initBuffer(){D(this.element),this.state$.setState(mt.RUNNING),this.subscription.add(G(...du.map(e=>V(this.element,e)),V(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:R.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(V(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(V(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&as(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()}switchRepresentation(e,t){return J(this,void 0,void 0,function*(){const i={[Ue.VIDEO]:this.videoBufferManager,[Ue.AUDIO]:this.audioBufferManager,[Ue.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)})}seek(e,t){var i,r,a,n,o;D(this.element),D(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),as(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(mt.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}waitingEventCallback(){return J(this,void 0,void 0,function*(){try{if(!this.element)return;this.isLive$.getValue()?yield 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}updateLive(){var e;return J(this,void 0,void 0,function*(){this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)===null||e===void 0||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);const t=this.element.currentTime*1e3,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 nc{constructor(e){this.subscription=new ce,this.videoState=new me(we.STOPPED),this.elementSize$=new T(void 0),this.textTracksManager=new Pt,this.droppedFramesManager=new Xs,this.videoTracks$=new T([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Ul,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===ie.Requested&&(o==null?void 0:o.to)!==m.PAUSED&&a!==we.STOPPED&&n!==m.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===m.STOPPED){a!==we.STOPPED&&(this.videoState.startTransitionTo(we.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(we.STOPPED),L(this.params.desiredState.playbackState,m.STOPPED,!0));return}switch(a){case we.STOPPED:this.videoState.startTransitionTo(we.READY),this.prepare();return;case we.READY:n===m.PAUSED?(this.videoState.setState(we.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED)):n===m.PLAYING?(this.videoState.startTransitionTo(we.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===m.READY&&L(this.params.desiredState.playbackState,m.READY);return;case we.PLAYING:n===m.PAUSED?(this.videoState.startTransitionTo(we.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(o==null?void 0:o.to)===m.PLAYING&&L(this.params.desiredState.playbackState,m.PLAYING);return;case we.PAUSED:n===m.PLAYING?(this.videoState.startTransitionTo(we.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)===m.PAUSED&&L(this.params.desiredState.playbackState,m.PAUSED);return;default:return z(a)}}},this.init3DScene=t=>{var i,r,a;if(this.scene3D)return;this.scene3D=new Zl(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=Ft(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(Qe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new UT({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=Vt(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(P(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(oe(I),_e()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(fi(this.video,t.isLooped,r)),this.subscription.add(Nt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ii(this.video,t.playbackRate,i.playbackRateState$,r)),a(Us(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(we.PLAYING),L(t.playbackState,m.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(we.PAUSED),L(t.playbackState,m.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===we.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d===mt.MANIFEST_READY){const c=[];this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();D(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((g,y)=>y.bitrate-g.bitrate),p=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=RT(g);y&&this.audioTracks.push({track:y,representation:g})}for(const g of p){const y=IT(g);if(y){c.push({track:y,representation:g});const v=!this.params.tuning.isAudioDisabled&<(f,p,g);v&&this.audioRepresentations.set(g.id,v)}}this.videoTracks$.next(c);for(const g of S){const y=xT(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();D(b),this.player.initRepresentations(b.id,(l=this.audioRepresentations.get(b.id))===null||l===void 0?void 0:l.id)}else d===mt.REPRESENTATIOS_READY&&(this.videoState.setState(we.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(G(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,V(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!==mt.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(Ue.VIDEO,c.id).catch(n);const f=this.audioRepresentations.get(c.id);f&&this.player.switchRepresentation(Ue.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(ye(),P(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(P(({to:d})=>d===m.READY),ye());this.subscription.add(G(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===m.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(G(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===m.READY)));const u=G(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,We(["init"])).pipe(lt(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=tt(this.video.buffered,this.video.currentTime*1e3),f=u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=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=Ni(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:p,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(){si(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(we.PAUSED),L(this.params.desiredState.playbackState,m.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),Ut(this.video)}}class VT extends nc{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 HT=class extends ec{constructor(e){super(e),this.liveOffset=new Js}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(Be({interval:Ri(qn),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()===Ae.PLAYING){const n=e.position$.getValue()+(r-1);e.position$.next(n),(a=this.liveOffset)===null||a===void 0||a.resetTo(-n*1e3)}})).add(Be({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(P(({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===m.PAUSED&&i===Ae.PAUSED,a=-e,n=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)===null||o===void 0||o.resetTo(n,r)})}};class GT extends nc{constructor(e){super(e),this.liveOffset=new Js}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(Be({interval:Ri(Kn),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()===we.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(Be({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(P(({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===m.PAUSED&&i===we.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 Rt={};var le;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(le||(le={}));const Ps=(s,e)=>new Yr(t=>{const i=(r,a)=>t.next(a);return s.on(e,i),()=>s.off(e,i)});class jT{constructor(e){this.subscription=new ce,this.videoState=new me(le.INITIALIZING),this.textTracksManager=new Pt,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!==le.INITIALIZING)switch((r==null?void 0:r.to)!==m.PAUSED&&a.state===ie.Requested&&this.seek(a.position),i){case m.STOPPED:switch(t){case le.STOPPED:break;case le.READY:case le.PLAYING:case le.PAUSED:this.stop();break;default:z(t)}break;case m.READY:switch(t){case le.STOPPED:this.prepare();break;case le.READY:case le.PLAYING:case le.PAUSED:break;default:z(t)}break;case m.PLAYING:switch(t){case le.PLAYING:break;case le.STOPPED:this.prepare();break;case le.READY:case le.PAUSED:this.playIfAllowed();break;default:z(t)}break;case m.PAUSED:switch(t){case le.PAUSED:break;case le.STOPPED:this.prepare();break;case le.READY:this.videoState.setState(le.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED);break;case le.PLAYING:this.pause();break;default:z(t)}break;default:z(i)}},this.video=Ft(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(Qe(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),Ut(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);Ks(import("hls.js").then(r=>{e||(Rt.Hls=r.default,Rt.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){D(Rt.Hls,"hls.js not loaded"),this.hls=new Rt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(le.STOPPED)}subscribe(){D(Rt.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=Vt(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(fi(this.video,e.isLooped,i)),this.subscription.add(Nt(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ii(this.video,e.playbackRate,r.playbackRateState$,i)),this.subscription.add(Ps(this.hls,Rt.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(le.PLAYING),L(e.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(le.PAUSED),L(e.playbackState,m.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())===null||d===void 0?void 0:d.to)===le.READY&&this.videoState.setState(le.READY),this.videoState.getState()===le.PLAYING&&this.playIfAllowed()},i)),a(Ps(this.hls,Rt.Events.MANIFEST_PARSED).pipe(P(({levels:d})=>d.reduce((l,c)=>{var h,f;const p=c.name||c.height.toString(10),{width:S,height:b}=c,g=(f=hs((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:ci({width:S,height:b});if(!g)return l;const y=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,v={id:p.toString(),quality:g,bitrate:c.bitrate/1e3,size:{width:S,height:b},fps:y};return this.trackLevels.set(p,{track:v,level:c}),l.push(v),l},[]))),t.availableVideoTracks$),a(Ps(this.hls,Rt.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||"",p=c.lang,S="internal";l.push({id:h,url:f,language:p,type:S})}e.internalTextTracks.startTransitionTo(l)}}),a(Ps(this.hls,Rt.Events.LEVEL_LOADING).pipe(P(({url:d})=>Qe(d))),t.hostname$),this.subscription.add(kt(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=Ps(this.hls,Rt.Events.LEVEL_SWITCHED).pipe(P(({level:d})=>n(this.hls.levels[d])));o.pipe(oe(I)).subscribe(t.currentVideoTrack$,i),this.subscription.add(kt(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),d=>{var l;if(W(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,p=this.hls.levels[f];!p||c.bitrate>p.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=G(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,We(["init"])).pipe(lt(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(le.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return J(this,void 0,void 0,function*(){this.videoState.startTransitionTo(le.PLAYING),(yield si(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(le.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(le.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(le.STOPPED),L(this.params.desiredState.playbackState,m.STOPPED,!0)}}const uu="X-Playback-Duration";var lu=s=>J(void 0,void 0,void 0,function*(){var e;const t=yield Ci(s),i=yield 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(uu)?parseInt(t.headers.get(uu),10):void 0});const YT=s=>{let e=null;if(s.QUALITY&&(e=hs(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=ci({width:t,height:i})}return e!=null?e:null},oc=(s,e=s)=>J(void 0,void 0,void 0,function*(){var t,i;const n=(yield(yield Ci(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=Li(c[1].split(",").map(E=>E.split("="))),p=(t=f.QUALITY)!==null&&t!==void 0?t:`stream-${f.BANDWIDTH}`,S=YT(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(x=>parseInt(x,10));E&&$&&(y={width:E,height:$})}const v=new URL(n[++d],e).toString();S&&o.push({id:p,quality:S,url:v,bandwidth:b,size:y,fps:g})}if(h){const f=Li(h[1].split(",").map(g=>g.split("=")).map(([g,y])=>[g,y.replace(/^"|"$/g,"")])),p=(i=f.URI)===null||i===void 0?void 0:i.replace(/playlist$/,"subtitles.vtt"),S=f.LANGUAGE,b=f.NAME;p&&S&&u.push({type:"internal",id:S,label:b,language:S,url:p,isAuto:!1})}}}return{qualityManifests:o,textTracks:u}});var ge;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(ge||(ge={}));class zT{constructor(e){var t;this.subscription=new ce,this.videoState=new me(ge.STOPPED),this.textTracksManager=new Pt,this.manifests$=new T([]),this.liveOffset=new Js,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===m.STOPPED){r!==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),L(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(r===ge.STOPPED){this.videoState.startTransitionTo(ge.READY),this.prepare();return}if(o||u||d){const h=this.videoState.getState();this.videoState.setState(ge.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),d&&this.params.output.autoVideoTrackLimits$.next(d.to),c.state===ie.None&&this.params.desiredState.seekState.setState({state:ie.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==m.PAUSED&&c.state===ie.Requested){this.videoState.startTransitionTo(ge.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case ge.READY:a===m.READY?L(this.params.desiredState.playbackState,m.READY):a===m.PAUSED?(this.videoState.setState(ge.PAUSED),this.liveOffset.pause(),L(this.params.desiredState.playbackState,m.PAUSED)):a===m.PLAYING&&(this.videoState.startTransitionTo(ge.PLAYING),this.playIfAllowed());return;case ge.PLAYING:a===m.PAUSED?(this.videoState.startTransitionTo(ge.PAUSED),this.liveOffset.pause(),this.video.pause()):(n==null?void 0:n.to)===m.PLAYING&&L(this.params.desiredState.playbackState,m.PLAYING);return;case ge.PAUSED:if(a===m.PLAYING)if(this.videoState.startTransitionTo(ge.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)===m.PAUSED&&(L(this.params.desiredState.playbackState,m.PAUSED),this.liveOffset.pause());return;case ge.CHANGING_MANIFEST:break;default:return z(r)}},this.params=e,this.video=Ft(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ft.INVARIANT,url:this.params.source.url},oc(qe(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(Qe(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=Vt(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(Nt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ii(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),L(t.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ge.PAUSED),L(t.playbackState,m.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)),this.subscription.add(this.maxSeekBackTime$.pipe(ye(),P(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&&I(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(Qe(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===ge.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===ie.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(Be({startTime:this.manifestStartTime$.pipe(oe(I)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(P(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=G(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,We(["init"])).pipe(lt(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ut(this.video)}prepare(){var e,t;const i=this.selectManifest();if(W(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?Te.DASH_CMAF_OFFSET_P:Te.OFFSET_P,u=qe(n.toString(),this.liveOffset.getTotalOffset(),o);this.video.setAttribute("src",u),this.video.load(),lu(u).then(d=>{var l;if(!W(d))this.maxSeekBackTime$.next(d);else{const c=(l=this.params.source.maxSeekBackTime)!==null&&l!==void 0?l:this.maxSeekBackTime$.getValue();if(W(c)||!isFinite(c))try{Ci(u).then(h=>h.text()).then(h=>{var f;const p=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))===null||f===void 0?void 0:f[1];if(p){const S=new URL(p,u).toString();lu(S).then(b=>{W(b)||this.maxSeekBackTime$.next(b)})}})}catch(h){}}})}playIfAllowed(){si(this.video).then(e=>{e||(this.videoState.setState(ge.PAUSED),this.liveOffset.pause(),L(this.params.desiredState.playbackState,m.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 be;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(be||(be={}));class qT{constructor(e){this.subscription=new ce,this.videoState=new me(be.STOPPED),this.textTracksManager=new Pt,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===m.STOPPED){i!==be.STOPPED&&(this.videoState.startTransitionTo(be.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(be.STOPPED),L(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(i===be.STOPPED){this.videoState.startTransitionTo(be.READY),this.prepare();return}if(n||o||u){const c=this.videoState.getState();this.videoState.setState(be.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),l.state===ie.None&&this.params.desiredState.seekState.setState({state:ie.Requested,position:h*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==m.PAUSED&&l.state===ie.Requested&&this.seek(l.position),i){case be.READY:r===m.READY?L(this.params.desiredState.playbackState,m.READY):r===m.PAUSED?(this.videoState.setState(be.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED)):r===m.PLAYING&&(this.videoState.startTransitionTo(be.PLAYING),this.playIfAllowed());return;case be.PLAYING:r===m.PAUSED?(this.videoState.startTransitionTo(be.PAUSED),this.video.pause()):(a==null?void 0:a.to)===m.PLAYING&&L(this.params.desiredState.playbackState,m.PLAYING);return;case be.PAUSED:r===m.PLAYING?(this.videoState.startTransitionTo(be.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===m.PAUSED&&L(this.params.desiredState.playbackState,m.PAUSED);return;case be.CHANGING_MANIFEST:break;default:return z(i)}},this.params=e,this.video=Ft(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:ft.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(Qe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),oc(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=Vt(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(fi(this.video,t.isLooped,i)),this.subscription.add(Nt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ii(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(be.PLAYING),L(t.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(be.PAUSED),L(t.playbackState,m.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===be.READY&&this.videoState.setState(be.READY),this.videoState.getState()===be.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&&I(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(Qe(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===be.CHANGING_MANIFEST&&this.videoState.setState(u.to),o.state===ie.Requested&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(P(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)),!bc()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:o}=this.video;this.subscription.add(G(V(o,"addtrack"),V(o,"removetrack"),V(o,"change"),We(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}const n=G(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,We(["init"])).pipe(lt(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ut(this.video)}prepare(){var e,t;const i=this.selectManifest();if(W(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(){si(this.video).then(e=>{e||(this.videoState.setState(be.PAUSED),L(this.params.desiredState.playbackState,m.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 ke;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(ke||(ke={}));class WT{constructor(e){this.subscription=new ce,this.videoState=new me(ke.STOPPED),this.trackUrls={},this.textTracksManager=new Pt,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===m.STOPPED){a!==ke.STOPPED&&(this.videoState.startTransitionTo(ke.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(ke.STOPPED),L(this.params.desiredState.playbackState,m.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!==ke.READY&&!l){this.handleQualityLimitTransition(d.to.max);return}if(a===ke.STOPPED){this.videoState.startTransitionTo(ke.READY),this.prepare();return}if(l){const{currentTime:h}=this.video;this.prepare(),c.state===ie.None&&this.params.desiredState.seekState.setState({state:ie.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)!==m.PAUSED&&c.state===ie.Requested&&this.seek(c.position),a){case ke.READY:n===m.READY?L(this.params.desiredState.playbackState,m.READY):n===m.PAUSED?(this.videoState.setState(ke.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED)):n===m.PLAYING&&(this.videoState.startTransitionTo(ke.PLAYING),this.playIfAllowed());return;case ke.PLAYING:n===m.PAUSED?(this.videoState.startTransitionTo(ke.PAUSED),this.video.pause()):(o==null?void 0:o.to)===m.PLAYING&&L(this.params.desiredState.playbackState,m.PLAYING);return;case ke.PAUSED:n===m.PLAYING?(this.videoState.startTransitionTo(ke.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===m.PAUSED&&L(this.params.desiredState.playbackState,m.PAUSED);return;default:return z(a)}},this.params=e,this.video=Ft(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=Vt(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(fi(this.video,t.isLooped,i)),this.subscription.add(Nt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ii(this.video,t.playbackRate,r.playbackRateState$,i)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ke.PLAYING),L(t.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ke.PAUSED),L(t.playbackState,m.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ke.READY&&this.videoState.setState(ke.READY);const u=this.params.desiredState.videoTrack.getTransition();u&&I(u.to)&&(this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to.id].track)),this.videoState.getState()===ke.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const n=G(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,We(["init"])).pipe(lt(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),Ut(this.video)}prepare(){var e;const t=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id;D(t,"MpegProvider: track is not selected");let{url:i}=this.trackUrls[t];D(i,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(i=li(i)),this.video.setAttribute("src",i),this.video.load(),this.params.output.hostname$.next(Qe(i))}playIfAllowed(){si(this.video).then(e=>{e||(this.videoState.setState(ke.PAUSED),L(this.params.desiredState.playbackState,m.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=>!Ii(c.track.quality)&&Tu(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&&An(l.quality,u.quality)&&(n=u),!n){const c=Object.values(this.trackUrls).filter(f=>!Ii(f.track.quality)&&ts(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=Ni(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 cu=["stun:videostun.mycdn.me:80"],QT=1e3,KT=3,un=()=>null;class JT{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=un,this.externalStopCallback=un,this.externalErrorCallback=un,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}}handleUpdateMessage(e){return J(this,void 0,void 0,function*(){try{const t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return J(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:cu}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return J(this,void 0,void 0,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return J(this,void 0,void 0,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:R.WTF,message:e.message})}onPeerConnectionStream(e){return J(this,void 0,void 0,function*(){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return J(this,void 0,void 0,function*(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=yield this.peerConnection.createOffer(e),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),QT)}normalizeOptions(e={}){const t={stunServerList:cu,maxRetryNumber:KT,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var Se;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Se||(Se={}));class XT{constructor(e){this.videoState=new me(Se.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===m.STOPPED){t!==Se.STOPPED&&(this.videoState.startTransitionTo(Se.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Se.STOPPED),L(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===Se.STOPPED){this.videoState.startTransitionTo(Se.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case Se.READY:i===m.PAUSED?(this.videoState.setState(Se.PAUSED),L(this.params.desiredState.playbackState,m.PAUSED)):i===m.PLAYING&&(this.videoState.startTransitionTo(Se.PLAYING),this.playIfAllowed());return;case Se.PLAYING:i===m.PAUSED?(this.videoState.startTransitionTo(Se.PAUSED),this.video.pause()):(r==null?void 0:r.to)===m.PLAYING&&L(this.params.desiredState.playbackState,m.PLAYING);return;case Se.PAUSED:i===m.PLAYING?(this.videoState.startTransitionTo(Se.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===m.PAUSED&&L(this.params.desiredState.playbackState,m.PAUSED);return;default:return z(t)}},this.subscription=new ce,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ft(e.container),this.liveStreamClient=new JT(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),Ut(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})};G(this.videoState.stateChangeStarted$.pipe(P(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(P(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const r=Vt(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)===Se.READY&&this.videoState.setState(Se.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(Se.PAUSED)},i)).add(r.playing$.subscribe(()=>{this.videoState.setState(Se.PLAYING)},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Nt(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case Se.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(m.STOPPED);break;case Se.READY:break;case Se.PAUSED:t.playbackState.setState(m.PAUSED);break;case Se.PLAYING:t.playbackState.setState(m.PLAYING);break;default:return z(n.to)}},i)).add(G(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,We(["init"])).pipe(lt(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(Qe(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:ft.INVARIANT}),this.video.srcObject=e,L(this.params.desiredState.playbackState,m.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(Se.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:R.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){si(this.video).then(e=>{e||(this.videoState.setState(Se.PAUSED),L(this.params.desiredState.playbackState,m.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 hu{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 ln,cn,hn,fn,pn,mn,vn,gn,gr,Sn,Sr,bn,br,yn,yr,Tn,Tr,En,Er,$n;const dc=jr().device===yc.Android,di=document.createElement("video"),ZT='video/mp4; codecs="avc1.42000a,mp4a.40.2"',eE='video/mp4; codecs="hev1.1.6.L93.B0"',uc='video/webm; codecs="vp09.00.10.08"',lc='video/webm; codecs="av01.0.00M.08"',tE='audio/mp4; codecs="mp4a.40.2"',iE='audio/webm; codecs="opus"',Me={mms:!!(window.ManagedMediaSource&&(!((cn=(ln=window.ManagedSourceBuffer)===null||ln===void 0?void 0:ln.prototype)===null||cn===void 0)&&cn.appendBuffer)),mse:!!(window.MediaSource&&window.MediaStreamTrack&&(!((fn=(hn=window.SourceBuffer)===null||hn===void 0?void 0:hn.prototype)===null||fn===void 0)&&fn.appendBuffer)),hls:!!(!((pn=di.canPlayType)===null||pn===void 0)&&pn.call(di,"application/x-mpegurl")||!((mn=di.canPlayType)===null||mn===void 0)&&mn.call(di,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},dt={mp4:!!(!((vn=di.canPlayType)===null||vn===void 0)&&vn.call(di,"video/mp4")),webm:!!(!((gn=di.canPlayType)===null||gn===void 0)&&gn.call(di,"video/webm")),cmaf:!0},Bt={h264:!!(!((Sn=(gr=window.MediaSource||window.ManagedMediaSource)===null||gr===void 0?void 0:gr.isTypeSupported)===null||Sn===void 0)&&Sn.call(gr,ZT)),h265:!!(!((bn=(Sr=window.MediaSource||window.ManagedMediaSource)===null||Sr===void 0?void 0:Sr.isTypeSupported)===null||bn===void 0)&&bn.call(Sr,eE)),vp9:!!(!((yn=(br=window.MediaSource||window.ManagedMediaSource)===null||br===void 0?void 0:br.isTypeSupported)===null||yn===void 0)&&yn.call(br,uc)),av1:!!(!((Tn=(yr=window.MediaSource||window.ManagedMediaSource)===null||yr===void 0?void 0:yr.isTypeSupported)===null||Tn===void 0)&&Tn.call(yr,lc)),aac:!!(!((En=(Tr=window.MediaSource||window.ManagedMediaSource)===null||Tr===void 0?void 0:Tr.isTypeSupported)===null||En===void 0)&&En.call(Tr,tE)),opus:!!(!(($n=(Er=window.MediaSource||window.ManagedMediaSource)===null||Er===void 0?void 0:Er.isTypeSupported)===null||$n===void 0)&&$n.call(Er,iE))},Wi=(Bt.h264||Bt.h265)&&Bt.aac;var oi;(function(s){s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient"})(oi||(oi={}));var Xt;(function(s){s.DASH="dash",s.HLS="hls",s.MPEG="mpeg"})(Xt||(Xt={}));let ki;const sE=()=>J(void 0,void 0,void 0,function*(){if(!window.navigator.mediaCapabilities)return;const s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},s),{video:Object.assign(Object.assign({},s.video),{contentType:lc})})),window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},s),{video:Object.assign(Object.assign({},s.video),{contentType:uc})}))]);ki={[A.DASH_WEBM_AV1]:e,[A.DASH_WEBM]:t}});try{sE()}catch(s){console.error(s)}const Vs=Me.hls&&dt.mp4,rE=()=>Object.keys(Bt).filter(s=>Bt[s]),aE=(s,e=!1,t=!1)=>s.filter(i=>{switch(i){case A.DASH:return Me.mse&&dt.mp4&&Wi;case A.DASH_SEP:return(Me.mse||Me.mms&&t)&&dt.mp4&&Wi;case A.DASH_WEBM:return(Me.mse||Me.mms&&t)&&dt.webm&&Bt.vp9&&Bt.opus;case A.DASH_WEBM_AV1:return(Me.mse||Me.mms&&t)&&dt.webm&&Bt.av1&&Bt.opus;case A.DASH_LIVE:return Me.mse&&dt.mp4&&Wi;case A.DASH_LIVE_CMAF:return(Me.mse||Me.mms&&t)&&dt.mp4&&Wi&&dt.cmaf;case A.DASH_ONDEMAND:return(Me.mse||Me.mms&&t)&&dt.mp4&&Wi;case A.HLS:case A.HLS_ONDEMAND:return Vs||e&&Me.mse&&dt.mp4&&Wi;case A.HLS_LIVE:case A.HLS_LIVE_CMAF:return Vs;case A.MPEG:return dt.mp4;case A.DASH_LIVE_WEBM:return!1;case A.WEB_RTC_LIVE:return Me.webrtc&&Me.ws&&Bt.h264&&(dt.mp4||dt.webm);default:return z(i)}}),Ds=s=>{const e=A.DASH_WEBM,t=A.DASH_WEBM_AV1;switch(s){case oi.VP9:return[e,t];case oi.AV1:return[t,e];case oi.NONE:return[];case oi.SMOOTH:return ki?ki[t].smooth?[t,e]:ki[e].smooth?[e,t]:[t,e]:[e,t];case oi.POWER_EFFICIENT:return ki?ki[t].powerEfficient?[t,e]:ki[e].powerEfficient?[e,t]:[t,e]:[e,t];default:z(s)}return[e,t]},nE=({webmCodec:s,androidPreferredFormat:e})=>{if(dc)switch(e){case Xt.MPEG:return[A.MPEG,...Ds(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND];case Xt.HLS:return[A.HLS,A.HLS_ONDEMAND,...Ds(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.MPEG];case Xt.DASH:return[...Ds(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG]}return Vs?[...Ds(s),A.DASH_SEP,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG,A.DASH]:[...Ds(s),A.DASH_SEP,A.DASH,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG]},oE=({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(dc)switch(s){case Xt.DASH:{o=a;break}case Xt.HLS:case Xt.MPEG:{o=n;break}}else Vs?o=n:o=a;return t?[A.WEB_RTC_LIVE,...o]:[...o,A.WEB_RTC_LIVE]},fu=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 dE=s=>new Yr(e=>{const t=new ce,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(P(({from:d,to:l})=>`${d}-${l}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(P(({type:d})=>d!==void 0)),n=new O;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 uE={cacheDuration:12e4},lE={chunkDuration:5e3,maxParallelRequests:5};class cE{constructor(e){this.current$=new T({type:void 0}),this.providerError$=new O,this.noAvailableProvidersError$=new O,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 O,warning$:new O,willSeekEvent$:new O,seekedEvent$:new O,loopedEvent$:new O,endedEvent$:new O,firstBytesEvent$:new O,firstFrameEvent$:new O,canplay$:new O,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 ce,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=aE([...oE(this.params.tuning),...nE(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>I(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 hu(a);const n=[...fu(!0),...fu(!1)];this.chromecastFormatsIterator=new hu(n.filter(o=>I(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(W(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!==ie.None;if(this.params.desiredState.seekState.setState({state:ie.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 Ye.SCREEN:return this.createScreenProvider(t);case Ye.CHROMECAST:return this.createChromecastProvider(t);default:return z(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:r}=this.params,a=this.providerOutput,n={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case A.DASH:{const o=this.applyFailoverHost(t[e]);return D(o),new cy(Object.assign(Object.assign({},n),{source:o,config:uE}))}case A.DASH_SEP:case A.DASH_WEBM:case A.DASH_WEBM_AV1:case A.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return D(o),this.params.tuning.useDashJs?new zd(Object.assign(Object.assign({},n),{source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}})):this.params.tuning.useNewDashVkProvider?new VT(Object.assign(Object.assign({},n),{source:o})):new z0(Object.assign(Object.assign({},n),{source:o}))}case A.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return D(o),this.params.tuning.useDashJsCMAF?new zd(Object.assign(Object.assign({},n),{source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}})):this.params.tuning.useNewDashVkProvider?new GT(Object.assign(Object.assign({},n),{source:o})):new HT(Object.assign(Object.assign({},n),{source:o}))}case A.HLS:case A.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return D(o),Vs||!this.params.tuning.useHlsJs?new qT(Object.assign(Object.assign({},n),{source:o})):new jT(Object.assign(Object.assign({},n),{source:o}))}case A.HLS_LIVE:case A.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return D(o),new zT(Object.assign(Object.assign({},n),{source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case A.MPEG:{const o=this.applyFailoverHost(t[e]);return D(o),new WT(Object.assign(Object.assign({},n),{source:o}))}case A.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return D(o),new ny(Object.assign(Object.assign({},n),{source:o,config:Object.assign(Object.assign({},lE),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case A.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return D(o),new XT({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 D(o),new gb({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()?Ye.CHROMECAST:Ye.SCREEN}chooseFormat(e){switch(e){case Ye.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case Ye.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return z(e)}}skipFormat(e){switch(e){case Ye.SCREEN:return this.screenFormatsIterator.next();case Ye.CHROMECAST:return this.chromecastFormatsIterator.next();default:return z(e)}}handleNoFormatsError(e){switch(e){case Ye.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case Ye.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return 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 Object.assign(Object.assign({},e),{url:i(e.url)})}return Li(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){const e=new ce;let t=!1,i=0;const r=he();return e.add(G(this.providerOutput.error$,dE({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(P(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(oe(({to:n})=>n===m.PLAYING),_e()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{const n=this.current$.getValue().destination;if(n===Ye.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(Ye.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=he()-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:Ye.SCREEN)}})),e}}const hE=5e3,pu="one_video_throughput",mu="one_video_rtt",Zt=window.navigator.connection,vu=()=>{const s=Zt==null?void 0:Zt.downlink;if(I(s)&&s!==10)return s*1e3},gu=()=>{const s=Zt==null?void 0:Zt.rtt;if(I(s)&&s!==3e3)return s},Su=(s,e,t)=>{const i=t*8,r=i/s;return i/(r+e)};class Os{constructor(e){var t,i;this.subscription=new ce,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=Os.load(pu)||(e.useBrowserEstimation?vu():void 0)||hE,a=(i=(t=Os.load(mu))!==null&&t!==void 0?t:e.useBrowserEstimation?gu():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new T(r),this.rtt$=new T(a),this.rttAdjustedThroughput$=new T(Su(r,a,e.rttPenaltyRequestSize)),this.throughput=Jn.getSmoothedValue(r,-1,e),this.rtt=Jn.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const u=vu();u&&this.throughput.next(u);const d=gu();I(d)&&this.rtt.next(d)};Zt&&"onchange"in Zt&&this.subscription.add(V(Zt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{ya.set(pu,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{ya.set(mu,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Be({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(P(({throughput:n,rtt:o})=>Su(n,o,e.rttPenaltyRequestSize)),oe(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=he();const r=new ce;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(V(e,"progress").pipe(_e()).subscribe(a=>{t=a.loaded,i=he()}));break;case 1:case 0:r.add(V(e,"loadstart").subscribe(()=>{t=0,i=he()}));break}r.add(V(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=he(),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=he(),n=0,o=he();const u=l=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${l}`).catch(()=>{})},d=({done:l,value:c})=>J(this,void 0,void 0,function*(){if(l)!t&&this.addRawSpeed(r,he()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){if(he()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=c.byteLength;else{const f=o-a;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,a=he()}o=he()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&he()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,he()-o,this.concurrentDownloads.size),n=0,o=he());yield 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(Os.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=ya.get(e);if(I(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const bu={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:ft.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:oi.VP9,androidPreferredFormat:Xt.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}},fE=s=>{var e;return Object.assign(Object.assign({},Tc(s,bu)),{configName:[...(e=s.configName)!==null&&e!==void 0?e:[],...bu.configName]})};var yu=({seekState:s,position$:e})=>G(s.stateChangeEnded$.pipe(P(({to:t})=>{var i;return t.state===ie.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),oe(I)),e.pipe(oe(()=>s.getState().state===ie.None))),pE=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return D(e,`Wrong container or containerId {${s.container}}`),e};const mE=(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(oe(r=>r.length>0),_e()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};class jE{constructor(e={configName:[]}){if(this.subscription=new ce,this.logger=new Ec,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.desiredState={playbackState:new me(m.STOPPED),seekState:new me({state:ie.None}),volume:new me({volume:1,muted:!1}),videoTrack:new me(void 0),autoVideoTrackSwitching:new me(!0),autoVideoTrackLimits:new me({}),isLooped:new me(!1),playbackRate:new me(1),externalTextTracks:new me([]),internalTextTracks:new me([]),currentTextTrack:new me(void 0),textTrackCuesSettings:new me({}),cameraOrientation:new me({x:0,y:0})},this.info={playbackState$:new T(m.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(ni.NONE),chromecastState$:new T(Ne.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 O,ready$:new O,started$:new O,playing$:new O,paused$:new O,stopped$:new O,willStart$:new O,willResume$:new O,willPause$:new O,willStop$:new O,willDestruct$:new O,watchCoverageRecord$:new O,watchCoverageLive$:new O,managedError$:new O,fatalError$:new O,ended$:new O,looped$:new O,seeked$:new O,willSeek$:new O,firstBytes$:new O,firstFrame$:new O,canplay$:new O,log$:new O},this.experimental={element$:new T(void 0),tuningConfigName$:new T([]),enableDebugTelemetry$:new T(!1),dumpTelemetry:Ub},this.initLogs(),this.tuning=fE(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new wc({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Os(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 p=typeof f;return["number","string","boolean"].includes(p)?f:f===null?null:`<${p}>`})),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=pE(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new cE({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()===m.STOPPED&&e.startTransitionTo(m.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==m.PLAYING&&t.startTransitionTo(m.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?V(document,"visibilitychange").pipe(_e()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==m.PAUSED&&e.startTransitionTo(m.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==m.STOPPED&&e.startTransitionTo(m.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:ie.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()===Ne.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()===Ne.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){D(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(oe(i=>i.length>0),_e()).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;D(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=>Object.assign({type:"external"},t))),this}selectTextTrack(e){var t;return mE(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(W(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===ie.None?void 0:t.position;return I(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(G(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(P(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(P(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(P(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(P(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(P(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(oe(({from:e})=>e===m.STOPPED),_e()).subscribe(()=>{this.initedAt=he(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case m.READY:this.events.ready$.next();break;case m.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case m.PAUSED:this.events.paused$.next();break;case m.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case m.PAUSED:this.events.willPause$.next();break;case m.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case m.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===ie.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},n),{state:ie.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===ie.Applying&&(this.desiredState.seekState.setState({state:ie.None}),this.events.seeked$.next())})).add(e.current$.pipe(P(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(P(n=>n.destination),ye()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(P(n=>n.map(({quality:o})=>o).sort((o,u)=>Ii(o)?1:Ii(u)?-1:ts(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(ye()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(ye()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(ye()).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(P(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(Be({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:yu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(P(({isLive:n,position:o,isLowLatency:u})=>{const d=u?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return n&&Math.abs(o)<d/1e3}),ye(),Bs(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(Be({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(P(({isLive:n,position:o,duration:u})=>n&&(Math.abs(u)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),ye(),Bs(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(P(n=>n.muted),ye()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(P(n=>n.volume),ye()).subscribe(this.info.volume$)).add(yu({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(G(e.providerOutput.endedEvent$.pipe(ss(!0)),e.providerOutput.seekedEvent$.pipe(ss(!1))).pipe(ye()).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(P(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(_e(),P(n=>n!=null?n:he()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(_e(),P(()=>he()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(_e(),P(()=>he()-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(oe(({to:n})=>n===m.PLAYING),_e()).subscribe(()=>i.next(!1)));let r=0;const a=G(e.providerOutput.isBuffering$,t,i).pipe(P(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),ye());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(G(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(G(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===Ne.CONNECTED?l=ni.SECOND_SCREEN:u?n?l=ni.PIP:o?l=ni.FULLSCREEN:l=ni.INLINE:l=ni.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(P(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 ce;this.subscription.add(t),this.subscription.add(e.current$.pipe(ye((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(oe(i=>i.length>0),_e()).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=Ni(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(G(this.desiredState.videoTrack.stateChangeStarted$.pipe(P(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(P(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(P(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(P(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(P(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(P(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(P(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(P(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(P(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;D(this.providerContainer),D(t),Fb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Nb(i)),this.providerContainer.current$.subscribe(({type:i})=>fr("provider",i)),t.duration$.subscribe(i=>fr("duration",i)),t.availableVideoTracks$.pipe(oe(i=>!!i.length),_e()).subscribe(i=>fr("tracks",i)),this.events.fatalError$.subscribe(new xt("fatalError")),this.events.managedError$.subscribe(new xt("managedError")),t.position$.subscribe(new xt("position")),t.currentVideoTrack$.pipe(P(i=>i==null?void 0:i.quality)).subscribe(new xt("quality")),this.info.currentBuffer$.subscribe(new xt("buffer")),t.isBuffering$.subscribe(new xt("isBuffering"))].forEach(i=>this.subscription.add(i)),fr("codecs",rE())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},i=()=>J(this,void 0,void 0,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:R.DOM,message:String(r)})})});this.subscription.add(G(V(document,"visibilitychange"),V(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===m.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 YE=`@vkontakte/videoplayer-core@${$c}`;export{Ne as ChromecastState,Ms as HttpConnectionType,WE as Observable,m as PlaybackState,jE as Player,YE as SDK_VERSION,QE as Subject,KE as Subscription,ni as Surface,$c as VERSION,JE as ValueSubject,A as VideoFormat,XE as VideoQuality};
|