@vkontakte/videoplayer-core 2.0.82 → 2.0.83-dev.65744ed.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 +64 -6
- package/es2015.esm.js +64 -6
- package/es2018.cjs.js +64 -6
- package/es2018.esm.js +64 -6
- package/esnext.cjs.js +64 -6
- package/esnext.esm.js +64 -6
- package/evergreen.esm.js +64 -6
- package/index.d.ts +9 -0
- package/package.json +1 -1
package/es2018.esm.js
CHANGED
|
@@ -1,8 +1,66 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.83-dev.65744ed.0
|
|
3
|
+
* Wed, 19 Apr 2023 17:05:19 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-83/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{ValueSubject as y,Subject as C,Subscription as ie,isNonNullable as _,ErrorCategory as L,isNullable as J,fromEvent as M,assertNever as O,merge as x,tap as Or,map as $,observableFrom as ke,filterChanged as pe,assertNonNullable as P,debounce as xe,timeout as Co,combine as Ze,once as ge,mapTo as $t,filter as q,now as he,Observable as ui,abortable as Be,getExponentialDelay as Nr,interval as xo,Logger as Oo}from"@vkontakte/videoplayer-shared/es2018.esm.js";import{Observable as sv,Subject as rv,Subscription as av,ValueSubject as nv}from"@vkontakte/videoplayer-shared/es2018.esm.js";import No from"lodash/debounce.js";const Bo="2.0.82",Mo="es2018.esm.js";var m;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(m||(m={}));var b;(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_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"})(b||(b={}));var _e;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(_e||(_e={}));var Ee;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})(Ee||(Ee={}));var oi;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(oi||(oi={}));var V;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(V||(V={}));var Uo=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 Fo{constructor(e){var t;this.connection$=new y(void 0),this.castState$=new y(Ee.NOT_AVAILABLE),this.errorEvent$=new C,this.realCastState$=new y(Ee.NOT_AVAILABLE),this.subscription=new ie,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const i="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${i}`}),e.isDisabled||!i)return;const r=_((t=window.chrome)===null||t===void 0?void 0:t.cast),a=Boolean(window.__onGCastApiAvailable);r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||Uo("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:L.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())===null||i===void 0?void 0:i.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||a===void 0||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){_(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();J(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();J(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(M(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 O(r.sessionState)}})).add(x(M(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Or(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),$(r=>r.castState)),ke([i.getCastState()])).pipe(pe(),$(Vo),Or(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===Ee.CONNECTED,o=_(this.connection$.getValue());if(n&&!o){const u=i.getCurrentSession();P(u);const d=u.getCastDevice(),l=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(J(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===Ee.CONNECTED?_(this.connection$.getValue())?Ee.CONNECTED:Ee.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:L.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const Vo=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return Ee.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return Ee.AVAILABLE;case cast.framework.CastState.CONNECTING:return Ee.CONNECTING;case cast.framework.CastState.CONNECTED:return Ee.CONNECTED;default:return O(s)}};var Br=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},it=function(s){try{return!!s()}catch(e){return!0}},Ho=it,Xi=!Ho(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),on=Xi,dn=Function.prototype,Ks=dn.call,Go=on&&dn.bind.bind(Ks,Ks),st=on?Go:function(s){return function(){return Ks.apply(s,arguments)}},un=st,Yo=un({}.toString),qo=un("".slice),Zi=function(s){return qo(Yo(s),8,-1)},jo=st,zo=it,Wo=Zi,hs=Object,Qo=jo("".split),Jo=zo(function(){return!hs("z").propertyIsEnumerable(0)})?function(s){return Wo(s)=="String"?Qo(s,""):hs(s)}:hs,es=function(s){return s==null},Ko=es,Xo=TypeError,ur=function(s){if(Ko(s))throw Xo("Can't call method on "+s);return s},Zo=Jo,ed=ur,li=function(s){return Zo(ed(s))},td=function(){},Ht={},yi=function(s){return s&&s.Math==Math&&s},je=yi(typeof globalThis=="object"&&globalThis)||yi(typeof window=="object"&&window)||yi(typeof self=="object"&&self)||yi(typeof Br=="object"&&Br)||function(){return this}()||Function("return this")(),Xs=typeof document=="object"&&document.all,id=typeof Xs=="undefined"&&Xs!==void 0,ln={all:Xs,IS_HTMLDDA:id},cn=ln,sd=cn.all,Oe=cn.IS_HTMLDDA?function(s){return typeof s=="function"||s===sd}:function(s){return typeof s=="function"},rd=je,ad=Oe,Mr=rd.WeakMap,nd=ad(Mr)&&/native code/.test(String(Mr)),Ur=Oe,hn=ln,od=hn.all,At=hn.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:Ur(s)||s===od}:function(s){return typeof s=="object"?s!==null:Ur(s)},dd=it,ht=!dd(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Gt={},ud=je,Fr=At,Zs=ud.document,ld=Fr(Zs)&&Fr(Zs.createElement),fn=function(s){return ld?Zs.createElement(s):{}},cd=ht,hd=it,fd=fn,pn=!cd&&!hd(function(){return Object.defineProperty(fd("div"),"a",{get:function(){return 7}}).a!=7}),pd=ht,md=it,mn=pd&&md(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),vd=At,Sd=String,gd=TypeError,wt=function(s){if(vd(s))return s;throw gd(Sd(s)+" is not an object")},bd=Xi,Ti=Function.prototype.call,rt=bd?Ti.bind(Ti):function(){return Ti.apply(Ti,arguments)},lr={},fs=lr,ps=je,yd=Oe,Vr=function(s){return yd(s)?s:void 0},cr=function(s,e){return arguments.length<2?Vr(fs[s])||Vr(ps[s]):fs[s]&&fs[s][e]||ps[s]&&ps[s][e]},Td=st,hr=Td({}.isPrototypeOf),Ed=typeof navigator!="undefined"&&String(navigator.userAgent)||"",vn=je,ms=Ed,Hr=vn.process,Gr=vn.Deno,Yr=Hr&&Hr.versions||Gr&&Gr.version,qr=Yr&&Yr.v8,Ne,Hi;qr&&(Ne=qr.split("."),Hi=Ne[0]>0&&Ne[0]<4?1:+(Ne[0]+Ne[1]));!Hi&&ms&&(Ne=ms.match(/Edge\/(\d+)/),(!Ne||Ne[1]>=74)&&(Ne=ms.match(/Chrome\/(\d+)/),Ne&&(Hi=+Ne[1])));var $d=Hi,jr=$d,Ad=it,Sn=!!Object.getOwnPropertySymbols&&!Ad(function(){var s=Symbol();return!String(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&jr&&jr<41}),wd=Sn,gn=wd&&!Symbol.sham&&typeof Symbol.iterator=="symbol",_d=cr,kd=Oe,Pd=hr,Rd=gn,Id=Object,bn=Rd?function(s){return typeof s=="symbol"}:function(s){var e=_d("Symbol");return kd(e)&&Pd(e.prototype,Id(s))},Dd=String,fr=function(s){try{return Dd(s)}catch(e){return"Object"}},Ld=Oe,Cd=fr,xd=TypeError,pr=function(s){if(Ld(s))return s;throw xd(Cd(s)+" is not a function")},Od=pr,Nd=es,ts=function(s,e){var t=s[e];return Nd(t)?void 0:Od(t)},vs=rt,Ss=Oe,gs=At,Bd=TypeError,Md=function(s,e){var t,i;if(e==="string"&&Ss(t=s.toString)&&!gs(i=vs(t,s))||Ss(t=s.valueOf)&&!gs(i=vs(t,s))||e!=="string"&&Ss(t=s.toString)&&!gs(i=vs(t,s)))return i;throw Bd("Can't convert object to primitive value")},Gi={},Ud={get exports(){return Gi},set exports(s){Gi=s}},Fd=!0,zr=je,Vd=Object.defineProperty,Hd=function(s,e){try{Vd(zr,s,{value:e,configurable:!0,writable:!0})}catch(t){zr[s]=e}return e},Gd=je,Yd=Hd,Wr="__core-js_shared__",qd=Gd[Wr]||Yd(Wr,{}),yn=qd,Qr=yn;(Ud.exports=function(s,e){return Qr[s]||(Qr[s]=e!==void 0?e:{})})("versions",[]).push({version:"3.27.2",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.27.2/LICENSE",source:"https://github.com/zloirock/core-js"});var jd=ur,zd=Object,is=function(s){return zd(jd(s))},Wd=st,Qd=is,Jd=Wd({}.hasOwnProperty),at=Object.hasOwn||function(e,t){return Jd(Qd(e),t)},Kd=st,Xd=0,Zd=Math.random(),eu=Kd(1 .toString),Tn=function(s){return"Symbol("+(s===void 0?"":s)+")_"+eu(++Xd+Zd,36)},tu=je,iu=Gi,Jr=at,su=Tn,ru=Sn,au=gn,Ot=tu.Symbol,bs=iu("wks"),nu=au?Ot.for||Ot:Ot&&Ot.withoutSetter||su,Ue=function(s){return Jr(bs,s)||(bs[s]=ru&&Jr(Ot,s)?Ot[s]:nu("Symbol."+s)),bs[s]},ou=rt,Kr=At,Xr=bn,du=ts,uu=Md,lu=Ue,cu=TypeError,hu=lu("toPrimitive"),fu=function(s,e){if(!Kr(s)||Xr(s))return s;var t=du(s,hu),i;if(t){if(e===void 0&&(e="default"),i=ou(t,s,e),!Kr(i)||Xr(i))return i;throw cu("Can't convert object to primitive value")}return e===void 0&&(e="number"),uu(s,e)},pu=fu,mu=bn,mr=function(s){var e=pu(s,"string");return mu(e)?e:e+""},vu=ht,Su=pn,gu=mn,Ei=wt,Zr=mr,bu=TypeError,ys=Object.defineProperty,yu=Object.getOwnPropertyDescriptor,Ts="enumerable",Es="configurable",$s="writable";Gt.f=vu?gu?function(e,t,i){if(Ei(e),t=Zr(t),Ei(i),typeof e=="function"&&t==="prototype"&&"value"in i&&$s in i&&!i[$s]){var r=yu(e,t);r&&r[$s]&&(e[t]=i.value,i={configurable:Es in i?i[Es]:r[Es],enumerable:Ts in i?i[Ts]:r[Ts],writable:!1})}return ys(e,t,i)}:ys:function(e,t,i){if(Ei(e),t=Zr(t),Ei(i),Su)try{return ys(e,t,i)}catch(r){}if("get"in i||"set"in i)throw bu("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var ss=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},Tu=ht,Eu=Gt,$u=ss,ci=Tu?function(s,e,t){return Eu.f(s,e,$u(1,t))}:function(s,e,t){return s[e]=t,s},Au=Gi,wu=Tn,ea=Au("keys"),vr=function(s){return ea[s]||(ea[s]=wu(s))},Sr={},_u=nd,En=je,ku=At,Pu=ci,As=at,ws=yn,Ru=vr,Iu=Sr,ta="Object already initialized",er=En.TypeError,Du=En.WeakMap,Yi,di,qi,Lu=function(s){return qi(s)?di(s):Yi(s,{})},Cu=function(s){return function(e){var t;if(!ku(e)||(t=di(e)).type!==s)throw er("Incompatible receiver, "+s+" required");return t}};if(_u||ws.state){var Ge=ws.state||(ws.state=new Du);Ge.get=Ge.get,Ge.has=Ge.has,Ge.set=Ge.set,Yi=function(s,e){if(Ge.has(s))throw er(ta);return e.facade=s,Ge.set(s,e),e},di=function(s){return Ge.get(s)||{}},qi=function(s){return Ge.has(s)}}else{var It=Ru("state");Iu[It]=!0,Yi=function(s,e){if(As(s,It))throw er(ta);return e.facade=s,Pu(s,It,e),e},di=function(s){return As(s,It)?s[It]:{}},qi=function(s){return As(s,It)}}var xu={set:Yi,get:di,has:qi,enforce:Lu,getterFor:Cu},Ou=Xi,$n=Function.prototype,ia=$n.apply,sa=$n.call,Nu=typeof Reflect=="object"&&Reflect.apply||(Ou?sa.bind(ia):function(){return sa.apply(ia,arguments)}),Bu=Zi,Mu=st,An=function(s){if(Bu(s)==="Function")return Mu(s)},wn={},_n={},kn={}.propertyIsEnumerable,Pn=Object.getOwnPropertyDescriptor,Uu=Pn&&!kn.call({1:2},1);_n.f=Uu?function(e){var t=Pn(this,e);return!!t&&t.enumerable}:kn;var Fu=ht,Vu=rt,Hu=_n,Gu=ss,Yu=li,qu=mr,ju=at,zu=pn,ra=Object.getOwnPropertyDescriptor;wn.f=Fu?ra:function(e,t){if(e=Yu(e),t=qu(t),zu)try{return ra(e,t)}catch(i){}if(ju(e,t))return Gu(!Vu(Hu.f,e,t),e[t])};var Wu=it,Qu=Oe,Ju=/#|\.prototype\./,hi=function(s,e){var t=Xu[Ku(s)];return t==el?!0:t==Zu?!1:Qu(e)?Wu(e):!!e},Ku=hi.normalize=function(s){return String(s).replace(Ju,".").toLowerCase()},Xu=hi.data={},Zu=hi.NATIVE="N",el=hi.POLYFILL="P",tl=hi,aa=An,il=pr,sl=Xi,rl=aa(aa.bind),Rn=function(s,e){return il(s),e===void 0?s:sl?rl(s,e):function(){return s.apply(e,arguments)}},$i=je,al=Nu,nl=An,ol=Oe,dl=wn.f,ul=tl,Dt=lr,ll=Rn,Lt=ci,na=at,cl=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 al(s,this,arguments)};return e.prototype=s.prototype,e},rs=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?$i:r?$i[t]:($i[t]||{}).prototype,o=i?Dt:Dt[t]||Lt(Dt,t,{})[t],u=o.prototype,d,l,c,h,p,v,f,S,g;for(h in e)d=ul(i?h:t+(r?".":"#")+h,s.forced),l=!d&&n&&na(n,h),v=o[h],l&&(s.dontCallGetSet?(g=dl(n,h),f=g&&g.value):f=n[h]),p=l&&f?f:e[h],!(l&&typeof v==typeof p)&&(s.bind&&l?S=ll(p,$i):s.wrap&&l?S=cl(p):a&&ol(p)?S=nl(p):S=p,(s.sham||p&&p.sham||v&&v.sham)&&Lt(S,"sham",!0),Lt(o,h,S),a&&(c=t+"Prototype",na(Dt,c)||Lt(Dt,c,{}),Lt(Dt[c],h,p),s.real&&u&&(d||!u[h])&&Lt(u,h,p)))},tr=ht,hl=at,In=Function.prototype,fl=tr&&Object.getOwnPropertyDescriptor,gr=hl(In,"name"),pl=gr&&function(){}.name==="something",ml=gr&&(!tr||tr&&fl(In,"name").configurable),vl={EXISTS:gr,PROPER:pl,CONFIGURABLE:ml},Dn={},Sl=Math.ceil,gl=Math.floor,bl=Math.trunc||function(e){var t=+e;return(t>0?gl:Sl)(t)},yl=bl,br=function(s){var e=+s;return e!==e||e===0?0:yl(e)},Tl=br,El=Math.max,$l=Math.min,Al=function(s,e){var t=Tl(s);return t<0?El(t+e,0):$l(t,e)},wl=br,_l=Math.min,kl=function(s){return s>0?_l(wl(s),9007199254740991):0},Pl=kl,yr=function(s){return Pl(s.length)},Rl=li,Il=Al,Dl=yr,oa=function(s){return function(e,t,i){var r=Rl(e),a=Dl(r),n=Il(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}},Ll={includes:oa(!0),indexOf:oa(!1)},Cl=st,_s=at,xl=li,Ol=Ll.indexOf,Nl=Sr,da=Cl([].push),Bl=function(s,e){var t=xl(s),i=0,r=[],a;for(a in t)!_s(Nl,a)&&_s(t,a)&&da(r,a);for(;e.length>i;)_s(t,a=e[i++])&&(~Ol(r,a)||da(r,a));return r},Ln=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Ml=Bl,Ul=Ln,Fl=Object.keys||function(e){return Ml(e,Ul)},Vl=ht,Hl=mn,Gl=Gt,Yl=wt,ql=li,jl=Fl;Dn.f=Vl&&!Hl?Object.defineProperties:function(e,t){Yl(e);for(var i=ql(t),r=jl(t),a=r.length,n=0,o;a>n;)Gl.f(e,o=r[n++],i[o]);return e};var zl=cr,Wl=zl("document","documentElement"),Ql=wt,Jl=Dn,ua=Ln,Kl=Sr,Xl=Wl,Zl=fn,ec=vr,la=">",ca="<",ir="prototype",sr="script",Cn=ec("IE_PROTO"),ks=function(){},xn=function(s){return ca+sr+la+s+ca+"/"+sr+la},ha=function(s){s.write(xn("")),s.close();var e=s.parentWindow.Object;return s=null,e},tc=function(){var s=Zl("iframe"),e="java"+sr+":",t;return s.style.display="none",Xl.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(xn("document.F=Object")),t.close(),t.F},Ai,Bi=function(){try{Ai=new ActiveXObject("htmlfile")}catch(e){}Bi=typeof document!="undefined"?document.domain&&Ai?ha(Ai):tc():ha(Ai);for(var s=ua.length;s--;)delete Bi[ir][ua[s]];return Bi()};Kl[Cn]=!0;var On=Object.create||function(e,t){var i;return e!==null?(ks[ir]=Ql(e),i=new ks,ks[ir]=null,i[Cn]=e):i=Bi(),t===void 0?i:Jl.f(i,t)},ic=it,sc=!ic(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),rc=at,ac=Oe,nc=is,oc=vr,dc=sc,fa=oc("IE_PROTO"),rr=Object,uc=rr.prototype,Nn=dc?rr.getPrototypeOf:function(s){var e=nc(s);if(rc(e,fa))return e[fa];var t=e.constructor;return ac(t)&&e instanceof t?t.prototype:e instanceof rr?uc:null},lc=ci,Bn=function(s,e,t,i){return i&&i.enumerable?s[e]=t:lc(s,e,t),s},cc=it,hc=Oe,fc=At,pc=On,pa=Nn,mc=Bn,vc=Ue,ar=vc("iterator"),Mn=!1,et,Ps,Rs;[].keys&&(Rs=[].keys(),"next"in Rs?(Ps=pa(pa(Rs)),Ps!==Object.prototype&&(et=Ps)):Mn=!0);var Sc=!fc(et)||cc(function(){var s={};return et[ar].call(s)!==s});Sc?et={}:et=pc(et);hc(et[ar])||mc(et,ar,function(){return this});var Un={IteratorPrototype:et,BUGGY_SAFARI_ITERATORS:Mn},gc=Ue,bc=gc("toStringTag"),Fn={};Fn[bc]="z";var Tr=String(Fn)==="[object z]",yc=Tr,Tc=Oe,Mi=Zi,Ec=Ue,$c=Ec("toStringTag"),Ac=Object,wc=Mi(function(){return arguments}())=="Arguments",_c=function(s,e){try{return s[e]}catch(t){}},as=yc?Mi:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=_c(e=Ac(s),$c))=="string"?t:wc?Mi(e):(i=Mi(e))=="Object"&&Tc(e.callee)?"Arguments":i},kc=Tr,Pc=as,Rc=kc?{}.toString:function(){return"[object "+Pc(this)+"]"},Ic=Tr,Dc=Gt.f,Lc=ci,Cc=at,xc=Rc,Oc=Ue,ma=Oc("toStringTag"),Vn=function(s,e,t,i){if(s){var r=t?s:s.prototype;Cc(r,ma)||Dc(r,ma,{configurable:!0,value:e}),i&&!Ic&&Lc(r,"toString",xc)}},Nc=Un.IteratorPrototype,Bc=On,Mc=ss,Uc=Vn,Fc=Ht,Vc=function(){return this},Hc=function(s,e,t,i){var r=e+" Iterator";return s.prototype=Bc(Nc,{next:Mc(+!i,t)}),Uc(s,r,!1,!0),Fc[r]=Vc,s},Gc=rs,Yc=rt,Hn=vl,qc=Hc,jc=Nn,zc=Vn,va=Bn,Wc=Ue,Sa=Ht,Gn=Un,Qc=Hn.PROPER;Hn.CONFIGURABLE;Gn.IteratorPrototype;var wi=Gn.BUGGY_SAFARI_ITERATORS,Is=Wc("iterator"),ga="keys",_i="values",ba="entries",Jc=function(){return this},Kc=function(s,e,t,i,r,a,n){qc(t,e,i);var o=function(g){if(g===r&&h)return h;if(!wi&&g in l)return l[g];switch(g){case ga:return function(){return new t(this,g)};case _i:return function(){return new t(this,g)};case ba:return function(){return new t(this,g)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,l=s.prototype,c=l[Is]||l["@@iterator"]||r&&l[r],h=!wi&&c||o(r),p=e=="Array"&&l.entries||c,v,f,S;if(p&&(v=jc(p.call(new s)),v!==Object.prototype&&v.next&&(zc(v,u,!0,!0),Sa[u]=Jc)),Qc&&r==_i&&c&&c.name!==_i&&(d=!0,h=function(){return Yc(c,this)}),r)if(f={values:o(_i),keys:a?h:o(ga),entries:o(ba)},n)for(S in f)(wi||d||!(S in l))&&va(l,S,f[S]);else Gc({target:e,proto:!0,forced:wi||d},f);return n&&l[Is]!==h&&va(l,Is,h,{name:r}),Sa[e]=h,f},Xc=function(s,e){return{value:s,done:e}},Zc=li,Er=td,ya=Ht,Yn=xu,eh=Gt.f,th=Kc,ki=Xc,ih=Fd,sh=ht,qn="Array Iterator",rh=Yn.set,ah=Yn.getterFor(qn);th(Array,"Array",function(s,e){rh(this,{type:qn,target:Zc(s),index:0,kind:e})},function(){var s=ah(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,ki(void 0,!0)):t=="keys"?ki(i,!1):t=="values"?ki(e[i],!1):ki([i,e[i]],!1)},"values");var Ta=ya.Arguments=ya.Array;Er();Er();Er();if(!ih&&sh&&Ta.name!=="values")try{eh(Ta,"name",{value:"values"})}catch(s){}var nh=Ue,oh=Ht,dh=nh("iterator"),uh=Array.prototype,lh=function(s){return s!==void 0&&(oh.Array===s||uh[dh]===s)},ch=as,Ea=ts,hh=es,fh=Ht,ph=Ue,mh=ph("iterator"),jn=function(s){if(!hh(s))return Ea(s,mh)||Ea(s,"@@iterator")||fh[ch(s)]},vh=rt,Sh=pr,gh=wt,bh=fr,yh=jn,Th=TypeError,Eh=function(s,e){var t=arguments.length<2?yh(s):e;if(Sh(t))return gh(vh(t,s));throw Th(bh(s)+" is not iterable")},$h=rt,$a=wt,Ah=ts,wh=function(s,e,t){var i,r;$a(s);try{if(i=Ah(s,"return"),!i){if(e==="throw")throw t;return t}i=$h(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return $a(i),t},_h=Rn,kh=rt,Ph=wt,Rh=fr,Ih=lh,Dh=yr,Aa=hr,Lh=Eh,Ch=jn,wa=wh,xh=TypeError,Ui=function(s,e){this.stopped=s,this.result=e},_a=Ui.prototype,Oh=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=_h(e,i),d,l,c,h,p,v,f,S=function(T){return d&&wa(d,"normal",T),new Ui(!0,T)},g=function(T){return r?(Ph(T),o?u(T[0],T[1],S):u(T[0],T[1])):o?u(T,S):u(T)};if(a)d=s.iterator;else if(n)d=s;else{if(l=Ch(s),!l)throw xh(Rh(s)+" is not iterable");if(Ih(l)){for(c=0,h=Dh(s);h>c;c++)if(p=g(s[c]),p&&Aa(_a,p))return p;return new Ui(!1)}d=Lh(s,l)}for(v=a?s.next:d.next;!(f=kh(v,d)).done;){try{p=g(f.value)}catch(T){wa(d,"throw",T)}if(typeof p=="object"&&p&&Aa(_a,p))return p}return new Ui(!1)},Nh=mr,Bh=Gt,Mh=ss,Uh=function(s,e,t){var i=Nh(e);i in s?Bh.f(s,i,Mh(0,t)):s[i]=t},Fh=rs,Vh=Oh,Hh=Uh;Fh({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Vh(e,function(i,r){Hh(t,i,r)},{AS_ENTRIES:!0}),t}});var Gh=lr,Yh=Gh.Object.fromEntries,qh={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},jh=qh,zh=je,Wh=as,Qh=ci,ka=Ht,Jh=Ue,Pa=Jh("toStringTag");for(var Ds in jh){var Ra=zh[Ds],Ls=Ra&&Ra.prototype;Ls&&Wh(Ls)!==Pa&&Qh(Ls,Pa,Ds),ka[Ds]=ka.Array}var Kh=Yh,Xh=Kh,Zh=Xh,ef=Zh,fi=ef,Bt;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(Bt||(Bt={}));var Mt=(s,e=0,t=Bt.OFFSET_P)=>{switch(t){case Bt.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Bt.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}default:O(t)}return s},R=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)},ae;(function(s){s.INVARIANT="Invariant quality",s.Q_144P="144p",s.Q_240P="240p",s.Q_360P="360p",s.Q_480P="480p",s.Q_720P="720p",s.Q_1080P="1080p",s.Q_1440P="1440p",s.Q_2160P="2160p",s.Q_4320P="4320p"})(ae||(ae={}));const Me={[ae.Q_144P]:{width:256,height:144},[ae.Q_240P]:{width:428,height:240},[ae.Q_360P]:{width:640,height:360},[ae.Q_480P]:{width:856,height:480},[ae.Q_720P]:{width:1280,height:720},[ae.Q_1080P]:{width:1920,height:1080},[ae.Q_1440P]:{width:2560,height:1440},[ae.Q_2160P]:{width:3840,height:2160},[ae.Q_4320P]:{width:7680,height:4320}},Fi=(s,e)=>Me[s].height>Me[e].height,tf=(s,e)=>Me[s].height>=Me[e].height,ri=(s,e)=>Me[s].height<Me[e].height,sf=(s,e)=>Me[s].height<=Me[e].height,rf=s=>s.sort((e,t)=>e===t?0:e===ae.INVARIANT?1:t===ae.INVARIANT?-1:ri(e,t)?1:-1)[0],af=Object.keys(Me).sort((s,e)=>ri(s,e)?-1:1),_t=({width:s,height:e})=>{const t=Math.min(s,e),i=Math.max(s,e);return af.find(r=>{const a=Me[r];return a.width>=i&&a.height>=t})},nf=s=>Me[s].height,ji=s=>s===ae.INVARIANT;class de{constructor(e){this.transitionStarted$=new C,this.transitionEnded$=new C,this.transitionUpdated$=new C,this.forceChanged$=new C,this.stateChangeStarted$=x(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=x(this.transitionEnded$,this.forceChanged$),this.state=e}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||_(t)&&t.to===e||(this.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}}const of=s=>{switch(s){case b.MPEG:case b.DASH:case b.DASH_SEP:case b.DASH_ONDEMAND:case b.DASH_WEBM:case b.HLS:case b.HLS_ONDEMAND:return!1;case b.DASH_LIVE:case b.DASH_LIVE_CMAF:case b.HLS_LIVE:case b.HLS_LIVE_CMAF:case b.DASH_LIVE_WEBM:case b.WEB_RTC_LIVE:return!0;default:return O(s)}};var Y;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Y||(Y={}));const df=5,uf=5,lf=500,Ia=7e3;class cf{constructor(e){this.subscription=new ie,this.loadMediaTimeoutSubscription=new ie,this.videoState=new de(Y.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!==Y.STOPPED&&(this.videoState.startTransitionTo(Y.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==m.PAUSED&&o.state===V.Requested&&i!==Y.STOPPED){this.seek(o.position/1e3);return}switch(a){case m.READY:{switch(i){case Y.PLAYING:case Y.PAUSED:case Y.READY:break;case Y.STOPPED:this.videoState.startTransitionTo(Y.READY),this.prepare();break;default:O(i)}break}case m.PLAYING:{switch(i){case Y.PLAYING:break;case Y.PAUSED:this.videoState.startTransitionTo(Y.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case Y.READY:this.videoState.startTransitionTo(Y.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case Y.STOPPED:this.videoState.startTransitionTo(Y.READY),this.prepare();break;default:O(i)}break}case m.PAUSED:{switch(i){case Y.PLAYING:this.videoState.startTransitionTo(Y.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case Y.PAUSED:break;case Y.READY:this.videoState.startTransitionTo(Y.PAUSED),this.videoState.setState(Y.PAUSED);break;case Y.STOPPED:this.videoState.startTransitionTo(Y.READY),this.prepare();break;default:O(i)}break}default:O(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(of(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new ie;this.subscription.add(e),this.subscription.add(x(this.videoState.stateChangeStarted$.pipe($(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe($(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));const t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const r=new C;e.add(r.pipe(xe(lf)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(M(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===V.Applying||Math.abs(o-a)>df)&&r.next(o),a=o})),e.add(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(M(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<uf&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),R(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:O(n)}}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(M(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const i=x(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(xe(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(Y.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED)):(this.videoState.setState(Y.PLAYING),R(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:V.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)===Y.PAUSED||e===Y.PLAYING)&&(this.videoState.setState(Y.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===Y.PLAYING||e===Y.PAUSED)&&(this.videoState.setState(Y.PLAYING),R(this.params.desiredState.playbackState,m.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===Y.READY&&this.videoState.setState(Y.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===m.READY&&R(this.params.desiredState.playbackState,m.READY)}handleRemoteStop(){this.videoState.getState()!==Y.STOPPED&&this.videoState.setState(Y.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 b.MPEG:{const l=i[e];P(l);const c=rf(Object.keys(l));P(c);const h=l[c];P(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case b.HLS:case b.HLS_ONDEMAND:{const l=i[e];P(l),r=l.url,a="application/x-mpegurl",n=chrome.cast.media.StreamType.BUFFERED;break}case b.DASH_SEP:case b.DASH_ONDEMAND:case b.DASH_WEBM:{const l=i[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case b.DASH_LIVE_CMAF:{const l=i[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case b.HLS_LIVE:case b.HLS_LIVE_CMAF:{const l=i[e];P(l),r=Mt(l.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case b.DASH:case b.DASH_LIVE:case b.WEB_RTC_LIVE:{const l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:L.VIDEO_PIPELINE,message:l,thrown:c}),c}case b.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return O(e)}const o=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,a);o.contentUrl=r,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return _(u)&&(o.metadata.title=u),_(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===V.Applying||i.state===V.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(Co(Ia).subscribe(()=>a(`timeout(${Ia})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===V.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:L.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}class Da{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 zn extends Da{constructor(){super(),this.listeners||Da.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 Wn=class{constructor(){Object.defineProperty(this,"signal",{value:new zn,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&&(Wn.prototype[Symbol.toStringTag]="AbortController",zn.prototype[Symbol.toStringTag]="AbortSignal");function Qn(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 hf(s){typeof s=="function"&&(s={fetch:s});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!Qn({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(p){c=new Error("Aborted"),c.name="AbortError"}if(l.aborted)return Promise.reject(c);const h=new Promise((p,v)=>{l.addEventListener("abort",()=>v(c),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([h,n(u,d)])}return n(u,d)},Request:a}}const ns=Qn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Jn=ns?hf({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ut=ns?Jn.fetch:window.fetch;ns?Jn.Request:window.Request;const Tt=ns?Wn:window.AbortController,ti=s=>s.range?s.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class ai{constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){var t;const{url:i}=e.request,r=(t=this.dashJsRequestQueue.get(i))!==null&&t!==void 0?t:[];r.push(e),this.dashJsRequestQueue.set(i,r)}async executeNextRequests(){for(const[e,t]of this.dashJsRequestQueue.entries()){const i=this.activeRequests.get(e);if(i){t.length&&this.onBigRequestProgress(i);const r=t[0];if(!r||!r.request.range)continue;const[a,n]=ti(r.request);if(a>=i.from&&n<=i.to)continue;this.activeRequests.delete(e)}if(t.length){const r=this.sendBigRequest(e,t.map(({request:a})=>a));this.activeRequests.set(e,r)}}}abort(e){var t;if(e){const{request:i}=e,r=((t=this.dashJsRequestQueue.get(i.url))!==null&&t!==void 0?t:[]).includes(e),a=this.activeRequests.get(i.url);r&&a&&a.abortController.abort()}else for(const{abortController:i}of this.activeRequests.values())i.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const i=t.map(ti),r=i[0][0];let a=i[0][1];for(let h=1;h<i.length&&a<this.params.minDataSize;h++){const p=i[h][1];p-r<=2*this.params.minDataSize&&(a=Math.max(a,p))}r===0?a=Math.max(a,r+this.params.minInitSize):a=Math.max(a,r+this.params.minDataSize);const n=new URL(e,location.href);n.searchParams.append("bytes",`${r}-${a}`);const o=n.toString(),u=new Tt,d=u.signal,l={url:e,from:r,to:a,loaded:0,data:null,abortController:u};d.addEventListener("abort",()=>this.onBigRequestAbort(l));const c=h=>{var p,v;throw(v=(p=this.params).onError)===null||v===void 0||v.call(p,{id:"BigRequestParsing",category:L.PARSER,message:"Error parsing response data",thrown:h}),h};return Ut(o,{signal:d}).then(h=>{var p,v,f;if(l.response=h,!h.ok||!h.body){this.onBigRequestError(l);return}const[S,g]=h.body.tee();(v=(p=this.params).onDownloadStream)===null||v===void 0||v.call(p,g);const T=S.getReader(),I=parseInt((f=h.headers.get("Content-Length"))!==null&&f!==void 0?f:"",10)||a-r+1;l.data=new ArrayBuffer(I);const w=new Uint8Array(l.data),A=async({done:N,value:K})=>{N?this.onBigRequestProgress(l):K&&(w.set(K,l.loaded),l.loaded+=K.byteLength,this.onBigRequestProgress(l),await(T==null?void 0:T.read().then(A,ai.suppressStreamErrors).catch(c)))};T==null||T.read().then(A,ai.suppressStreamErrors).catch(c)},ai.suppressAbort).catch(h=>this.onBigRequestError(l,h)),l}onBigRequestProgress({url:e,from:t,to:i,loaded:r,data:a,response:n}){var o,u,d,l,c,h,p,v;if(!this.activeRequests.has(e)||!a)return;const f=(o=this.dashJsRequestQueue.get(e))!==null&&o!==void 0?o:[];for(const S of f){const{request:g}=S,[T,I]=ti(g),w=T>=t&&I<=t+r,A=t>=T&&t+r<I,N=a.slice(T-t,Math.min(I-t+1,r));if((w||A)&&(g.requestStartDate=(u=g.requestStartDate)!==null&&u!==void 0?u:new Date,g.firstByteDate=(d=g.firstByteDate)!==null&&d!==void 0?d:new Date,g.bytesLoaded=N.byteLength,g.bytesTotal=i-t),w){g.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[]).filter(G=>G!==S)),(c=S.success)===null||c===void 0||c.call(S,N,"",e);const K=n?Array.from(n.headers.entries()).map(([G,U])=>`${G}: ${U}`).join(`\r
|
|
7
|
-
`):"";(h=this.dashMetrics)===null||h===void 0||h.addHttpRequest(g,e,(p=n==null?void 0:n.status)!==null&&p!==void 0?p:200,K,[])}else A&&((v=S.progress)===null||v===void 0||v.call(S,{loaded:r,total:i-t,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:t,to:i},r){var a,n,o,u;if((n=(a=this.params).onError)===null||n===void 0||n.call(a,{id:"BigRequest",category:L.NETWORK,message:"Download error",thrown:r}),!this.activeRequests.has(e))return;const d=(o=this.dashJsRequestQueue.get(e))!==null&&o!==void 0?o:[];for(const l of d){const[c,h]=ti(l.request);(c>=t&&c<i||h>t&&h<=i)&&((u=l==null?void 0:l.error)===null||u===void 0||u.call(l,l.request,String(r)))}if(this.activeRequests.delete(e),r)throw r}onBigRequestAbort({url:e,from:t,to:i}){var r,a;if(!this.activeRequests.has(e))return;const n=(r=this.dashJsRequestQueue.get(e))!==null&&r!==void 0?r:[];for(const o of n){const[u,d]=ti(o.request);(u>=t&&u<i||d>t&&d<=i)&&((a=o==null?void 0:o.abort)===null||a===void 0||a.call(o,o.request))}this.activeRequests.delete(e)}static suppressAbort(e){if(!(e instanceof DOMException)||!(e.name==="AbortError"||e.code===20))throw e}static suppressStreamErrors(){}}class zi{constructor(e,t,i){this.baseLoader=e,this.config=i,this.bigRequest=t,t.setMetrics(i.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(zi.shouldDelegateToBase(t))return this.baseLoader.load(e);this.bigRequest.queueDashJSRequest(e),this.bigRequest.executeNextRequests()}abort(e){if(!e){this.baseLoader.abort(),this.bigRequest.abort();return}const{request:t}=e;zi.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const ff=(s,e)=>t=>({create:i=>{const r=s(t).create(i);return new zi(r,e,i)}}),pf=(s,e)=>{const t=new ai(e);return s.extend("SchemeLoaderFactory",function(){const{parent:i}=this,r=i.getLoader;return{getLoader:a=>{const n=r(a);return ff(n,t)}}},!0),()=>t.destroy()};var mf=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)},vf=s=>{const e=new y(1/0),t=new C,i=new y(void 0),r=new y(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},u=l=>{var c,h,p,v,f;const S=fi(l.getAllResponseHeaders().trim().split(/[\n\r]+/).map(I=>I.split(": ")));if("x-playback-duration"in S||"x-playback-duration-millis"in S){const I=parseInt((c=l.getResponseHeader("X-Playback-Duration"))!==null&&c!==void 0?c:"",10),w=parseInt((h=l.getResponseHeader("X-Playback-Duration-Millis"))!==null&&h!==void 0?h:"",10),A=(p=w!=null?w:I*1e3)!==null&&p!==void 0?p:NaN;_(A)&&!isNaN(A)&&e.next(A)}const g=(v=S["x-delivery-type"])!==null&&v!==void 0?v:oi.HTTP1,T=(f={1:!0,0:!1}[S["x-reused"]])!==null&&f!==void 0?f:void 0;i.next(g),r.next(T)},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 p=h.onload,v=h.progress;h.onload=function(...f){return u(this),p(...f)},h.progress=function(...f){return d(this),v(...f)},o()}return c(h)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:i}},Ft=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},Sf=s=>s.extend("RequestModifier",()=>({modifyRequestURL:Ft}),!0),gf=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 qe=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=s.getState(),o=e(),u=J(r),d=new ie;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},kt=(s,e,t)=>qe(e,()=>s.loop,i=>{_(i)&&(s.loop=i)},{onError:t}),nt=(s,e,t,i)=>qe(e,()=>({muted:s.muted,volume:s.volume}),r=>{_(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),ft=(s,e,t,i)=>qe(e,()=>s.playbackRate,r=>{_(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),bf=s=>["__",s.language,s.label].join("|"),yf=(s,e)=>{if(s.id===e)return!0;const[t,i,r]=e.split("|");return s.language===i&&s.label===r};class ze{constructor(){this.available$=new C,this.current$=new y(void 0),this.error$=new C,this.subscription=new ie,this.externalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:L.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(qe(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{_(a)&&this.setExternal(a)},{equal:(a,n)=>_(a)&&_(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe($(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(qe(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(qe(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){P(this.video);const{textTracks:e}=this.video;this.subscription.add(M(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();this.select(i)})),this.subscription.add(x(M(e,"addtrack"),M(e,"removetrack"),ke(["init"])).pipe($(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),pe((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(x(M(e,"change"),ke(["init"])).pipe($(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),$(i=>i&&this.htmlTextTrackToITextTrack(i).id),pe()).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(M(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 p=(d=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&d!==void 0?d:null;p&&p.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(M(e,"removetrack").subscribe(i=>{var r;(r=i.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const r=i;_(t.align)&&(r.align=t.align),_(t.position)&&(r.position=t.position),_(t.size)&&(r.size=t.size),_(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){P(this.video);const t=[...this.video.textTracks];return e?t:t.filter(ze.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,r=e.id!==""?e.id:bf(e);return this.externalTracks.has(r)?{id:r,type:"external",language:t,label:i,url:this.externalTracks.get(r).url}:{id:r,type:"internal",language:t,label:i}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.id===""&&e.label===""&&e.language==="")}setExternal(e){e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks.keys()).filter(t=>!e.find(i=>i.id===t)).forEach(t=>this.detach(t))}select(e){P(this.video);for(const t of this.htmlTextTracksAsArray(!0))_(e)&&yf(t,e)?t.mode="showing":t.mode="disabled"}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){P(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),this.externalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){P(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e);t&&this.video.removeChild(t),this.externalTracks.delete(e)}}var ot=s=>{const e=document.createElement("video");return e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),s.appendChild(e),e};class $r{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){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0}}var Kn=()=>{const{userAgent:s}=window.navigator;return!/chrome/i.test(s)&&/webkit|safari|khtml/i.test(s)};const nr=3;class Tf{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<nr&&(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||nr))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 Xn=(s,e,t=nr)=>{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 Ef=50,$f=s=>s.webkitAudioDecodedByteCount!=="undefined"?!!s.webkitAudioDecodedByteCount:s.mozHasAudio!=="undefined"?s.mozHasAudio:s.audioTracks?!!s.audioTracks.length:!0,dt=s=>{const e=v=>M(s,v).pipe($t(void 0)),i=x(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>M(s,v))).pipe($(v=>v.type==="ended"?s.readyState<2:s.readyState<3),pe()),r=x(M(s,"progress"),M(s,"timeupdate")).pipe($(()=>Xn(s.buffered,s.currentTime))),a=Kn()?Ze({play:e("play").pipe(ge()),playing:e("playing")}).pipe($t(void 0)):e("playing"),n=M(s,"playing").pipe(xe(Ef),$(()=>$f(s))),o=M(s,"volumechange").pipe($(()=>({muted:s.muted,volume:s.volume}))),u=M(s,"ratechange").pipe($(()=>s.playbackRate)),d=M(s,"error").pipe(q(()=>Boolean(s.error||s.played.length)),$(()=>{var v;const f=s.error;return{id:f?`MediaError#${f.code}`:"HtmlVideoError",category:L.VIDEO_PIPELINE,message:f?f.message:"Error event from HTML video element",thrown:(v=s.error)!==null&&v!==void 0?v:void 0}})),l=M(s,"timeupdate").pipe($(()=>s.currentTime)),c=new C,h=.3;let p;return l.subscribe(v=>{s.loop&&_(p)&&_(v)&&p>=s.duration-h&&v<=h&&c.next(p),p=v}),{playing$:a,pause$:e("pause").pipe(q(()=>!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$:M(s,"durationchange").pipe($(()=>s.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:o,isAudioAvailable$:n,playbackRateState$:u}},Ar=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var Af=rs,wf=is,_f=yr,kf=br;Af({target:"Array",proto:!0},{at:function(e){var t=wf(this),i=_f(t),r=kf(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});var Pf=cr,Zn=Pf,Rf=Zn,If=Rf("Array","at"),Df=If,Lf=Df,Cf=Lf,xf=Cf,Je=xf;let wr=!1,Ke={};const Of=s=>{wr=s},Nf=()=>{Ke={}},Bf=s=>{s(Ke)},Pi=(s,e)=>{var t;wr&&(Ke.meta=(t=Ke.meta)!==null&&t!==void 0?t:{},Ke.meta[s]=e)};class Ye{constructor(e){this.name=e}next(e){var t,i;if(!wr)return;Ke.series=(t=Ke.series)!==null&&t!==void 0?t:{};const r=(i=Ke.series[this.name])!==null&&i!==void 0?i:[];r.push([Date.now(),e]),Ke.series[this.name]=r}}const Mf=new Ye("best_bitrate"),Uf=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class Ff{constructor(){this.history={}}recordSelection(e){this.history[e.id]=he()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const pi=(s,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:d})=>{var l,c,h,p;const v=i.usePixelRatio&&(l=window.devicePixelRatio)!==null&&l!==void 0?l:1,f=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*v*i.containerSizeFactor,height:e.height*v*i.containerSizeFactor},S=f&&_t(f),g=i.considerPlaybackRate&&_(o)?o:1,T=s.filter(F=>!ji(F.quality)).sort((F,B)=>Fi(F.quality,B.quality)?-1:1),I=(c=Je(T,-1))===null||c===void 0?void 0:c.quality,w=(h=Je(T,0))===null||h===void 0?void 0:h.quality,A=J(r)||_(r.min)&&_(r.max)&&ri(r.max,r.min)||_(r.min)&&w&&Fi(r.min,w)||_(r.max)&&I&&ri(r.max,I),N=g*Uf(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),G=T.filter(F=>{const B=S?ri(F.quality,S):!0,te=_(t)&&isFinite(t)&&_(F.bitrate)?t-a>=F.bitrate*N:!0,ue=i.lazyQualitySwitch&&_(i.minBufferToSwitchUp)&&u&&!ji(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Fi(F.quality,u.quality),me=A||(J(r.max)||sf(F.quality,r.max))&&(J(r.min)||tf(F.quality,r.min));return B&&te&&!ue&&me})[0];G&&G.bitrate&&Mf.next(G.bitrate);const U=(p=G!=null?G:T[Math.ceil((T.length-1)/2)])!==null&&p!==void 0?p:s[0],X=U&&d&&d.history[U.id]&&he()-d.history[U.id]<=i.trackCooldown&&(!d.last||U.id!==d.last.id);if(U!=null&&U.id&&d&&!X&&d.recordSelection(U),X&&(d!=null&&d.last)){const F=d.last;return d==null||d.recordSwitch(F),F}return d==null||d.recordSwitch(U),U};var Ae=s=>new URL(s).hostname;const Vf=300,Wi=(s,e=Vf)=>new ui(t=>{const{width:i,height:r}=s.getBoundingClientRect();if(t.next({width:i,height:r}),!window.ResizeObserver)return;const a=new ResizeObserver(No(n=>{const o=n[0];if(!o)return;let u,d;o.contentBoxSize&&o.contentBoxSize[0]?(d=o.contentBoxSize[0].blockSize,u=o.contentBoxSize[0].inlineSize):o.contentRect&&(u=o.contentRect.width,d=o.contentRect.height),_(u)&&_(d)&&t.next({width:u,height:d})},e));return a.observe(s),()=>a.disconnect()}),Hf=5e3,ii={};var j;(function(s){s.DOWNLOADING_LIB="downloading_lib",s.STOPPED="stopped",s.STREAM_INITIALIZED="stream_initialized",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(j||(j={}));const Se=(s,e)=>new ui(t=>{const i=r=>t.next(r);return s.on(e,i),()=>s.off(e,i)});class La{constructor(e){this.subscription=new ie,this.videoState=new de(j.DOWNLOADING_LIB),this.textTracksManager=new ze,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new y(void 0),this.maxSeekBackTime$=new y(1/0),this.availableFrom$=new y(void 0),this.elementSize$=new y(void 0),this.liveOffset=new $r,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===j.DOWNLOADING_LIB||t===j.STREAM_INITIALIZED))switch((r==null?void 0:r.to)!==m.PAUSED&&a.state===V.Requested&&t!==j.STOPPED&&i!==m.STOPPED&&(n?this.seek(a.position-this.liveOffset.getTotalPausedTime()):this.seek(a.position)),i){case m.STOPPED:{switch(t){case j.STOPPED:break;case j.PLAYING:case j.PAUSED:case j.READY:this.stop();break;default:O(t)}break}case m.READY:{switch(t){case j.STOPPED:this.prepare();break;case j.PLAYING:case j.PAUSED:case j.READY:break;default:O(t)}break}case m.PLAYING:{switch(t){case j.PLAYING:break;case j.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 j.READY:this.play();break;case j.STOPPED:this.prepare();break;default:O(t)}break}case m.PAUSED:{switch(t){case j.PLAYING:this.pause(),this.liveOffset.pause();break;case j.PAUSED:break;case j.READY:this.videoState.setState(j.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED);break;case j.STOPPED:this.prepare();break;default:O(t)}break}default:O(i)}},this.video=ot(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(Ae(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:L.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"),Hf);import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(ii.MediaPlayer=r.MediaPlayer,ii.Debug=r.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){P(ii.MediaPlayer,"dashjs not loaded"),P(ii.Debug,"dashjs not loaded"),this.player=ii.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(t=>(t.height&&(this.frameRatesByFrameHeight[t.height]=t.frameRate?Ar(t.frameRate+""):void 0),!0)),(this.params.format===b.DASH_WEBM||this.params.format===b.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=pf(this.player,{minInitSize:this.params.tuning.bigRequestMinInitSize,minDataSize:this.params.tuning.bigRequestMinDataSize,onError:t=>this.params.output.error$.next(t),onDownloadStream:t=>this.params.dependencies.throughputEstimator.trackStream(t)}):this.params.tuning.stripRangeHeader&&gf(this.player),mf(this.player),this.params.tuning.requestQuick&&Sf(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(j.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=f=>{e.error$.next({id:"DashIFProvider",category:L.WTF,message:"DashIFProvider internal logic error",thrown:f})},r=(f,S)=>this.subscription.add(f.subscribe(S,i));r(Wi(this.video),this.elementSize$),r(Se(this.player,"error").pipe($(f=>{const S=typeof f.error=="object"?f.error.code:f.error,g=typeof f.error=="object"?f.error.message:void 0;return{id:`DashJS#${S}`,message:g}})),e.error$),r(Se(this.player,"playbackError").pipe($(f=>({id:"DashJSPlayback",message:f.error}))),e.error$);const a=Se(this.player,"qualityChangeRendered").pipe(q(({mediaType:f})=>f==="video"),$(({newQuality:f})=>{var S;return(S=this.videoTracks.find(({bitrateInfo:g})=>g.qualityIndex===f))===null||S===void 0?void 0:S.track}));a.pipe(q(_)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(q(({to:f})=>f===j.STREAM_INITIALIZED),ge()).subscribe(()=>{this.subscription.add(qe(t.videoTrack,()=>{var f,S;const g=this.player.getQualityFor("video");return(S=(f=this.videoTracks.find(({bitrateInfo:T})=>T.qualityIndex===g))===null||f===void 0?void 0:f.track)===null||S===void 0?void 0:S.id},f=>{var S;if(J(f))return;const g=(S=this.videoTracks.find(({track:T})=>T.id===f))===null||S===void 0?void 0:S.bitrateInfo;g&&this.player.setQualityFor("video",g.qualityIndex)},{changed$:a.pipe($(f=>f==null?void 0:f.id)),onError:i}))},i)),this.subscription.add(qe(t.autoVideoTrackSwitching,()=>{var f,S,g;return(g=(S=(f=this.player.getSettings().streaming)===null||f===void 0?void 0:f.abr)===null||S===void 0?void 0:S.autoSwitchBitrate)===null||g===void 0?void 0:g.video},f=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:f}}}}),{onError:i})),r(Se(this.player,"bufferStateChanged").pipe(q(({mediaType:f})=>f==="video"),$(({state:f})=>f==="bufferStalled")),e.isBuffering$),r(Se(this.player,"fragmentLoadingStarted"),({mediaType:f,request:{url:S}})=>{var g,T;const I=this.player.getDashMetrics(),w=I.getLatestFragmentRequestHeaderValueByID(f,"X-Reused"),A=(g=I.getLatestFragmentRequestHeaderValueByID(f,"X-Delivery-Type"))!==null&&g!==void 0?g:oi.HTTP1,N=(T={1:!0,0:!1}[w])!==null&&T!==void 0?T:void 0;this.params.output.httpConnectionType$.next(A),this.params.output.httpConnectionReused$.next(N),e.hostname$.next(Ae(S))}),r(Se(this.player,"streamInitialized"),({streamInfo:{duration:f,manifestInfo:{isDynamic:S,availableFrom:g}}})=>{this.isLive$.next(S),this.availableFrom$.next(g.getTime()),S||e.duration$.next(f),this.videoTracks=[];const T=this.player.getQualityFor("video");let I;for(const w of this.player.getBitrateInfoListFor("video")){const A=w.qualityIndex.toString(10),N=_t(w),K=w.bitrate/1e3,G={width:w.width,height:w.height},U=this.frameRatesByFrameHeight[w.height];if(N){const X={id:A,quality:N,bitrate:K,size:G,fps:U};this.videoTracks.push({track:X,bitrateInfo:w}),w.qualityIndex===T&&(I=X)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:w})=>w)),I&&e.currentVideoTrack$.next(I),this.videoState.setState(j.STREAM_INITIALIZED),this.videoState.startTransitionTo(j.READY)}),r(Se(this.player,"fragmentLoadingCompleted"),({request:f})=>{if(!f.requestEndDate||!f.firstByteDate||!f.bytesLoaded)return;const S=f.requestEndDate.getTime()-f.firstByteDate.getTime(),g=f.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(g,S)}),r(x(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const f=this.params.dependencies.throughputEstimator.throughput$.getValue(),S=pi(this.videoTracks.map(({track:T})=>T),{container:this.elementSize$.getValue(),throughput:f,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),g=this.videoTracks.find(({track:T})=>T===S);g!=null&&g.bitrateInfo&&this.player.setQualityFor("video",g==null?void 0:g.bitrateInfo.qualityIndex,!1)}),r(Ze({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(q(_))}).pipe(q(({isLive:f})=>f),$(({maxSeekBackTime:f})=>-f/1e3)),this.params.output.duration$);const n=Se(this.player,"playbackTimeUpdated").pipe($(({time:f})=>f!=null?f:0));r(Ze({availableFrom:this.availableFrom$.pipe(q(_)),currentTime:n}),({availableFrom:f,currentTime:S})=>this.params.output.liveTime$.next(f+S*1e3)),r(n.pipe(q(()=>this.isLive$.getValue()===!1)),e.position$),r(Se(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),r(Se(this.player,"playbackEnded"),e.endedEvent$),r(Se(this.player,"playbackProgress").pipe($(()=>Xn(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(Se(this.player,"playbackPlaying"),()=>{this.videoState.setState(j.PLAYING),R(t.playbackState,m.PLAYING)}),r(Se(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(j.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(Se(this.player,"playbackPaused"),()=>{this.videoState.setState(j.PAUSED),R(t.playbackState,m.PAUSED)}),r(Se(this.player,"canPlay"),()=>{var f;((f=this.videoState.getTransition())===null||f===void 0?void 0:f.to)===j.READY&&this.videoState.setState(j.READY)}),r(this.isLive$,e.isLive$),r(Wi(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=x(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(xe(0));r(o,this.syncPlayback);const{playbackDuration$:u,ping$:d,connectionType$:l,connectionReused$:c}=vf(this.player);r(l,this.params.output.httpConnectionType$),r(c,this.params.output.httpConnectionReused$),r(u,this.maxSeekBackTime$),r(d.pipe(ge()),e.firstBytesEvent$),r(Se(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(Ze({isLive:this.isLive$,isShort:e.duration$.pipe($(f=>f<60))}),({isLive:f,isShort:S})=>{const g=!f&&S;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:g}}})}),r(n.pipe(q(f=>f>this.params.tuning.insufficientBufferRuleMargin),ge()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(Se(this.player,"manifestLoaded").pipe(ge()).subscribe(()=>{this.subscription.add(Se(this.player,"playbackPlaying").pipe(ge(),$t(void 0)).subscribe(e.firstFrameEvent$,i))},i)),this.subscription.add(kt(this.video,t.isLooped,i));const{volumeState$:h,looped$:p,playbackRateState$:v}=dt(this.video);this.subscription.add(nt(this.video,t.volume,h,i)),this.subscription.add(h.subscribe(e.volume$,i)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(ft(this.video,t.playbackRate,v,i))}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(j.STOPPED),R(this.params.desiredState.playbackState,m.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(j.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=Mt(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Bt.PLAYBACK_SHIFT);this.player.attachSource(r)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(j.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(j.PAUSED),this.video.pause()}destroy(){var e,t;this.subscription.unsubscribe(),this.textTracksManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(i){}this.video.remove(),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var mi=s=>{switch(s){case"mobile":return ae.Q_144P;case"lowest":return ae.Q_240P;case"low":return ae.Q_360P;case"sd":case"medium":return ae.Q_480P;case"hd":case"high":return ae.Q_720P;case"fullhd":case"full":return ae.Q_1080P;case"quadhd":case"quad":return ae.Q_1440P;case"ultrahd":case"ultra":return ae.Q_2160P}},pt=async s=>{const e=s.muted;try{await s.play()}catch(t){if(t instanceof DOMException&&(t.code===20||t.name==="AbortError"))return!1;if(e)return console.warn(t),!1;s.muted=!0;try{await s.play()}catch(i){return s.muted=!1,console.warn(i),!1}}return!0};function Te(){return he()}function eo(s){return Te()-s}function Ca(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 Gf(s,e,t){const i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Vi(s,e,t,i){const r=window.XMLHttpRequest;let a,n,o,u=!1,d=0,l,c,h=!1,p="arraybuffer",v=7e3,f=2e3,S=()=>{if(u)return;P(l);const B=eo(l);let te;if(B<f){te=f-B,setTimeout(S,te);return}f*=2,f>v&&(f=v),n&&n.abort(),n=new r,N()};const g=B=>(a=B,F),T=B=>(c=B,F),I=()=>(p="json",F),w=()=>{if(!u){if(--d>=0){S(),i&&i();return}u=!0,c&&c(),t&&t()}},A=B=>(h=B,F),N=()=>{l=Te(),n=new r,n.open("get",s);let B=0,te,ue=0;const me=()=>(P(l),Math.max(l,Math.max(te||0,ue||0)));if(a&&n.addEventListener("progress",k=>{const H=Te();a.updateChunk&&k.loaded>B&&(a.updateChunk(me(),k.loaded-B),B=k.loaded,te=H)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>w())),n.addEventListener("load",()=>{if(u)return;P(n);const k=n.status;if(k>=200&&k<300){if(n.response.byteLength&&a){const H=n.response.byteLength-B;H&&a.updateChunk&&a.updateChunk(me(),H)}c&&c(),n&&e(n.response)}else w()}),n.addEventListener("error",()=>{w()}),h){const k=()=>{P(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ue=Te(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=p,n.send(),F},F={withBitrateReporting:g,withParallel:A,withJSONResponse:I,withRetryCount:B=>(d=B,F),withRetryInterval:(B,te)=>(_(B)&&(f=B),_(te)&&(v=te),F),withTimeout:B=>(o=B,F),withFinally:T,send:N,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return F}const Yf=100,qf=2e3,jf=500;let zf=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-jf;if(t-e>qf){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>Yf&&(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 Wf{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=Te(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=Te()-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=Vi(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Te()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=Te();if(Object.keys(this.activeRequests).length>=e)return!1;const 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 Ri=1e4,Ii=3,Qf=300,Jf=2e3,Kf=6e4,Xf=10,Zf=1,ep=500;class tp{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 zf(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Ca(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=Ca(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;Boolean(e.error)&&!this.destroyed&&(t(`Video element error: ${(i=e.error)===null||i===void 0?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,i=t.buffered.length;let r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let i,r,a;const n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!i||i.bitrate>a.bitrate)&&(i=a));return r||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||_(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:i,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const n=()=>{Gf(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 Wf(Ii,Ri,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 w=a&&(!l||l===this.rep);return w||t("Not running!"),w},h=(w,A,N)=>{u&&u.abort(),u=Vi(this.urlResolver.resolve(w,!1),A,N,()=>this._retryCallback()).withTimeout(Ri).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ii).withFinally(()=>{u=null}).send()},p=(w,A,N)=>{P(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(w,!1),A,N,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},v=w=>{const A=i.playbackRate;i.playbackRate!==w&&(t(`Playback rate switch: ${A}=>${w}`),i.playbackRate=w)},f=w=>{this.lowLatency=w,t(`lowLatency changed to ${w}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)v(1);else{let w=this._getBufferSizeSec();if(this.bufferStates.length<5){v(1);return}const N=Te()-1e4;let K=0;for(let U=0;U<this.bufferStates.length;U++){const X=this.bufferStates[U];w=Math.min(w,X.buf),X.ts<N&&K++}this.bufferStates.splice(0,K),t(`update playback rate; minBuffer=${w} drop=${K} jitter=${this.sourceJitter}`);let G=w-Zf;this.sourceJitter>=0?G-=this.sourceJitter/2:this.sourceJitter-=1,G>3?v(1.15):G>1?v(1.1):G>.3?v(1.05):v(1)}},g=w=>{let A;const N=()=>A&&A.start?A.start.length:0,K=k=>A.start[k]/1e3,G=k=>A.dur[k]/1e3,U=k=>A.fragIndex+k,X=(k,H)=>({chunkIdx:U(k),startTS:K(k),dur:G(k),discontinuity:H}),F=()=>{let k=0;if(A&&A.dur){let H=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,ne=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,fe=H;this.sourceJitter>1&&(fe+=this.sourceJitter-1);let ve=A.dur.length-1;for(;ve>=0&&(fe-=A.dur[ve],!(fe<=0));--ve);k=Math.min(ve,A.dur.length-1-ne),k=Math.max(k,0)}return X(k,!0)},B=k=>{const H=N();if(!(H<=0)){if(_(k)){for(let ne=0;ne<H;ne++)if(K(ne)>k)return X(ne)}return F()}},te=k=>{const H=N(),ne=k?k.chunkIdx+1:0,fe=ne-A.fragIndex;if(!(H<=0)){if(!k||fe<0||fe-H>Xf)return t(`Resync: offset=${fe} bChunks=${H} chunk=`+JSON.stringify(k)),F();if(!(fe>=H))return X(ne-A.fragIndex,!1)}},ue=(k,H,ne)=>{d&&d.abort(),d=Vi(this.urlResolver.resolve(k,!0,this.lowLatency),H,ne,()=>this._retryCallback()).withTimeout(Ri).withRetryCount(Ii).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(k,H)=>{ue(w,ne=>{if(!c())return;A=ne;const fe=Boolean(A.lowLatency);fe!==this.lowLatency&&f(fe);let ve=0;for(let we=0;we<A.dur.length;++we)ve+=A.dur[we];ve>0&&(P(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ve/A.dur.length)),r({name:"index",zeroTime:A.zeroTime,shiftDuration:A.shiftDuration}),this.sourceJitter=A.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,A.jitter/1e3)):1,k(B(H))},()=>this._handleNetworkError())},nextChunk:te}},T=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),P(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:w=>{const{videoElement:A,logger:N}=this.params;let K=g(e.jidxUrl),G,U,X,F,B=0,te,ue,me;const k=()=>{te&&(clearTimeout(te),te=void 0);const Z=Math.max(ep,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),be=B+Z,$e=Te(),Pe=Math.min(1e4,be-$e);B=$e;const mt=()=>{d||c()&&K.seek(()=>{c()&&(B=Te(),H(),k())})};Pe>0?te=window.setTimeout(()=>{this.paused?k():mt()},Pe):mt()},H=()=>{let Z;for(;Z=K.nextChunk(F);)F=Z,Fe(Z);const be=K.nextChunk(X);if(be){if(X&&be.discontinuity){N("Detected discontinuity; restarting playback"),this.paused?k():(T(),this._initPlayerWith(e));return}we(be)}else k()},ne=(Z,be)=>{if(!c()||!this.sourceBuffer)return;let $e,Pe,mt;const Ve=ut=>{window.setTimeout(()=>{c()&&ne(Z,be)},ut)};if(this.sourceBuffer.updating)N("Source buffer is updating; delaying appendBuffer"),Ve(100);else{const ut=Te(),vt=A.currentTime;!this.paused&&A.buffered.length>1&&ue===vt&&ut-me>500&&(N("Stall suspected; trying to fix"),this._fixupStall()),ue!==vt&&(ue=vt,me=ut);const qt=this._getBufferSizeSec();if(qt>30)N(`Buffered ${qt} seconds; delaying appendBuffer`),Ve(2e3);else try{this.sourceBuffer.appendBuffer(Z),this.videoPlayStarted?(this.bufferStates.push({ts:ut,buf:qt}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),be&&be()}catch(Pt){if(Pt.name==="QuotaExceededError")N("QuotaExceededError; delaying appendBuffer"),mt=this.sourceBuffer.buffered.length,mt!==0&&($e=this.sourceBuffer.buffered.start(0),Pe=vt,Pe-$e>4&&this.sourceBuffer.remove($e,Pe-3)),Ve(1e3);else throw Pt}}},fe=()=>{U&&G&&(N([`Appending chunk, sz=${U.byteLength}:`,JSON.stringify(X)]),ne(U,function(){U=null,H()}))},ve=Z=>e.fragUrlTemplate.replace("%%id%%",Z.chunkIdx),we=Z=>{c()&&p(ve(Z),(be,$e)=>{if(c()){if($e/=1e3,U=be,X=Z,n=Z.startTS,$e){const Pe=Math.min(10,Z.dur/$e);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Pe:Pe}fe()}},()=>this._handleNetworkError())},Fe=Z=>{c()&&(P(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ve(Z),!1)))},Yt=Z=>{c()&&(e.cachedHeader=Z,ne(Z,()=>{G=!0,fe()}))};a=!0,K.seek(Z=>{if(c()){if(B=Te(),!Z){k();return}F=Z,!J(w)||Z.startTS>w?we(Z):(X=Z,H())}},w),e.cachedHeader?Yt(e.cachedHeader):h(e.headerUrl,Yt,()=>this._handleNetworkError())},stop:T,getTimestampSec:()=>n},l}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),_(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,P(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return _(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let h,p,v;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(p=this._getBufferSizeSec(),v=c/this.bitrate,p>10&&v>.8||p>15&&v>.5||p>20&&v>.3)){e(`Not switching: buffer=${Math.floor(p)}; 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,p)=>{const v=Te();if(this.chunkRateEstimator.addInterval(h,v,p)){const S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:v-h,speed:S}),!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&&eo(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,h)=>{const p=a.updateChunk(c,h);return p&&d(),p},notifySwitch:c=>{const h=Te();c<o&&(n=h),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Vi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Ri).withRetryCount(Ii).withRetryInterval(Qf,Jf).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;pt(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))},Kf))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var z;(function(s){s.STOPPED="stopped",s.MANIFEST_READY="manifest_ready",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(z||(z={}));const ip=[z.PAUSED,z.PLAYING,z.READY],sp=[z.PAUSED,z.PLAYING,z.READY];class rp{constructor(e){this.subscription=new ie,this.videoState=new de(z.STOPPED),this.representations$=new y([]),this.textTracksManager=new ze,this.maxSeekBackTime$=new y(1/0),this.zeroTime$=new y(void 0),this.liveOffset=new $r,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:L.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),p=(n=mi(c.name))!==null&&n!==void 0?n:_t(c.video),v=c.bitrate/1e3,f={...c.video};if(!p)continue;const S={id:h,quality:p,bitrate:v,size:f};l.push({track:S,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)===z.MANIFEST_READY&&this.videoState.setState(z.MANIFEST_READY);break}case"qualitySwitch":{const d=r.quality,l=(u=this.representations$.getValue().find(({representation:c})=>c===d))===null||u===void 0?void 0:u.track;this.params.output.hostname$.next(new URL(d.headerUrl,this.params.source.url).hostname),_(l)&&this.params.output.currentVideoTrack$.next(l);break}case"bandwidth":{const{size:d,duration:l}=r;this.params.dependencies.throughputEstimator.addRawSpeed(d,l);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{var r;const a=this.videoState.getState(),n=this.videoState.getTransition(),o=this.params.desiredState.playbackState.getState(),u=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${a}; videoTransition: ${JSON.stringify(n)}; desiredPlaybackState: ${o}; seekState: ${JSON.stringify(d)};`}),o===m.STOPPED){a!==z.STOPPED&&(this.videoState.startTransitionTo(z.STOPPED),this.dash.destroy(),this.video.setAttribute("src",""),this.video.load(),this.videoState.setState(z.STOPPED));return}if(!n){if(sp.includes(a)){const l=(r=this.params.desiredState.videoTrack.getTransition())===null||r===void 0?void 0:r.to;_(l)&&this.setVideoTrack(l);const c=this.params.desiredState.autoVideoTrackSwitching.getTransition();c&&this.setAutoQuality(c.to)}if((u==null?void 0:u.to)!==m.PAUSED&&d.state===V.Requested&&ip.includes(a)){this.seek(d.position-this.liveOffset.getTotalPausedTime());return}switch(a){case z.STOPPED:this.videoState.startTransitionTo(z.MANIFEST_READY),this.dash.attachSource(Mt(this.params.source.url));return;case z.MANIFEST_READY:this.videoState.startTransitionTo(z.READY),this.prepare();break;case z.READY:if(o===m.PAUSED)this.videoState.setState(z.PAUSED);else if(o===m.PLAYING){this.videoState.startTransitionTo(z.PLAYING);const l=u==null?void 0:u.from;l&&l===m.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(z.PAUSED)})}return;case z.PLAYING:o===m.PAUSED&&(this.videoState.startTransitionTo(z.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case z.PAUSED:o===m.PLAYING&&(this.videoState.startTransitionTo(z.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(z.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return O(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:L.WTF,message:"DashLiveProvider internal logic error",thrown:r})};x(this.videoState.stateChangeStarted$.pipe($(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe($(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=ot(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.hostname$.next(Ae(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=dt(this.video);this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===z.READY&&this.videoState.setState(z.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===V.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(z.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(pe(),$(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Ze({zeroTime:this.zeroTime$.pipe(q(_)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(kt(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(ft(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(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:r}})=>{const a=r&&nf(r);this.dash.setMaxAutoQuality(a)})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case z.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(m.STOPPED);break;case z.MANIFEST_READY:case z.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 z.PAUSED:this.params.desiredState.playbackState.setState(m.PAUSED);break;case z.PLAYING:this.params.desiredState.playbackState.setState(m.PLAYING);break;default:return O(r.to)}},t)).add(x(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(xe(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const e=new tp({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,i,r,a,n;const o=this.representations$.getValue(),u=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),d=(r=(i=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||i===void 0?void 0:i.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),l=!d&&_(u)?u:(a=pi(o.map(({track:h})=>h),{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()}))===null||a===void 0?void 0:a.id,c=(n=o.find(({track:h})=>h.id===l))===null||n===void 0?void 0:n.representation;P(c,"Representations missing"),this.dash.startPlay(c,d),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(l),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(d)}setVideoTrack(e){var t;const i=(t=this.representations$.getValue().find(({track:r})=>r.id===e))===null||t===void 0?void 0:t.representation;P(i,`No such representation ${e}`),this.dash.switchByName(i.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=-e,i=t<=this.maxSeekBackTime$.getValue()?t:0;this.params.output.position$.next(e/1e3),this.liveOffset.resetTo(i),this.dash.reinit(Mt(this.params.source.url,i))}}var to=s=>{var e,t;const i=s.get("X-Delivery-Type"),r=s.get("X-Reused"),a=i===null?oi.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}},yt=(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 ap=s=>{const e=document.createElement("a");return e.href=s,e.origin},np=s=>{const e=document.createElement("a");return e.href=s,e.host};class io{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(P(this._xhr),((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=fi(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(np(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 Qi{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 p=f=>{r(Qi._str2ua(f.substr(u))),u=f.length};let v=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(v=Ft(v)),this._lastXhr=new io(v,e.failoverHosts,f=>{this._lastXhr=void 0,p(f);const S=Date.now()-d;this._params.onBandwidthChange({size:f.length,duration:S,speed:8*f.length/(S/1e3)}),this._onDashCallback("loading",{size:f.length,done:!0}),a==null||a()},f=>{if(f.length-u>o&&p(f),c===0){c=Date.now();return}h=f.length-l;const S=Date.now()-c;h>=100*1024&&S>=1e3&&(this._params.onBandwidthChange({size:h,duration:S,speed:8*h/(S/1e3)}),h=0,l=f.length,c=Date.now()),this._onDashCallback("loading",{size:f.length,done:!1})},n,(f,S,g)=>this._params.onError(f,S,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=Qi._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 op{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=Ft(i)),new io(i,t,r=>{this.attachManifest(r,t,ap(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,p,v,f,S,g,T,I,w,A,N,K,G,U,X,F,B;const te=d.getElementsByTagName("SegmentBase")[0],ue=te&&n(te,"indexRange").split("-"),me=te&&te.getElementsByTagName("Initialization")[0],k=me&&n(me,"range").split("-");if(!k||!ue){const Fe=d.parentElement;if((Fe==null?void 0:Fe.getAttribute("contentType"))==="text"){const Yt=(l=d.getAttribute("id"))!==null&&l!==void 0?l:void 0,Z=(i?i+"/":"")+((v=(p=(h=(c=d.getElementsByTagName("BaseURL"))===null||c===void 0?void 0:c[0])===null||h===void 0?void 0:h.childNodes)===null||p===void 0?void 0:p[0])===null||v===void 0?void 0:v.data),be=(f=Fe.getAttribute("lang"))!==null&&f!==void 0?f:void 0;Z&&u.push({id:Yt,url:Z,language:be})}return}const H=.1,ne=Number((S=d.attributes.getNamedItem("bandwidth"))===null||S===void 0?void 0:S.value),fe=(i?i+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ve;const we=(T=(g=d.attributes.getNamedItem("frameRate"))===null||g===void 0?void 0:g.value)!==null&&T!==void 0?T:void 0;ve=we?Ar(we):void 0,o.push({width:Number((I=d.attributes.getNamedItem("width"))===null||I===void 0?void 0:I.value),height:Number((w=d.attributes.getNamedItem("height"))===null||w===void 0?void 0:w.value),bandwidth:ne,baseURL:fe,failoverHosts:t,indexFrom:Number(ue[0]),indexTo:Number(ue[1]),initFrom:Number(k[0]),initTo:Number(k[1]),codecs:(N=(A=d.attributes.getNamedItem("codecs"))===null||A===void 0?void 0:A.value)!==null&&N!==void 0?N:void 0,mimeType:(G=(K=d.attributes.getNamedItem("mimeType"))===null||K===void 0?void 0:K.value)!==null&&G!==void 0?G:void 0,fps:ve,bufferSize:H*ne/8,bufferLength:H,name:(X=(U=d.attributes.getNamedItem("okQuality"))===null||U===void 0?void 0:U.value)!==null&&X!==void 0?X:void 0,id:(B=(F=d.attributes.getNamedItem("id"))===null||F===void 0?void 0:F.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");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(this._representations)}_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 p=d+(n.getUint32(a,!1)&2147483647),v=u+n.getUint32(a+4,!1);a+=12,e.refs.push({fromTime:u/o,toTime:v/o,fromOffset:d,toOffset:p-1}),d=p,u=v}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 p=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),p)}const l=this._appendVector[String(d.fromTime)];l!==r&&(r=l,this._params.onRepresentationPlay(l));let c;if(this._findRef(d.toTime)){const p=this._buffer.getByTime(this._video.currentTime);if(!p){this._onDashCallback("buffering");return}c=p.to-this._video.currentTime,c<e.bufferLength&&(this._onDashCallback("buffering"),a!==p.to&&(a=p.to,window.setTimeout(()=>{try{const v=this._buffer.getNextWithGap(p);v&&(this._video.currentTime=v.from)}catch(v){throw this._params.onError("GapSyncError",`Seek Error ${String(v)}`,v),v}},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 Qi({mediaSource:i,sourceBuffer:d,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(d){throw this._params.onError("DashSourceOpen",`Source open exception ${String(d)}`,d),d}this._loadInitAndSidx(e),i.duration||(i.duration=this._duration),this._loopTimeout||o(),i.removeEventListener("sourceopen",u),i.removeEventListener("webkitsourceopen",u)};i.addEventListener("sourceopen",u,!1),i.addEventListener("webkitsourceopen",u,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener("waiting",()=>{const d=this._video&&this._video.played.length;d&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(d-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,i=!1,r=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const a=this._findRef(t);if(a){if(i){this._isLastRef(a)&&t>=a.toTime&&(t=a.fromTime);const n=this._findRef(this._video.currentTime),o=Math.abs(this._video.currentTime-t),u=r||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||a===n||o<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=u?t:a.fromTime}this._appendVector[String(a.fromTime)]=e,this._stream.load(e,a.fromOffset,a.toOffset,(n,o)=>this._stream.append(n,o),()=>{this._lastLoadOffset=a.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},n=>this._params.onResponseHeaders(n),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const i=this._buffer.getByTime(this._video.currentTime),r=this._findRef(this._video.currentTime);if(!i||!r){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const a=.1;if(r.toTime<i.to+a){const n=this._findRef(r.toTime);n&&n.toTime<i.to+a?(this._buffer.smartRemove(r.fromTime-a,n.toTime+a,(o,u)=>this._stream.remove(o,u)),this._loadRef(e,n.toTime)):(this._buffer.smartRemove(r.fromTime-a,r.toTime+a,(o,u)=>this._stream.remove(o,u)),this._loadRef(e,r.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t){this._stream&&this._buffer.getByTime(e)?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0,t)}updateRefsForCurrentTime(){const e=this._video.currentTime;(!this._stream||J(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return;if(Array.isArray(i)&&i.length===0){this._params.onError("emptyrefs","Empty refs");return}let r;for(let a=0;a<i.length;a++){const n=i[a];if(n.fromTime<=e&&n.toTime>e)return n;n.fromTime>e&&(!r||n.fromTime<r.fromTime)&&(r=n)}if(!r){const a=i[i.length-1];if(e>a.toTime)return a}return r}_isLastRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return!1;const r=i[i.length-1];return e.fromTime===r.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const i=this._video.buffered.start(t),r=this._video.buffered.end(t);if(e>i&&e<r)return Math.round(r*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var W;(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"})(W||(W={}));const dp=[W.PAUSED,W.PLAYING];class up{constructor(e){this.videoState=new de(W.STOPPED),this.subscription=new ie,this.representations$=new y([]),this.currentRepresentation$=new y(void 0),this.textTracksManager=new ze,this.elementSize$=new y(void 0),this.dashLiteEvents={idxRequestPing$:new C,responseHeaders$:new C,manifestReady$:new C,representationPlay$:new C,error$:new C},this.handleManifestReady=t=>{var i,r,a;const n=[];for(const o of t){const u=(r=(i=o.name)!==null&&i!==void 0?i:o.id)!==null&&r!==void 0?r:o.height.toString(10),d=(a=o.name&&mi(o.name))!==null&&a!==void 0?a:_t(o),l=o.bandwidth/1e3,c={width:o.width,height:o.height},h=o.fps;if(!d)continue;const p={id:u,quality:d,bitrate:l,size:c,fps:h};n.push({track:p,representation:o})}this.representations$.next(n),this.params.output.availableVideoTracks$.next(n.map(({track:o})=>o)),this.videoState.setState(W.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var i;const r=(i=this.representations$.getValue().find(({representation:a})=>a===t))===null||i===void 0?void 0:i.track;r&&(this.params.output.currentVideoTrack$.next(r),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(r.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return P(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(n)};`}),r===m.STOPPED){t!==W.STOPPED&&(this.videoState.startTransitionTo(W.STOPPED),this.dash.destroy(),this.video.setAttribute("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(W.STOPPED),R(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(!i)switch((a==null?void 0:a.to)!==m.PAUSED&&n.state===V.Requested&&dp.includes(t)&&this.seek(n.position,n.forcePrecise),t){case W.STOPPED:this.videoState.startTransitionTo(W.MANIFEST_LOADED),this.prepare();return;case W.MANIFEST_LOADED:this.videoState.startTransitionTo(W.INITIAL_REPRESENTATION_SELECTED);return;case W.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(W.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case W.METADATA_LOADED:this.videoState.startTransitionTo(W.READY),this.dash.updateRefsForCurrentTime();return;case W.READY:r===m.READY?R(this.params.desiredState.playbackState,m.READY):r===m.PAUSED?(this.videoState.setState(W.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED)):r===m.PLAYING&&(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed());return;case W.PLAYING:r===m.PAUSED?(this.videoState.startTransitionTo(W.PAUSED),this.video.pause()):(a==null?void 0:a.to)===m.PLAYING&&R(this.params.desiredState.playbackState,m.PLAYING);return;case W.PAUSED:r===m.PLAYING?(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===m.PAUSED&&R(this.params.desiredState.playbackState,m.PAUSED);return;default:return O(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),x(this.videoState.stateChangeStarted$.pipe($(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe($(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=ot(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(Ae(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Tf(this.video),this.dash=new op({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:t=>this.dashLiteEvents.manifestReady$.next(t),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:L.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:L.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=dt(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.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(a.seeking$.subscribe(()=>{J(this.params.desiredState.seekState.getState().state!==V.Applying)&&(this.videoState.getState()===W.PLAYING||this.videoState.getState()===W.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(kt(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(ft(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),n(Wi(this.video),this.elementSize$),this.subscription.add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===W.READY&&this.videoState.setState(W.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED)})).add(a.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING),R(this.params.desiredState.playbackState,m.PLAYING)},i)).add(a.loadedMetadata$.subscribe(()=>{this.videoState.setState(W.METADATA_LOADED)},i)).add(a.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},i)).add(this.dashLiteEvents.error$.pipe($(({id:o,message:u,thrown:d})=>({id:`DashLite_${o}`,category:L.WTF,message:u,thrown:d}))).subscribe(this.params.output.error$)).add(x(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$,this.params.output.element$,this.elementSize$,M(this.video,"progress")).pipe($(()=>{var o,u,d;const l=this.currentRepresentation$.getValue(),c=this.representations$.getValue(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition(),p=this.params.desiredState.videoTrack.getState(),v=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),f=this.elementSize$.getValue(),S=r();h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to);let g;if(!S&&_(p))g=p;else{const T=yt(this.video.buffered,this.video.currentTime*1e3),I=S?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,w=Math.min(T/I,1);g=(u=pi(c.map(({track:A})=>A),{container:f,throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:w,playbackRate:this.video.playbackRate,current:(o=c.find(({representation:A})=>A===l))===null||o===void 0?void 0:o.track}))===null||u===void 0?void 0:u.id}return _(g)?(d=c.find(({track:T})=>T.id===g))===null||d===void 0?void 0:d.representation:void 0}),pe()).subscribe(this.currentRepresentation$,i)).add(Ze({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(q(o=>o.to===W.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(q(_))}).pipe(ge()).subscribe(()=>this.videoState.setState(W.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(q(_),pe((o,u)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?o.height<=u.height:o===u)).subscribe(o=>{const u=yt(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(Ae(o.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:u,reused:d}=to(o);this.params.output.httpConnectionType$.next(u),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(ge(),$t(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(q(_)).subscribe(this.handleRepresentationPlay,i)).add(x(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(xe(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}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 O(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){pt(this.video).then(e=>{e||(this.videoState.setState(W.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED,!0))})}}var De;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(De||(De={}));var Ji;(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"})(Ji||(Ji={}));var Le;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(Le||(Le={}));var ee;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(ee||(ee={}));var Vt;(function(s){s.MP4="mp4",s.WEBM="webm"})(Vt||(Vt={}));var or=(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 lp=(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)},cp=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",xa=cp?lp:window.requestIdleCallback;var Cs,xs;let so=!1;try{so=Kn()&&parseInt((xs=(Cs=navigator.userAgent.match(/Version\/(\d+)/))===null||Cs===void 0?void 0:Cs[1])!==null&&xs!==void 0?xs:"",10)<16}catch(s){console.error(s)}class hp{constructor(e){this.bufferFull$=new C,this.error$=new C,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const i=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!i),this.currentTask=null}this.queue.length&&this.pull()}catch(i){this.error$.next({id:"BufferTaskQueueUnknown",category:L.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i;so&&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)}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"&&i==="remove"||this.error$.next({id:`BufferTaskQueue:${i}`,category:L.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:O(t)}}}var Oa=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};const ro=new TextDecoder("ascii"),ao=s=>{let e=0,t=s.getUint32(e);e+=4;const i=new DataView(s.buffer,s.byteOffset+e,4),r=ro.decode(i);e+=4,t===0?t=1/0:t===1&&(e+=8,t=1/0);const a=Math.min(t,s.byteLength)-e,n=new DataView(s.buffer,s.byteOffset+e,a);return{id:r,size:t,contents:n}},fp=s=>ro.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",pp=(s,e,t)=>{const i=ao(s),r=[];let a=0;const n=()=>{const f=i.contents.getUint32(a);return a+=4,f};if((n()&4278190080)!==0)throw new SyntaxError("Unsupported sidx version");n();const d=n(),l=n(),c=n(),h=n()&4294967295;let p=l/d*1e3,v=(t?t.to+1:s.byteOffset+s.byteLength)+c;for(let f=0;f<h;f++){const S=n(),g=S>>>31,T=S<<1>>>1,I=n();if(n(),g!==0)throw new Error("Unsupported multilevel sidx");const w=I/d*1e3;r.push({status:ee.NONE,time:{from:p,to:p+w},byte:{from:v,to:v+T-1}}),p+=w,v+=T}return r},mp=s=>{let e=0,t=!1,i=!1;for(;e<=s.byteLength&&!t;){const r=new DataView(s.buffer,s.byteOffset+e);try{const a=ao(r);if(i||(i=a.id==="mdat"),e+a.size<=s.byteLength)e+=a.size;else break}catch(a){t=!0}}return e>0&&e<=s.byteLength&&i?new DataView(s.buffer,s.byteOffset,e):null},vp={validateData:fp,parseInit:()=>null,getIndexRange:()=>{},parseSegments:pp,parseFeedableSegmentChunk:mp};var E;(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.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"})(E||(E={}));var D;(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"})(D||(D={}));const Na={[E.EBML]:{type:D.Master},[E.EBMLVersion]:{type:D.UnsignedInteger},[E.EBMLReadVersion]:{type:D.UnsignedInteger},[E.EBMLMaxIDLength]:{type:D.UnsignedInteger},[E.EBMLMaxSizeLength]:{type:D.UnsignedInteger},[E.DocType]:{type:D.String},[E.DocTypeVersion]:{type:D.UnsignedInteger},[E.DocTypeReadVersion]:{type:D.UnsignedInteger},[E.Void]:{type:D.Binary},[E.Segment]:{type:D.Master},[E.SeekHead]:{type:D.Master},[E.Seek]:{type:D.Master},[E.SeekID]:{type:D.Binary},[E.SeekPosition]:{type:D.UnsignedInteger},[E.Info]:{type:D.Master},[E.TimestampScale]:{type:D.UnsignedInteger},[E.Duration]:{type:D.Float},[E.Tracks]:{type:D.Master},[E.Chapters]:{type:D.Master},[E.Cluster]:{type:D.Master},[E.Timestamp]:{type:D.UnsignedInteger},[E.SilentTracks]:{type:D.Master},[E.SilentTrackNumber]:{type:D.UnsignedInteger},[E.Position]:{type:D.UnsignedInteger},[E.PrevSize]:{type:D.UnsignedInteger},[E.SimpleBlock]:{type:D.Binary},[E.BlockGroup]:{type:D.Master},[E.EncryptedBlock]:{type:D.Binary},[E.Attachments]:{type:D.Master},[E.Tags]:{type:D.Master},[E.Cues]:{type:D.Master},[E.CuePoint]:{type:D.Master},[E.CueTime]:{type:D.UnsignedInteger},[E.CueTrackPositions]:{type:D.Master},[E.CueTrack]:{type:D.UnsignedInteger},[E.CueClusterPosition]:{type:D.UnsignedInteger},[E.CueRelativePosition]:{type:D.UnsignedInteger},[E.CueDuration]:{type:D.UnsignedInteger},[E.CueBlockNumber]:{type:D.UnsignedInteger},[E.CueCodecState]:{type:D.UnsignedInteger},[E.CueReference]:{type:D.Master},[E.CueRefTime]:{type:D.UnsignedInteger}},no=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=Ki(s,t),r=i in Na,a=r?Na[i].type:D.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=Ki(u),c=d*2**((o-1)*8)+l,h=t+o;let p;return h+c>s.byteLength?p=new DataView(s.buffer,s.byteOffset+h):p=new DataView(s.buffer,s.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:p,valueSize:c}},Ki=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{const t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Xe=(s,e)=>{switch(e){case D.SignedInteger:return s.getInt8(0);case D.UnsignedInteger:return Ki(s);case D.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case D.String:return new TextDecoder("ascii").decode(s);case D.UTF8:return new TextDecoder("utf-8").decode(s);case D.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case D.Master:return s;case D.Binary:return s;default:O(e)}},vi=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=no(i);if(!e(r))return;r.type===D.Master&&vi(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},Sp=s=>{if(s.getUint32(0)!==E.EBML)return!1;let e,t,i;const r=no(s);return vi(r.value,({tag:a,type:n,value:o})=>(a===E.EBMLReadVersion?e=Xe(o,n):a===E.DocType?t=Xe(o,n):a===E.DocTypeReadVersion&&(i=Xe(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},oo=[E.Info,E.SeekHead,E.Tracks,E.Chapters,E.Cluster,E.Cues,E.Attachments,E.Tags],gp=[E.Timestamp,E.SilentTracks,E.SilentTrackNumber,E.Position,E.PrevSize,E.SimpleBlock,E.BlockGroup,E.EncryptedBlock],bp=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,d;return vi(s,({tag:l,type:c,value:h,valueSize:p})=>{if(l===E.SeekID){const v=Xe(h,c);d=Ki(v)}else l!==E.SeekPosition&&(d=void 0);return l===E.Segment?(e=h.byteOffset,t=h.byteOffset+p):l===E.Info?a=!0:l===E.SeekHead?n=!0:l===E.TimestampScale?i=Xe(h,c):l===E.Duration?r=Xe(h,c):l===E.SeekPosition&&d===E.Cues?u=Xe(h,c):a&&n&&oo.includes(l)&&(o=!0),!o}),P(e,"Failed to parse webm Segment start"),P(t,"Failed to parse webm Segment end"),P(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:u}},yp=s=>{if(J(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Tp=(s,e)=>{let t=!1,i=!1;const r=o=>_(o.time)&&_(o.position),a=[];let n;return vi(s,({tag:o,type:u,value:d})=>{switch(o){case E.Cues:t=!0;break;case E.CuePoint:n&&r(n)&&a.push(n),n={};break;case E.CueTime:n&&(n.time=Xe(d,u));break;case E.CueTrackPositions:break;case E.CueClusterPosition:n&&(n.position=Xe(d,u));break;default:t&&oo.includes(o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{const{time:d,position:l}=o,c=a[u+1];return{status:ee.NONE,time:{from:d,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},Ep=s=>{let e=0,t=!1;try{vi(s,i=>i.tag===E.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):gp.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[E.SimpleBlock,E.BlockGroup,E.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},$p={validateData:Sp,parseInit:bp,getIndexRange:yp,parseSegments:Tp,parseFeedableSegmentChunk:Ep};class Ba{constructor(e,t,i,r,{fetcher:a,tuning:n,getCurrentPosition:o,compatibilityMode:u=!1}){switch(this.onLastSegment$=new y(!1),this.fullyBuffered$=new y(!1),this.playingRepresentation$=new y(void 0),this.error$=new C,this.gaps=[],this.subscription=new ie,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new Tt,this.destroyAbortController=new Tt,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=Be(this.destroyAbortController.signal,async function*(d){const l=this.representations.get(d);P(l,`Cannot find representation ${d}`),this.playingRepresentationId=d,this.downloadingRepresentationId=d,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${l.mime}; codecs="${l.codecs}"`),this.sourceBufferTaskQueue=new hp(this.sourceBuffer),this.subscription.add(M(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},v=>this.error$.next({id:"SegmentEjection",category:L.WTF,message:"Error when trying to clear segments ejected by browser",thrown:v}))),this.subscription.add(M(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:L.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(v=>{if(!this.sourceBuffer)return;const f=Math.min(this.bufferLimit,Oa(this.sourceBuffer.buffered)*.8);this.bufferLimit=f,this.pruneBuffer(this.getCurrentPosition(),v)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(v=>this.error$.next(v))),yield this.loadInit(l,"high",!0);const c=this.initData.get(l.id),h=this.segments.get(l.id);if(P(c,"No init buffer for starting representation"),P(h,"No segments for starting representation"),!(c instanceof ArrayBuffer))return;let p=0;for(const v of h)v.time.from-p>0&&this.gaps.push({representation:l.id,from:p,to:v.time.from}),p=v.time.to;_(l.duration)&&l.duration-p>0&&this.gaps.push({representation:l.id,from:p,to:l.duration}),yield this.sourceBufferTaskQueue.append(c,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId)}.bind(this)),this.switchTo=Be(this.destroyAbortController.signal,async function*(d){if(d===this.downloadingRepresentationId||d===this.switchingToRepresentationId)return;this.switchingToRepresentationId=d;const l=this.representations.get(d);P(l,`No such representation ${d}`);let c=this.initData.get(d);if(J(c)?yield this.loadInit(l,"high",!1):c instanceof Promise&&(yield c),c=this.initData.get(d),!c||!(c instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=d,this.abort(),yield this.sourceBufferTaskQueue.append(c,this.downloadAbortController.signal);const h=this.getCurrentPosition();_(h)&&this.maintain(h)}.bind(this)),this.fetcher=a,this.tuning=n,this.compatibilityMode=u,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.container=i,i){case Vt.MP4:this.containerParser=vp;break;case Vt.WEBM:this.containerParser=$p;break;default:O(i)}this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.representations=new Map(r.map(d=>[d.id,d])),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 Tt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(J(e)||J(this.downloadingRepresentationId)||J(this.playingRepresentationId)||J(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(P(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const r=i.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const l=yt(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)&&Oa(this.sourceBuffer.buffered)>=this.bufferLimit){const d=yt(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=Je(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===ee.FED&&!o.length&&yt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const u=Je(i,-1);u&&u.status===ee.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===u))}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;this.initData.clear(),this.segments.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(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){const r=e.findIndex(({status:c,time:{from:h,to:p}},v)=>{const f=h<=i&&p>=i,S=h>i||f||v===0&&i===0,g=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&h<=i+g||p<=i+g;return(c===ee.NONE||c===ee.PARTIALLY_EJECTED&&S&&T&&this.sourceBuffer&&!or(this.sourceBuffer.buffered,i))&&S&&T});if(r===-1)return[];if(t!==Le.BYTE_RANGE)return e.slice(r,r+1);const a=e;let n=0,o=0;const u=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=d||o<=l);c++){const h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status===ee.NONE||h.status===ee.PARTIALLY_EJECTED)u.push(h);else break}return u}async loadSegments(e,t,i="auto"){if(!e.length)return;let r,a,n=e;const{type:o}=t.segmentReference;switch(o){case Le.BYTE_RANGE:{r=t.segmentReference.url,a={from:Je(e,0).byte.from,to:Je(e,-1).byte.to};break}case Le.TEMPLATE:{const d=Je(e,0);r=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:O(o)}for(const d of n)d.status=ee.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:u}=this.downloadAbortController;if(this.failedDownloads&&(await Be(u,async function*(){const d=Nr(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,d))}.bind(this))(),u.aborted))for(const d of this.activeSegments)e.includes(d.segment)&&this.abortSegment(d.segment);return void this.fetcher.fetch(r,{range:a,onProgress:(d,l)=>{if(!u.aborted)try{this.onSomeDataLoaded(d,t.id,a?a.from:0,l,u)}catch(c){this.error$.next({id:"SegmentFeeding",category:L.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}},signal:u,priority:i}).then(()=>this.failedDownloads=0,d=>{for(const l of this.activeSegments)e.includes(l.segment)&&this.abortSegment(l.segment);this.onSegmentDownloadError(d)})}onSegmentDownloadError(e){var t;let i=!1;const r=this.getCurrentPosition();this.sourceBuffer&&_(r)&&(i=yt((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:L.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),c.segment.status=ee.FED,"size"in c.segment&&(c.segment.size=c.fedBytes);for(const p of this.representations.values())if(p.id!==t)for(const v of(h=this.segments.get(p.id))!==null&&h!==void 0?h:[])v.status===ee.FED&&v.time.from===c.segment.time.from&&v.time.to===c.segment.time.to&&(v.status=ee.NONE);this.activeSegments.delete(c),this.detectGapsWhenIdle(t,[c.segment])},u=this.representations.get(t);if(!u)return;const d=u.segmentReference.type,l=e.byteLength;for(const c of this.activeSegments){const{segment:h}=c,p=d===Le.BYTE_RANGE,v=p?h.byte.to-h.byte.from+1:l;if(c.representationId!==t||!(!p||h.byte.from>=i&&h.byte.to<i+e.byteLength))continue;if(a.aborted){n();continue}const S=p?h.byte.from-i:0,g=p?h.byte.to-i:e.byteLength,T=S<r,I=g<=r;if(h.status===ee.DOWNLOADING&&T&&I){h.status=ee.DOWNLOADED,this.activeSegments.delete(c);const w=new DataView(e.buffer,e.byteOffset+S,v);this.sourceBufferTaskQueue.append(w,a).then(A=>A&&!a.aborted?o(c):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&T&&(c.loadedBytes=Math.min(v,r-S),c.loadedBytes>c.feedingBytes)){const w=new DataView(e.buffer,e.byteOffset+S+c.feedingBytes,c.loadedBytes-c.feedingBytes),A=c.loadedBytes===v?w:this.containerParser.parseFeedableSegmentChunk(w);A!=null&&A.byteLength&&(h.status=ee.PARTIALLY_FED,c.feedingBytes+=A.byteLength,this.sourceBufferTaskQueue.append(A,a).then(N=>{if(a.aborted)n();else if(N)c.fedBytes+=A.byteLength,c.fedBytes===v&&o(c);else{if(c.feedingBytes<v)return;n()}}))}}}abortSegment(e){e.status===ee.PARTIALLY_FED||e.status===ee.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=ee.NONE),e.status=ee.PARTIALLY_EJECTED):e.status=ee.NONE;for(const t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);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=xa(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Be(this.destroyAbortController.signal,async function*(){const o=Nr(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(o=>{if(!o)return;const{dataView:u,segments:d}=o,l=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,l),this.segments.set(e.id,d)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:L.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||J(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,n=-1/0,o=!1;const u=d=>{var l;a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const c="size"in d?(l=d.size)!==null&&l!==void 0?l:0:d.byte.to-d.byte.from;r+=c};for(const d of this.segments.values())for(const l of d){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;l.status===ee.FED&&u(l)}if(o=isFinite(a)&&isFinite(n),!o){r=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const l of d){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;l.status===ee.FED&&u(l)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const l=this.sourceBuffer.buffered.start(d)*1e3,c=this.sourceBuffer.buffered.end(d)*1e3;for(const h of this.segments.values())for(const p of h)if(p.status===ee.NONE&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)){a=l,n=c;break}}if(o=isFinite(a)&&isFinite(n),!o&&i){r=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const l of this.segments.values())for(const c of l)c.time.from>e+d&&c.status===ee.FED&&u(c)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}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=xa(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:L.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(J(this.sourceBuffer)||J(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}const t=1;for(const i of this.segments.values())for(const r of i){const{status:a}=r;if(a!==ee.FED&&a!==ee.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(l=>l.from-t<=n&&l.to+t>=o),d=e.filter(l=>n>=l.from-t&&n<=l.to+t||o>=l.from-t&&o<=l.to+t);u||(d.length===1?r.status=ee.PARTIALLY_EJECTED:r.status=ee.NONE)}}}var Nt;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(Nt||(Nt={}));class Ap{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new y(void 0),this.lastConnectionReused$=new y(void 0),this.lastRequestFirstBytes$=new y(void 0),this.abortAllController=new Tt,this.subscription=new ie,this.fetchManifest=Be(this.abortAllController.signal,async function*(r){let a=r;this.requestQuic&&(a=Ft(a));const n=yield Ut(a,{signal:this.abortAllController.signal}).catch(si);return n?(this.onHeadersReceived(n.headers),n.text()):null}.bind(this)),this.fetch=Be(this.abortAllController.signal,async function*(r,{rangeMethod:a=this.compatibilityMode?Nt.HEADER:Nt.PARAM,range:n,onProgress:o,priority:u="auto",signal:d,measureThroughput:l=!0}={}){var c,h,p,v;let f=r;const S=new Headers;if(n)switch(a){case Nt.HEADER:{S.append("Range",`bytes=${n.from}-${n.to}`);break}case Nt.PARAM:{const k=new URL(f,location.href);k.searchParams.append("bytes",`${n.from}-${n.to}`),f=k.toString();break}default:O(a)}this.requestQuic&&(f=Ft(f));let g=this.abortAllController.signal;if(d){const k=new Tt;if(this.subscription.add(x(M(this.abortAllController.signal,"abort"),M(d,"abort")).subscribe(()=>{try{k.abort()}catch(H){si(H)}})),this.abortAllController.signal.aborted||d.aborted)try{k.abort()}catch(H){si(H)}g=k.signal}const T=he(),I=yield Ut(f,{priority:u,headers:S,signal:g}).catch(si),w=he();if((c=this.throughputEstimator)===null||c===void 0||c.addRawRtt(w-T),!I)return null;if(!I.ok||!I.body)return Promise.reject(new Error(`Fetch error ${I.status}: ${I.statusText}`));this.onHeadersReceived(I.headers);const A=parseInt((h=I.headers.get("Content-Length"))!==null&&h!==void 0?h:"",10)||n&&n.to-n.from+1||NaN;if(!A){const k=yield I.arrayBuffer();return(p=this.throughputEstimator)===null||p===void 0||p.addRawSpeed(k.byteLength,he()-w),o==null||o(new DataView(k),k.byteLength),k}if(!o&&!l)return I.arrayBuffer();const[N,K]=I.body.tee(),G=N.getReader();l&&((v=this.throughputEstimator)===null||v===void 0||v.trackStream(K));let U=0;const X=new ArrayBuffer(A),F=new Uint8Array(X),B=new DataView(X);let te=!1;const ue=k=>{te=!0,si(k)},me=Be(g,async function*({done:k,value:H}){U===0&&this.lastRequestFirstBytes$.next(he()-T),!g.aborted&&(k?o==null||o(B,U):H&&(F.set(H,U),U+=H.byteLength,o==null||o(B,U),yield G==null?void 0:G.read().then(me,ue)))}.bind(this));return yield G==null?void 0:G.read().then(me,ue),te?null:X}.bind(this)),this.fetchByteRangeRepresentation=Be(this.abortAllController.signal,async function*(r,a,n){var o;if(r.type!==Le.BYTE_RANGE)return null;const{from:u,to:d}=r.initRange;let l=u,c=d,h=!1,p,v;r.indexRange&&(p=r.indexRange.from,v=r.indexRange.to,h=d+1===p,h&&(l=Math.min(p,u),c=Math.max(v,d))),l=Math.min(l,0);const f=yield this.fetch(r.url,{range:{from:l,to:c},priority:n,measureThroughput:!1});if(!f)return null;const S=new DataView(f,u-l,d-l+1);if(!a.validateData(S))throw new Error("Invalid media file");const g=a.parseInit(S),T=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(g);if(!T)throw new ReferenceError("No way to load representation index");let I;if(h)I=new DataView(f,T.from-l,T.to-T.from+1);else{const A=yield this.fetch(r.url,{range:T,priority:n,measureThroughput:!1});if(!A)return null;I=new DataView(A)}const w=a.parseSegments(I,g,T);return{dataView:new DataView(f),segments:w}}.bind(this)),this.fetchTemplateRepresentation=Be(this.abortAllController.signal,async function*(r,a){if(r.type!==Le.TEMPLATE)return null;const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield this.fetch(n,{priority:a,measureThroughput:!1});return o?{segments:r.segments.map(d=>({...d,status:ee.NONE,size:void 0})),dataView:new DataView(o)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=to(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var r,a;const{type:n}=e;switch(n){case Le.BYTE_RANGE:return(r=await this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case Le.TEMPLATE:return(a=await this.fetchTemplateRepresentation(e,i))!==null&&a!==void 0?a:null;default:O(n)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const si=s=>{if(!(s instanceof DOMException)||!(s.name==="AbortError"||s.code===20))throw s};var wp=At,_p=Zi,kp=Ue,Pp=kp("match"),Rp=function(s){var e;return wp(s)&&((e=s[Pp])!==void 0?!!e:_p(s)=="RegExp")},Ip=as,Dp=String,Lp=function(s){if(Ip(s)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return Dp(s)},Cp=wt,xp=function(){var s=Cp(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},Op=rt,Np=at,Bp=hr,Mp=xp,Ma=RegExp.prototype,Up=function(s){var e=s.flags;return e===void 0&&!("flags"in Ma)&&!Np(s,"flags")&&Bp(Ma,s)?Op(Mp,s):e},_r=st,Fp=is,Vp=Math.floor,Os=_r("".charAt),Hp=_r("".replace),Ns=_r("".slice),Gp=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Yp=/\$([$&'`]|\d{1,2})/g,qp=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=Yp;return r!==void 0&&(r=Fp(r),u=Gp),Hp(a,u,function(d,l){var c;switch(Os(l,0)){case"$":return"$";case"&":return s;case"`":return Ns(e,0,t);case"'":return Ns(e,n);case"<":c=r[Ns(l,1,-1)];break;default:var h=+l;if(h===0)return d;if(h>o){var p=Vp(h/10);return p===0?d:p<=o?i[p-1]===void 0?Os(l,1):i[p-1]+Os(l,1):d}c=i[h-1]}return c===void 0?"":c})},jp=rs,zp=rt,kr=st,Ua=ur,Wp=Oe,Qp=es,Jp=Rp,Ct=Lp,Kp=ts,Xp=Up,Zp=qp,em=Ue,tm=em("replace"),im=TypeError,uo=kr("".indexOf),sm=kr("".replace),Fa=kr("".slice),rm=Math.max,Va=function(s,e,t){return t>s.length?-1:e===""?t:uo(s,e,t)};jp({target:"String",proto:!0},{replaceAll:function(e,t){var i=Ua(this),r,a,n,o,u,d,l,c,h,p=0,v=0,f="";if(!Qp(e)){if(r=Jp(e),r&&(a=Ct(Ua(Xp(e))),!~uo(a,"g")))throw im("`.replaceAll` does not allow non-global regexes");if(n=Kp(e,tm),n)return zp(n,e,i,t);if(r)return sm(Ct(i),e,t)}for(o=Ct(i),u=Ct(e),d=Wp(t),d||(t=Ct(t)),l=u.length,c=rm(1,l),p=Va(o,u,0);p!==-1;)h=d?Ct(t(u,p,o)):Zp(u,o,p,[],void 0,t),f+=Fa(o,v,p)+h,v=p+l,p=Va(o,u,p+c);return v<o.length&&(f+=Fa(o,v)),f}});var am=Zn,nm=am("String","replaceAll"),om=nm,dm=om,um=dm,lm=um,Ha=lm;const Ga=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},Bs=(s,e)=>{let t=s;t=Ha(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=Ha(t,n,(o,u)=>J(a)?o:J(u)?a:a.padStart(parseInt(u,10),"0"))}return t},cm=(s,e)=>{var t,i,r,a,n,o,u,d,l,c,h,p,v,f,S,g,T,I,w,A,N,K,G,U,X,F,B,te,ue,me,k,H,ne,fe,ve,we,Fe;const Z=new DOMParser().parseFromString(s,"application/xml"),be={video:[],audio:[],text:[]},$e=Z.children[0],Pe=$e.getElementsByTagName("Period")[0],mt=Pe.children;let Ve;const ut=$e.getAttribute("mediaPresentationDuration"),vt=Pe.getAttribute("duration");if(ut)Ve=Ga(ut);else if(vt){const He=Ga(vt);_(He)&&(Ve=He)}let qt=0;const Pt=(i=(t=$e.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],mo=Pt.includes(Ji.WEBM_AS_IN_FFMPEG)||Pt.includes(Ji.WEBM_AS_IN_SPEC)?Vt.WEBM:Vt.MP4;for(const He of mt){const Si=He.getAttribute("mimeType"),vo=He.getAttribute("codecs"),Pr=(r=He.getAttribute("contentType"))!==null&&r!==void 0?r:Si==null?void 0:Si.split("/")[0],So=(n=(a=He.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],go=He.querySelectorAll("Representation"),bo=He.querySelector("SegmentTemplate");if(Pr!=="text")for(const ye of go){const jt=(o=ye.getAttribute("mimeType"))!==null&&o!==void 0?o:Si,Rr=(d=(u=ye.getAttribute("codecs"))!==null&&u!==void 0?u:vo)!==null&&d!==void 0?d:"",gi=(c=(l=ye.getAttribute("contentType"))!==null&&l!==void 0?l:jt==null?void 0:jt.split("/")[0])!==null&&c!==void 0?c:Pr,yo=(p=(h=He.getAttribute("profiles"))===null||h===void 0?void 0:h.split(","))!==null&&p!==void 0?p:[],To=parseInt((v=ye.getAttribute("width"))!==null&&v!==void 0?v:"",10),Ir=parseInt((f=ye.getAttribute("height"))!==null&&f!==void 0?f:"",10),Dr=parseInt((S=ye.getAttribute("bandwidth"))!==null&&S!==void 0?S:"",10)/1e3,Lr=(g=ye.getAttribute("frameRate"))!==null&&g!==void 0?g:"",Eo=(T=ye.getAttribute("quality"))!==null&&T!==void 0?T:void 0,$o=Lr?Ar(Lr):void 0,Ao=(I=ye.getAttribute("id"))!==null&&I!==void 0?I:(qt++).toString(10),wo=gi==="video"?`${Ir}p`:gi==="audio"?`${Dr}Kbps`:Rr,_o=`${Ao}@${wo}`,ko=(N=(A=(w=ye.querySelector("BaseURL"))===null||w===void 0?void 0:w.textContent)===null||A===void 0?void 0:A.trim())!==null&&N!==void 0?N:"",Cr=new URL(ko,e).toString(),Po=[...Pt,...So,...yo];let ds;const Ro=ye.querySelector("SegmentBase"),St=(K=ye.querySelector("SegmentTemplate"))!==null&&K!==void 0?K:bo;if(Ro){const zt=(U=(G=ye.querySelector("SegmentBase Initialization"))===null||G===void 0?void 0:G.getAttribute("range"))!==null&&U!==void 0?U:"",[Wt,ls]=zt.split("-").map(gt=>parseInt(gt,10)),Qt={from:Wt,to:ls},Jt=(X=ye.querySelector("SegmentBase"))===null||X===void 0?void 0:X.getAttribute("indexRange"),[cs,bi]=Jt?Jt.split("-").map(gt=>parseInt(gt,10)):[],Kt=Jt?{from:cs,to:bi}:void 0;ds={type:Le.BYTE_RANGE,url:Cr,initRange:Qt,indexRange:Kt}}else if(St){const zt={representationId:(F=ye.getAttribute("id"))!==null&&F!==void 0?F:void 0,bandwidth:(B=ye.getAttribute("bandwidth"))!==null&&B!==void 0?B:void 0},Wt=parseInt((te=St.getAttribute("timescale"))!==null&&te!==void 0?te:"",10),ls=(ue=St.getAttribute("initialization"))!==null&&ue!==void 0?ue:"",Qt=St.getAttribute("media"),Jt=(k=parseInt((me=St.getAttribute("startNumber"))!==null&&me!==void 0?me:"",10))!==null&&k!==void 0?k:1,cs=Bs(ls,zt);if(!Qt)throw new ReferenceError("No media attribute in SegmentTemplate");const bi=(H=St.querySelectorAll("SegmentTimeline S"))!==null&&H!==void 0?H:[],Kt=[];if(bi.length){let gt=Jt,bt=0;for(const Xt of bi){const Rt=parseInt((ne=Xt.getAttribute("d"))!==null&&ne!==void 0?ne:"",10)*1e3,Zt=parseInt((fe=Xt.getAttribute("r"))!==null&&fe!==void 0?fe:"",10)||0,ei=(we=parseInt((ve=Xt.getAttribute("t"))!==null&&ve!==void 0?ve:"",10))!==null&&we!==void 0?we:void 0;for(let xr=0;xr<Zt+1;xr++){const Io=Bs(Qt,{...zt,segmentNumber:gt.toString(10),segmentTime:ei.toString(10)}),Do=ei?ei/Wt:bt;bt+=Rt/Wt;const Lo=bt;gt++,Kt.push({time:{from:Do,to:Lo},url:Io})}}}else if(_(Ve)){const bt=parseInt((Fe=St.getAttribute("duration"))!==null&&Fe!==void 0?Fe:"",10)/Wt*1e3,Xt=Math.ceil(Ve/bt);let Rt=0;for(let Zt=1;Zt<Xt;Zt++){const ei=Bs(Qt,{...zt,segmentNumber:Zt.toString(10),segmentTime:Rt.toString(10)});Kt.push({time:{from:Rt,to:Rt+bt},url:ei}),Rt+=bt}}ds={type:Le.TEMPLATE,baseUrl:Cr,initUrl:cs,segments:Kt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!gi||!jt)continue;const us={video:De.VIDEO,audio:De.AUDIO,text:De.TEXT}[gi];us&&be[us].push({id:_o,kind:us,segmentReference:ds,profiles:Po,duration:Ve,bitrate:Dr,mime:jt,codecs:Rr,width:To,height:Ir,fps:$o,quality:Eo})}}return{duration:Ve,container:mo,representations:be}},hm=["timeupdate","progress","play","seeked","stalled","waiting"];var Ie;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(Ie||(Ie={}));let fm=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new ie,this.state$=new de(Ie.NONE),this.currentVideoRepresentation$=new y(void 0),this.error$=new C,this.lastConnectionType$=new y(void 0),this.lastConnectionReused$=new y(void 0),this.lastRequestFirstBytes$=new y(void 0),this.forceEnded$=new C,this.gapWatchdogStarted=!1,this.destroyController=new Tt,this.initManifest=Be(this.destroyController.signal,async function*(t,i){this.element=t,this.state$.startTransitionTo(Ie.MANIFEST_READY);const r=yield this.fetcher.fetchManifest(i).catch(o=>this.error$.next({id:"LoadManifest",category:L.NETWORK,message:"Failed to load manifest",thrown:o}));if(!r)return;let a;try{a=cm(r!=null?r:"",i)}catch(o){this.error$.next({id:"ManifestParsing",category:L.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!a)return;const n=({mime:o,codecs:u})=>{var d,l,c;return Boolean(((d=t.canPlayType)===null||d===void 0?void 0:d.call(t,o))&&((c=(l=window.MediaSource)===null||l===void 0?void 0:l.isTypeSupported)===null||c===void 0?void 0:c.call(l,`${o}; codecs="${u}"`)))};this.manifest={...a,representations:fi(Object.entries(a.representations).map(([o,u])=>[o,u.filter(n)]))},this.manifest.representations.video.length?this.state$.setState(Ie.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:L.PARSER,message:"No playable video representations"})}.bind(this)),this.initRepresentations=Be(this.destroyController.signal,async function*(t,i){P(this.manifest),P(this.element),this.state$.startTransitionTo(Ie.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};this.videoBufferManager=new Ba(De.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],_(i)&&(this.audioBufferManager=new Ba(De.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,r),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));const a=x(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe($(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=x(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe($(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.subscription.add(x(this.forceEnded$,Ze({allBuffersFull:a,someBufferEnded:n}).pipe(q(({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:L.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:u})}})),this.subscription.add(x(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(o=>{var u;return(u=this.source)===null||u===void 0?void 0:u.addEventListener("sourceopen",o)})),_(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&_(i)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)]):yield this.videoBufferManager.startWith(t),this.state$.setState(Ie.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=xo(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),a=>{this.error$.next({id:"GapWatchdog",category:L.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Ap({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initBuffer(){P(this.element),this.state$.setState(Ie.RUNNING),this.subscription.add(x(...hm.map(e=>M(this.element,e)),M(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:L.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(M(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(M(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&or(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){const i={[De.VIDEO]:this.videoBufferManager,[De.AUDIO]:this.audioBufferManager,[De.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)}seek(e,t){var i,r,a,n,o;P(this.element),P(this.videoBufferManager);let u;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?u=e:u=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!==null&&i!==void 0?i:e,(a=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&a!==void 0?a:e),or(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(Ie.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(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3,t=[];for(const i of this.bufferManagers)for(const r of i.gaps)i.playingRepresentation$.getValue()===r.representation&&r.from<=e&&r.to>e&&(this.element.duration*1e3-r.to<this.tuning.endGapTolerance?t.push(1/0):t.push(r.to));if(t.length){const i=Math.max(...t);i===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=i/1e3}}};var le;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(le||(le={}));const pm=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a})=>{var n;const o=(n=a?mi(a):void 0)!==null&&n!==void 0?n:_t({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r}},mm=({id:s,bitrate:e})=>({id:s,bitrate:e}),vm=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=Je(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:Je(s,-1)};class Sm{constructor(e){this.subscription=new ie,this.videoState=new de(le.STOPPED),this.elementSize$=new y(void 0),this.textTracksManager=new ze,this.videoTracks=[],this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Ff,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(!this.videoState.getTransition()){if(a.state===V.Requested&&(r==null?void 0:r.to)!==m.PAUSED&&t!==le.STOPPED&&i!==m.STOPPED&&this.seek(a.position,a.forcePrecise),i===m.STOPPED){t!==le.STOPPED&&(this.videoState.startTransitionTo(le.STOPPED),this.player.stop(),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(le.STOPPED),R(this.params.desiredState.playbackState,m.STOPPED,!0));return}switch(t){case le.STOPPED:this.videoState.startTransitionTo(le.READY),this.prepare();return;case le.READY:i===m.PAUSED?(this.videoState.setState(le.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED)):i===m.PLAYING?(this.videoState.startTransitionTo(le.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===m.READY&&R(this.params.desiredState.playbackState,m.READY);return;case le.PLAYING:i===m.PAUSED?(this.videoState.startTransitionTo(le.PAUSED),this.video.pause()):(r==null?void 0:r.to)===m.PLAYING&&R(this.params.desiredState.playbackState,m.PLAYING);return;case le.PAUSED:i===m.PLAYING?(this.videoState.startTransitionTo(le.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===m.PAUSED&&R(this.params.desiredState.playbackState,m.PAUSED);return;default:return O(t)}}},this.params=e,this.video=ot(this.params.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(Ae(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new fm({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=dt(this.video),r=d=>{e.error$.next({id:"DashVKProvider",category:L.WTF,message:"DashVKProvider internal logic error",thrown:d})},a=(d,l)=>this.subscription.add(d.subscribe(l,r));a(i.timeUpdate$,e.position$),a(i.durationChange$,e.duration$),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.isAudioAvailable$,e.isAudioAvailable$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.lastRequestFirstBytes$.pipe(q(_),ge(),$t(void 0)),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(kt(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(ft(this.video,t.playbackRate,i.playbackRateState$,r)),a(Wi(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(le.PLAYING),R(t.playbackState,m.PLAYING)},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(le.PAUSED),R(t.playbackState,m.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===le.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d===Ie.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[];const c=this.player.getRepresentations();P(c,"Manifest not loaded or empty");const h=Array.from(c.audio).sort((f,S)=>S.bitrate-f.bitrate),p=Array.from(c.video).sort((f,S)=>S.bitrate-f.bitrate);if(!this.params.tuning.isAudioDisabled)for(const f of h){const S=mm(f);S&&this.audioTracks.push({track:S,representation:f})}for(const f of p){const S=pm(f);if(S){this.videoTracks.push({track:S,representation:f});const g=!this.params.tuning.isAudioDisabled&&vm(h,p,f);g&&this.audioRepresentations.set(f.id,g)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:f})=>f)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:f})=>f)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length);const v=this.selectVideoRepresentation();P(v),this.player.initRepresentations(v.id,(l=this.audioRepresentations.get(v.id))===null||l===void 0?void 0:l.id)}else d===Ie.REPRESENTATIOS_READY&&(this.videoState.setState(le.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:L.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(x(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,M(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!==Ie.RUNNING||l||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation();if(c){this.player.switchRepresentation(De.VIDEO,c.id).catch(n);const h=this.audioRepresentations.get(c.id);h&&this.player.switchRepresentation(De.AUDIO,h.id).catch(n)}},r)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(pe(),$(d=>{var l;return d&&((l=this.videoTracks.find(({representation:{id:c}})=>c===d))===null||l===void 0?void 0:l.track)})).subscribe(e.currentVideoTrack$,r)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe($(({to:d})=>d===m.READY),pe());this.subscription.add(x(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(x(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===m.READY)));const u=x(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(xe(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,i,r,a,n;const o=this.params.desiredState.autoVideoTrackSwitching.getState(),u=this.params.desiredState.videoTrack.getState(),d=(e=this.videoTracks.find(({track:{id:g}})=>g===u))===null||e===void 0?void 0:e.track,l=this.params.output.currentVideoTrack$.getValue(),c=yt(this.video.buffered,this.video.currentTime*1e3),h=o?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=Math.min(c/Math.min(h,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),v=Math.max(d&&!o&&(i=(t=this.audioRepresentations.get(d.id))===null||t===void 0?void 0:t.bitrate)!==null&&i!==void 0?i:0,l&&(a=(r=this.audioRepresentations.get(l.id))===null||r===void 0?void 0:r.bitrate)!==null&&a!==void 0?a:0),f=pi(this.videoTracks.map(({track:g})=>g),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:p,current:l,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),S=o?f!=null?f:d:d!=null?d:f;return S&&((n=this.videoTracks.find(({track:g})=>g===S))===null||n===void 0?void 0:n.representation)}async prepare(){this.player.initManifest(this.video,this.params.source.url)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){pt(this.video).then(e=>{e||(this.videoState.setState(le.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED,!0))})}}const gm=5e3,We={};var Q;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Q||(Q={}));const Di=(s,e)=>new ui(t=>{const i=(r,a)=>t.next(a);return s.on(e,i),()=>s.off(e,i)});class bm{constructor(e){this.subscription=new ie,this.videoState=new de(Q.INITIALIZING),this.textTracksManager=new ze,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!==Q.INITIALIZING)switch((r==null?void 0:r.to)!==m.PAUSED&&a.state===V.Requested&&this.seek(a.position),i){case m.STOPPED:switch(t){case Q.STOPPED:break;case Q.READY:case Q.PLAYING:case Q.PAUSED:this.stop();break;default:O(t)}break;case m.READY:switch(t){case Q.STOPPED:this.prepare();break;case Q.READY:case Q.PLAYING:case Q.PAUSED:break;default:O(t)}break;case m.PLAYING:switch(t){case Q.PLAYING:break;case Q.STOPPED:this.prepare();break;case Q.READY:case Q.PAUSED:this.playIfAllowed();break;default:O(t)}break;case m.PAUSED:switch(t){case Q.PAUSED:break;case Q.STOPPED:this.prepare();break;case Q.READY:this.videoState.setState(Q.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED);break;case Q.PLAYING:this.pause();break;default:O(t)}break;default:O(i)}},this.video=ot(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(Ae(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.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:L.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),gm);import("hls.js/dist/hls.min.js").then(r=>{e||(We.Hls=r.default,We.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){P(We.Hls,"hls.js not loaded"),this.hls=new We.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(Q.STOPPED)}subscribe(){P(We.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:L.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=dt(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.isAudioAvailable$,t.isAudioAvailable$),this.subscription.add(kt(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(ft(this.video,e.playbackRate,r.playbackRateState$,i)),this.subscription.add(Di(this.hls,We.Events.ERROR).subscribe(d=>{var l;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:L.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(Q.PLAYING),R(e.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(Q.PAUSED),R(e.playbackState,m.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())===null||d===void 0?void 0:d.to)===Q.READY&&this.videoState.setState(Q.READY),this.videoState.getState()===Q.PLAYING&&this.playIfAllowed()},i)),a(Di(this.hls,We.Events.MANIFEST_PARSED).pipe($(({levels:d})=>d.reduce((l,c)=>{var h,p;const v=c.name||c.height.toString(10),{width:f,height:S}=c,g=(p=mi((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&p!==void 0?p:_t({width:f,height:S});if(!g)return l;const T=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,I={id:v.toString(),quality:g,bitrate:c.bitrate/1e3,size:{width:f,height:S},fps:T};return this.trackLevels.set(v,{track:I,level:c}),l.push(I),l},[]))),t.availableVideoTracks$),a(Di(this.hls,We.Events.LEVEL_LOADING).pipe($(({url:d})=>Ae(d))),t.hostname$),this.subscription.add(qe(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=Di(this.hls,We.Events.LEVEL_SWITCHED).pipe($(({level:d})=>n(this.hls.levels[d])));o.pipe(q(_)).subscribe(t.currentVideoTrack$,i),this.subscription.add(qe(e.videoTrack,()=>{var d;return(d=n(this.hls.levels[this.hls.currentLevel]))===null||d===void 0?void 0:d.id},d=>{var l;if(J(d))return;const c=(l=this.trackLevels.get(d))===null||l===void 0?void 0:l.level;if(!c)return;const h=this.hls.levels.indexOf(c),p=this.hls.currentLevel,v=this.hls.levels[p];!v||c.bitrate>v.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o.pipe($(d=>d==null?void 0:d.id)),onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const u=x(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(xe(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(Q.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(Q.PLAYING),await pt(this.video)||(this.videoState.setState(Q.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED,!0))}pause(){this.videoState.startTransitionTo(Q.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.setAttribute("src",""),this.video.load(),this.videoState.setState(Q.STOPPED),R(this.params.desiredState.playbackState,m.STOPPED,!0)}}const Ya="X-Playback-Duration";var qa=async s=>{const e=await Ut(s,{method:"HEAD"});return e.headers.has(Ya)?parseInt(e.headers.get(Ya),10):void 0};const ym=s=>{let e=null;if(s.QUALITY&&(e=mi(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=_t({width:t,height:i})}return e!=null?e:null},lo=async(s,e=s)=>{var t;const a=(await(await Ut(s)).text()).split(`
|
|
8
|
-
`),n=[];for(let o=0;o<a.length;o++){const d=a[o].match(/^#EXT-X-STREAM-INF:(.+)/);if(!d)continue;const l=fi(d[1].split(",").map(g=>g.split("="))),c=(t=l.QUALITY)!==null&&t!==void 0?t:`stream-${l.BANDWIDTH}`,h=ym(l);let p;l.BANDWIDTH&&(p=parseInt(l.BANDWIDTH,10)/1e3||void 0),!p&&l["AVERAGE-BANDWIDTH"]&&(p=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const v=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0;let f;if(l.RESOLUTION){const[g,T]=l.RESOLUTION.split("x").map(I=>parseInt(I,10));g&&T&&(f={width:g,height:T})}const S=new URL(a[++o],e).toString();h&&n.push({id:c,quality:h,url:S,bandwidth:p,size:f,fps:v})}return n};var se;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(se||(se={}));class Tm{constructor(e){var t;this.subscription=new ie,this.videoState=new de(se.STOPPED),this.textTracksManager=new ze,this.manifests$=new y([]),this.liveOffset=new $r,this.manifestStartTime$=new y(void 0),this.syncPlayback=()=>{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!==se.STOPPED&&(this.videoState.startTransitionTo(se.STOPPED),this.video.setAttribute("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(se.STOPPED),R(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(r===se.STOPPED){this.videoState.startTransitionTo(se.READY),this.prepare();return}if(o||u){const c=this.videoState.getState();this.videoState.setState(se.CHANGING_MANIFEST),this.videoState.startTransitionTo(c),this.prepare(),l.state===V.None&&this.params.desiredState.seekState.setState({state:V.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==m.PAUSED&&l.state===V.Requested){this.videoState.startTransitionTo(se.READY),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case se.READY:a===m.READY?R(this.params.desiredState.playbackState,m.READY):a===m.PAUSED?(this.videoState.setState(se.PAUSED),this.liveOffset.pause(),R(this.params.desiredState.playbackState,m.PAUSED)):a===m.PLAYING&&(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed());return;case se.PLAYING:a===m.PAUSED?(this.videoState.startTransitionTo(se.PAUSED),this.liveOffset.pause(),this.video.pause()):(n==null?void 0:n.to)===m.PLAYING&&R(this.params.desiredState.playbackState,m.PLAYING);return;case se.PAUSED:a===m.PLAYING?(this.videoState.startTransitionTo(se.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)):this.seek(-this.liveOffset.getTotalOffset())):(n==null?void 0:n.to)===m.PAUSED&&(R(this.params.desiredState.playbackState,m.PAUSED),this.liveOffset.pause());return;case se.CHANGING_MANIFEST:break;default:return O(r)}},this.params=e,this.video=ot(e.container),this.params.output.element$.next(this.video);const i={id:"master",quality:ae.INVARIANT,url:this.params.source.url};this.manifests$.next([i]),lo(Mt(this.params.source.url),this.params.source.url).then(r=>{this.manifests$.next([i,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:L.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ae(this.params.source.url)),this.maxSeekBackTime$=new y((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;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)return;const d=a?"master":o;return a&&!n&&r.startTransitionTo("master"),u.find(l=>l.id===d)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:L.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=dt(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.isAudioAvailable$,e.isAudioAvailable$),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(ft(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(se.PLAYING),R(t.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(se.PAUSED),R(t.playbackState,m.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===se.READY&&this.videoState.setState(se.READY),this.videoState.getState()===se.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(pe(),$(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.to)){const c=d.to;this.params.desiredState.videoTrack.setState(c);const h=this.manifests$.getValue().find(p=>p.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Ae(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===se.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===V.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(Ze({startTime:this.manifestStartTime$.pipe(q(_)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe($(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));const n=x(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,ke(["init"])).pipe(xe(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();if(J(e))return;const t=Mt(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),qa(t).then(i=>{var r;if(!J(i))this.maxSeekBackTime$.next(i);else{const a=(r=this.params.source.maxSeekBackTime)!==null&&r!==void 0?r:this.maxSeekBackTime$.getValue();if(J(a)||!isFinite(a))try{Ut(t).then(n=>n.text()).then(n=>{var o;const u=(o=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(n))===null||o===void 0?void 0:o[1];if(u){const d=new URL(u,t).toString();qa(d).then(l=>{J(l)||this.maxSeekBackTime$.next(l)})}})}catch(n){}}})}playIfAllowed(){pt(this.video).then(e=>{e||(this.videoState.setState(se.PAUSED),this.liveOffset.pause(),R(this.params.desiredState.playbackState,m.PAUSED,!0))})}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 oe;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(oe||(oe={}));class Em{constructor(e){this.subscription=new ie,this.videoState=new de(oe.STOPPED),this.textTracksManager=new ze,this.manifests$=new y([]),this.syncPlayback=()=>{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!==oe.STOPPED&&(this.videoState.startTransitionTo(oe.STOPPED),this.video.setAttribute("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(oe.STOPPED),R(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.seekState.getState();if(i===oe.STOPPED){this.videoState.startTransitionTo(oe.READY),this.prepare();return}if(n||o){const l=this.videoState.getState();this.videoState.setState(oe.CHANGING_MANIFEST),this.videoState.startTransitionTo(l);const{currentTime:c}=this.video;this.prepare(),d.state===V.None&&this.params.desiredState.seekState.setState({state:V.Requested,position:c*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==m.PAUSED&&d.state===V.Requested&&this.seek(d.position),i){case oe.READY:r===m.READY?R(this.params.desiredState.playbackState,m.READY):r===m.PAUSED?(this.videoState.setState(oe.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED)):r===m.PLAYING&&(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed());return;case oe.PLAYING:r===m.PAUSED?(this.videoState.startTransitionTo(oe.PAUSED),this.video.pause()):(a==null?void 0:a.to)===m.PLAYING&&R(this.params.desiredState.playbackState,m.PLAYING);return;case oe.PAUSED:r===m.PLAYING?(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===m.PAUSED&&R(this.params.desiredState.playbackState,m.PAUSED);return;case oe.CHANGING_MANIFEST:break;default:return O(i)}},this.params=e,this.video=ot(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:ae.INVARIANT,url:this.params.source.url};this.manifests$.next([t]),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(Ae(this.params.source.url)),lo(this.params.source.url).then(i=>{this.manifests$.next([t,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:L.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),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)return;const d=a?"master":o;return a&&!n&&r.startTransitionTo("master"),u.find(l=>l.id===d)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:L.WTF,message:"HlsProvider internal logic error",thrown:o})},r=dt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));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.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(kt(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(ft(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(oe.PLAYING),R(t.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(oe.PAUSED),R(t.playbackState,m.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===oe.READY&&this.videoState.setState(oe.READY),this.videoState.getState()===oe.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.to)){const c=d.to;this.params.desiredState.videoTrack.setState(c);const h=this.manifests$.getValue().find(p=>p.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Ae(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===oe.CHANGING_MANIFEST&&this.videoState.setState(u.to),o.state===V.Requested&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe($(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));const n=x(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(xe(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();J(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){pt(this.video).then(e=>{e||(this.videoState.setState(oe.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var ce;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(ce||(ce={}));class $m{constructor(e){this.subscription=new ie,this.videoState=new de(ce.STOPPED),this.trackUrls={},this.textTracksManager=new ze,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(i===m.STOPPED){t!==ce.STOPPED&&(this.videoState.startTransitionTo(ce.STOPPED),this.video.setAttribute("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(ce.STOPPED),R(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(t===ce.STOPPED){this.videoState.startTransitionTo(ce.READY),this.prepare();return}if(n){const{currentTime:u}=this.video;this.prepare(),o.state===V.None&&this.params.desiredState.seekState.setState({state:V.Requested,position:u*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!==m.PAUSED&&o.state===V.Requested&&this.seek(o.position),t){case ce.READY:i===m.READY?R(this.params.desiredState.playbackState,m.READY):i===m.PAUSED?(this.videoState.setState(ce.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED)):i===m.PLAYING&&(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed());return;case ce.PLAYING:i===m.PAUSED?(this.videoState.startTransitionTo(ce.PAUSED),this.video.pause()):(r==null?void 0:r.to)===m.PLAYING&&R(this.params.desiredState.playbackState,m.PLAYING);return;case ce.PAUSED:i===m.PLAYING?(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===m.PAUSED&&R(this.params.desiredState.playbackState,m.PAUSED);return;default:return O(t)}},this.params=e,this.video=ot(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).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.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:L.WTF,message:"MpegProvider internal logic error",thrown:o})},r=dt(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.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(kt(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(ft(this.video,t.playbackRate,r.playbackRateState$,i)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ce.PLAYING),R(t.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ce.PAUSED),R(t.playbackState,m.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ce.READY&&this.videoState.setState(ce.READY);const u=this.params.desiredState.videoTrack.getTransition();u&&_(u.to)&&(this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to].track)),this.videoState.getState()===ce.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const n=x(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(xe(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){var e,t;const i=(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();P(i,"MpegProvider: track is not selected");let{url:r}=this.trackUrls[i];P(r,`MpegProvider: No url for ${i}`),this.params.tuning.requestQuick&&(r=Ft(r)),this.video.setAttribute("src",r),this.video.load(),this.params.output.hostname$.next(Ae(r))}playIfAllowed(){pt(this.video).then(e=>{e||(this.videoState.setState(ce.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}const ja=["stun:videostun.mycdn.me:80"],Am=1e3,wm=3,Ms=()=>null;class _m{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=Ms,this.externalStopCallback=Ms,this.externalErrorCallback=Ms,this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:ja}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:L.WTF,message:e.message})}async onPeerConnectionStream(e){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),Am)}normalizeOptions(e={}){const t={stunServerList:ja,maxRetryNumber:wm,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var re;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(re||(re={}));class km{constructor(e){this.videoState=new de(re.STOPPED),this.maxSeekBackTime$=new y(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!==re.STOPPED&&(this.videoState.startTransitionTo(re.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(re.STOPPED),R(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===re.STOPPED){this.videoState.startTransitionTo(re.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case re.READY:i===m.PAUSED?(this.videoState.setState(re.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED)):i===m.PLAYING&&(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed());return;case re.PLAYING:i===m.PAUSED?(this.videoState.startTransitionTo(re.PAUSED),this.video.pause()):(r==null?void 0:r.to)===m.PLAYING&&R(this.params.desiredState.playbackState,m.PLAYING);return;case re.PAUSED:i===m.PLAYING?(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===m.PAUSED&&R(this.params.desiredState.playbackState,m.PAUSED);return;default:return O(t)}},this.subscription=new ie,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ot(e.container),this.liveStreamClient=new _m(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.video.remove(),this.params.output.element$.next(void 0),this.liveStreamClient.disconnect()}subscribe(){const{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:L.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};x(this.videoState.stateChangeStarted$.pipe($(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe($(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const r=dt(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$),a(r.isAudioAvailable$,e.isAudioAvailable$),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)===re.READY&&this.videoState.setState(re.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(re.PAUSED)},i)).add(r.playing$.subscribe(()=>{this.videoState.setState(re.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 re.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(m.STOPPED);break;case re.READY:break;case re.PAUSED:t.playbackState.setState(m.PAUSED);break;case re.PLAYING:t.playbackState.setState(m.PLAYING);break;default:return O(n.to)}},i)).add(x(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(xe(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.hostname$.next(Ae(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:ae.INVARIANT}),this.video.srcObject=e,R(this.params.desiredState.playbackState,m.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(re.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:L.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){pt(this.video).then(e=>{e||(this.videoState.setState(re.PAUSED),R(this.params.desiredState.playbackState,m.PAUSED,!0))})}prepare(){this.liveStreamClient.connect()}}class za{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 Boolean(this.current.done)}}var Pm=()=>{var s,e;const t=window.navigator;return t.userAgentData?((e=(s=t.userAgentData)===null||s===void 0?void 0:s.platform)===null||e===void 0?void 0:e.toLowerCase())==="android":window.navigator.userAgent.toLowerCase().includes("android")},Us,Fs,Vs,Hs,Gs,Ys,Li,qs,Ci,js,xi,zs,Oi,Ws,Ni,Qs;const co=Pm(),lt=document.createElement("video"),Qe={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&((Fs=(Us=window.SourceBuffer)===null||Us===void 0?void 0:Us.prototype)===null||Fs===void 0?void 0:Fs.appendBuffer)),hls:Boolean(((Vs=lt.canPlayType)===null||Vs===void 0?void 0:Vs.call(lt,"application/x-mpegurl"))||((Hs=lt.canPlayType)===null||Hs===void 0?void 0:Hs.call(lt,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection)},Re={mp4:Boolean((Gs=lt.canPlayType)===null||Gs===void 0?void 0:Gs.call(lt,"video/mp4")),webm:Boolean((Ys=lt.canPlayType)===null||Ys===void 0?void 0:Ys.call(lt,"video/webm")),cmaf:!0},ct={h264:Boolean((qs=(Li=window.MediaSource)===null||Li===void 0?void 0:Li.isTypeSupported)===null||qs===void 0?void 0:qs.call(Li,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean((js=(Ci=window.MediaSource)===null||Ci===void 0?void 0:Ci.isTypeSupported)===null||js===void 0?void 0:js.call(Ci,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean((zs=(xi=window.MediaSource)===null||xi===void 0?void 0:xi.isTypeSupported)===null||zs===void 0?void 0:zs.call(xi,'video/webm; codecs="vp9"')),aac:Boolean((Ws=(Oi=window.MediaSource)===null||Oi===void 0?void 0:Oi.isTypeSupported)===null||Ws===void 0?void 0:Ws.call(Oi,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean((Qs=(Ni=window.MediaSource)===null||Ni===void 0?void 0:Ni.isTypeSupported)===null||Qs===void 0?void 0:Qs.call(Ni,'audio/webm; codecs="opus"'))},xt=(ct.h264||ct.h265)&&ct.aac,os=Qe.hls&&Re.mp4,Rm=Boolean(window.WebSocket),Im=()=>Object.keys(ct).filter(s=>ct[s]),Dm=(s,e=!1)=>s.filter(t=>{switch(t){case b.DASH:return Qe.mse&&Re.mp4&&xt;case b.DASH_SEP:return Qe.mse&&Re.mp4&&xt;case b.DASH_WEBM:return Qe.mse&&Re.webm&&ct.vp9&&ct.opus;case b.DASH_LIVE:return Qe.mse&&Re.mp4&&xt;case b.DASH_LIVE_CMAF:return Qe.mse&&Re.mp4&&xt&&Re.cmaf;case b.DASH_ONDEMAND:return Qe.mse&&Re.mp4&&xt;case b.HLS:case b.HLS_LIVE:case b.HLS_LIVE_CMAF:case b.HLS_ONDEMAND:return os||e&&Qe.mse&&Re.mp4&&xt;case b.MPEG:return Re.mp4;case b.DASH_LIVE_WEBM:return!1;case b.WEB_RTC_LIVE:return Qe.webrtc&&Rm&&ct.h264&&(Re.mp4||Re.webm);default:return O(t)}}),Lm=()=>co?[b.MPEG,b.DASH_WEBM,b.DASH_SEP,b.DASH,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND]:os?[b.DASH_WEBM,b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG,b.DASH]:[b.DASH_WEBM,b.DASH_SEP,b.DASH,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG],Cm=()=>co?[b.HLS_LIVE,b.HLS_LIVE_CMAF,b.WEB_RTC_LIVE,b.DASH_LIVE,b.DASH_LIVE_CMAF]:os?[b.WEB_RTC_LIVE,b.HLS_LIVE,b.HLS_LIVE_CMAF,b.DASH_LIVE,b.DASH_LIVE_CMAF]:[b.WEB_RTC_LIVE,b.DASH_LIVE,b.DASH_LIVE_CMAF,b.HLS_LIVE,b.HLS_LIVE_CMAF],Wa=s=>s?[b.HLS_LIVE]:[b.DASH_WEBM,b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG];var xm=s=>new ui(e=>{const t=new ie,i=s.desiredPlaybackState$.stateChangeStarted$.pipe($(({from:d,to:l})=>`${d}-${l}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$,n=new C;let o=0,u="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>n.next(d),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="provider change",o=0})),t.add(a.subscribe(()=>{o&&(window.clearTimeout(o),o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const Qa={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},Om={cacheDuration:12e4},Nm={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Bm={maxPausedTime:3e4},Ja={maxPausedTime:3e4};class Mm{constructor(e){this.current$=new y({type:void 0}),this.providerError$=new C,this.noAvailableProvidersError$=new C,this.providerOutput={position$:new y(0),duration$:new y(1/0),volume$:new y({muted:!1,volume:1}),currentVideoTrack$:new y(void 0),availableVideoTracks$:new y([]),availableAudioTracks$:new y([]),isAudioAvailable$:new y(!0),autoVideoTrackLimitingAvailable$:new y(!1),currentBuffer$:new y(void 0),isBuffering$:new y(!0),error$:new C,willSeekEvent$:new C,seekedEvent$:new C,loopedEvent$:new C,endedEvent$:new C,firstBytesEvent$:new C,firstFrameEvent$:new C,canplay$:new C,isLive$:new y(void 0),liveTime$:new y(void 0),availableTextTracks$:new y([]),currentTextTrack$:new y(void 0),hostname$:new y(void 0),httpConnectionType$:new y(void 0),httpConnectionReused$:new y(void 0),element$:new y(void 0)},this.subscription=new ie,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Dm([...Cm(),...Lm()],this.params.tuning.useHlsJs).filter(n=>_(e.sources[n])),{formatsToAvoid:i}=this.params.tuning,r=i.length?[...t.filter(n=>!i.includes(n)),...t.filter(n=>i.includes(n))]:t;this.screenFormatsIterator=new za(r);const a=[...Wa(!0),...Wa(!1)];this.chromecastFormatsIterator=new za(a.filter(n=>_(e.sources[n])))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(J(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:L.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const e=this.current$.getValue().destination;P(e,"No current provider"),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!==V.None;this.params.desiredState.seekState.setState({state:V.Requested,position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case _e.SCREEN:return this.createScreenProvider(t);case _e.CHROMECAST:return this.createChromecastProvider(t);default:return O(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 b.DASH:{const o=this.applyFailoverHost(t[e]);return P(o),new up({...n,source:o,config:Om})}case b.DASH_SEP:case b.DASH_WEBM:case b.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),this.params.tuning.useDashJs?new La({...n,source:o,format:e,config:Ja}):new Sm({...n,source:o})}case b.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new La({...n,source:o,format:e,config:Ja})}case b.HLS:case b.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),os||!this.params.tuning.useHlsJs?new Em({...n,source:o}):new bm({...n,source:o})}case b.HLS_LIVE:case b.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new Tm({...n,source:o,config:Bm})}case b.MPEG:{const o=this.applyFailoverHost(t[e]);return P(o),new $m({...n,source:o})}case b.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new rp({...n,source:o,config:Nm})}case b.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new km({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case b.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return O(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return P(o),new cf({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()?_e.CHROMECAST:_e.SCREEN}chooseFormat(e){switch(e){case _e.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case _e.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return O(e)}}skipFormat(e){switch(e){case _e.SCREEN:return this.screenFormatsIterator.next();case _e.CHROMECAST:return this.chromecastFormatsIterator.next();default:return O(e)}}handleNoFormatsError(e){switch(e){case _e.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case _e.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return O(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=r=>{const a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return fi(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){const e=new ie;let t=!1,i=0;return e.add(x(this.providerOutput.error$,xm({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:Qa.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(q(({type:r})=>r!==void 0))}).pipe($(r=>({id:`ProviderHangup:${r}`,category:L.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(q(({to:a})=>a===m.PLAYING),ge()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{if(this.current$.getValue().destination===_e.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const a=r.category===L.NETWORK,n=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),o=i<Qa.providerErrorLimit;n&&(a&&t||!o)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):o?(i++,this.reinitProvider()):this.switchToNextProvider()}})),e}}var Ce;(function(s){s[s.LOCAL_STORAGE=0]="LOCAL_STORAGE",s[s.SESSION_STORAGE=1]="SESSION_STORAGE",s[s.RUNTIME=2]="RUNTIME"})(Ce||(Ce={}));const ho=new Map;let Et=Ce.RUNTIME;const Js=`vk-videoplayer-dummy-key-${Math.random()}`,Um=()=>{try{localStorage.setItem(Js,"test"),localStorage.removeItem(Js),Et=Ce.LOCAL_STORAGE}catch(s){if(s instanceof DOMException||s instanceof TypeError)try{sessionStorage.getItem(Js),Et=Ce.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)Et=Ce.RUNTIME;else throw e}else throw s}};Um();const Fm=s=>{var e,t;switch(Et){case Ce.LOCAL_STORAGE:return(e=localStorage.getItem(s))!==null&&e!==void 0?e:void 0;case Ce.SESSION_STORAGE:return(t=sessionStorage.getItem(s))!==null&&t!==void 0?t:void 0;case Ce.RUNTIME:return ho.get(s);default:O(Et)}},Ka=(s,e)=>{switch(Et){case Ce.LOCAL_STORAGE:try{localStorage.setItem(s,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Ce.SESSION_STORAGE:try{sessionStorage.setItem(s,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Ce.RUNTIME:return void ho.set(s,e);default:O(Et)}},dr=(s,e,t)=>t*e+(1-t)*s,fo=(s,e)=>s.reduce((t,i)=>t+i,0)/e,Vm=(s,e,t,i)=>{let r=0,a=t;const n=fo(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 y(e.initial),this.debounced$=new y(e.initial);const i=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ye(`raw_${i}`),this.smoothedSeries$=new Ye(`smoothed_${i}`),this.reportedSeries$=new Ye(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(J(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class Hm extends po{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=dr(this.slow,e,this.params.emaAlphaSlow),this.fast=dr(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Gm extends po{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=fo(this.pastMeasures,this.takenMeasures);this.emaSmoothed=dr(this.emaSmoothed,e,this.params.emaAlpha);const i=Vm(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class Xa{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Hm({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Gm({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}}const Ym=5e3,Za="one_video_throughput",en="one_video_rtt",tt=window.navigator.connection,tn=()=>{const s=tt==null?void 0:tt.downlink;if(_(s)&&s!==10)return s*1e3},sn=()=>{const s=tt==null?void 0:tt.rtt;if(_(s)&&s!==3e3)return s},rn=(s,e,t)=>{const i=t*8,r=i/s;return i/(r+e)};class ni{constructor(e){var t,i;this.subscription=new ie,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=ni.load(Za)||(e.useBrowserEstimation?tn():void 0)||Ym,a=(i=(t=ni.load(en))!==null&&t!==void 0?t:e.useBrowserEstimation?sn():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new y(r),this.rtt$=new y(a),this.rttAdjustedThroughput$=new y(rn(r,a,e.rttPenaltyRequestSize)),this.throughput=Xa.getSmoothedValue(r,-1,e),this.rtt=Xa.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const u=tn();u&&this.throughput.next(u);const d=sn();_(d)&&this.rtt.next(d)};tt&&"onchange"in tt&&this.subscription.add(M(tt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Ka(Za,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Ka(en,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Ze({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe($(({throughput:n,rtt:o})=>rn(n,o,e.rttPenaltyRequestSize)),q(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 ie;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(M(e,"progress").pipe(ge()).subscribe(a=>{t=a.loaded,i=he()}));break;case 1:case 0:r.add(M(e,"loadstart").subscribe(()=>{t=0,i=he()}));break}r.add(M(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){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let i=0;const r=he();let a=0,n=he();const o=d=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},u=async({done:d,value:l})=>{d?(this.addRawSpeed(i,he()-r,1),this.concurrentDownloads.delete(e)):l&&(i+=l.byteLength,a+=l.byteLength,a>=this.tuningConfig.streamMinSampleSize&&he()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,he()-n,this.concurrentDownloads.size),a=0,n=he()),await(t==null?void 0:t.read().then(u,o)))};this.concurrentDownloads.add(e),t==null||t.read().then(u,o)}addRawSpeed(e,t,i=1){if(ni.sanityCheck(e,t)){const r=e*8/t;this.throughput.next(r*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=Fm(e);if(_(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const an={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},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,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,useHlsJs:!0,isAudioDisabled:!1,webrtc:{connectionRetryMaxNumber:3}},qm=s=>{const e={};for(const t of Object.keys(an)){const i=an[t],r=s[t];Array.isArray(i)&&Array.isArray(r)?e[t]=r:typeof i=="object"&&typeof r=="object"?e[t]={...i,...r}:e[t]=r!=null?r:i}return e};var jm=({seekState:s,position$:e})=>x(s.stateChangeEnded$.pipe($(({to:t})=>{var i;return t.state===V.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),q(_)),e.pipe(q(()=>s.getState().state===V.None))),zm=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return P(e,`Wrong container or containerId {${s.container}}`),e};const nn=({playbackState:s,seekState:e,playbackAbort$:t,looped$:i,position$:r})=>new ui(a=>{let n;const o=s.transitionEnded$.pipe(q(p=>(p.from===m.PAUSED||p.from===m.STOPPED)&&p.to===m.PLAYING)),u=s.stateChangeEnded$.pipe(q(p=>p.from===m.PLAYING&&p.to===m.PAUSED)),d=e.stateChangeEnded$.pipe(q(({to:p})=>{var v,f;return p.state===V.Requested&&((f=(v=s.getTransition())===null||v===void 0?void 0:v.from)!==null&&f!==void 0?f:s.getState())===m.PLAYING})),l=e.stateChangeEnded$.pipe(q(({from:p,to:v})=>{var f,S;return p.state===V.Applying&&v.state===V.None&&((S=(f=s.getTransition())===null||f===void 0?void 0:f.from)!==null&&S!==void 0?S:s.getState())===m.PLAYING})),c=x(o,l).pipe($(()=>r.getValue()),q(_)),h=x(x(u,d,t),i).pipe($(()=>r.getValue()),q(_));return new ie().add(c.subscribe(p=>{n=p})).add(h.subscribe(p=>{if(J(n)||n===p)return;const v={from:n,to:p};n=void 0,a.next(v)}))});class Zm{constructor(e={}){if(this.subscription=new ie,this.logger=new Oo,this.isPlaybackStarted=!1,this.desiredState={playbackState:new de(m.STOPPED),seekState:new de({state:V.None}),volume:new de({volume:1,muted:!1}),videoTrack:new de(void 0),autoVideoTrackSwitching:new de(!0),autoVideoTrackLimits:new de({}),isLooped:new de(!1),playbackRate:new de(1),externalTextTracks:new de([]),currentTextTrack:new de(void 0),textTrackCuesSettings:new de({})},this.info={playbackState$:new y(m.STOPPED),position$:new y(0),duration$:new y(1/0),muted$:new y(!1),volume$:new y(1),availableQualities$:new y([]),availableQualitiesFps$:new y({}),availableAudioTracks$:new y([]),isAudioAvailable$:new y(!0),currentQuality$:new y(void 0),isAutoQualityEnabled$:new y(!0),autoQualityLimitingAvailable$:new y(!1),autoQualityLimits$:new y({}),currentPlaybackRate$:new y(1),currentBuffer$:new y({start:0,end:0}),isBuffering$:new y(!0),isStalled$:new y(!1),isEnded$:new y(!1),isLooped$:new y(!1),isLive$:new y(void 0),liveTime$:new y(void 0),currentFormat$:new y(void 0),availableTextTracks$:new y([]),currentTextTrack$:new y(void 0),throughputEstimation$:new y(void 0),rttEstimation$:new y(void 0),videoBitrate$:new y(void 0),hostname$:new y(void 0),httpConnectionType$:new y(void 0),httpConnectionReused$:new y(void 0),chromecastState$:new y(Ee.NOT_AVAILABLE),chromecastDeviceName$:new y(void 0),intrinsicVideoSize$:new y(void 0)},this.events={inited$:new C,started$:new C,willPause$:new C,willResume$:new C,willDestruct$:new C,watchCoverageRecord$:new C,watchCoverageLive$:new C,managedError$:new C,fatalError$:new C,ended$:new C,looped$:new C,seeked$:new C,willSeek$:new C,firstBytes$:new C,firstFrame$:new C,canplay$:new C,log$:new C},this.experimental={element$:new y(void 0),enableDebugTelemetry$:new y(!1),dumpTelemetry:Bf},this.initLogs(),this.tuning=qm(e),this.chromecastInitializer=new Fo({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new ni(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,p)=>{const v=typeof p;return["number","string","boolean"].includes(v)?p:p===null?null:`<${v}>`})),d=`Player.${String(i)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:L.WTF,message:l,thrown:o}),o}}}})}initVideo(e){var t,i,r;return this.config=e,this.domContainer=zm(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Mm({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},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(),(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=this.desiredState.playbackState;return e.getState()!==m.PLAYING&&e.startTransitionTo(m.PLAYING),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){return this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:V.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()===Ee.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()===Ee.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){P(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const i=t.find(r=>r.quality===e);return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.setState(e),this}setPlaybackRate(e){var t;P(this.providerContainer);const i=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return i&&(this.desiredState.playbackRate.setState(e),i.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return(e===void 0||!((t=this.providerContainer)===null||t===void 0)&&t.providerOutput.availableTextTracks$.getValue().find(i=>i.id===e))&&this.desiredState.currentTextTrack.startTransitionTo(e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){P(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(J(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===V.None?void 0:t.position;return _(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}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(x(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe($(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(q(({from:e})=>e===m.STOPPED),ge()).subscribe(()=>{this.initedAt=he(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.pipe(q(()=>!this.isPlaybackStarted),q(e=>e.to===m.PLAYING)).subscribe(()=>{this.isPlaybackStarted=!0,this.events.started$.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();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const u=this.desiredState.seekState.getState();u.state===V.Requested?this.desiredState.seekState.setState({...u,state:V.Applying}):this.events.managedError$.next({id:`WillSeekIn${u.state}`,category:L.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===V.Applying&&(this.desiredState.seekState.setState({state:V.None}),this.events.seeked$.next())})).add(e.current$.pipe($(u=>u.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe($(u=>u.destination),pe()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe($(u=>u.map(({quality:d})=>d).sort((d,l)=>ji(d)?1:ji(l)?-1:Fi(l,d)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(u=>{const d={};for(const l of u)l.fps&&(d[l.quality]=l.fps);this.info.availableQualitiesFps$.next(d)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(u=>{this.info.currentQuality$.next(u==null?void 0:u.quality),this.info.videoBitrate$.next(u==null?void 0:u.bitrate)})).add(e.providerOutput.hostname$.pipe(pe()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(pe()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(pe()).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.currentBuffer$.pipe($(u=>u?{start:u.from,end:u.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.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe($(u=>u.muted),pe()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe($(u=>u.volume),pe()).subscribe(this.info.volume$)).add(jm({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(x(e.providerOutput.endedEvent$.pipe($t(!0)),e.providerOutput.seekedEvent$.pipe($t(!1))).pipe(pe()).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($(u=>({id:"NoProviders",category:L.VIDEO_PIPELINE,message:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(ge(),$(()=>he()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(ge(),$(()=>he()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ge(),$(()=>he()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const t=new y(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new y(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(q(({to:u})=>u===m.PLAYING),ge()).subscribe(()=>i.next(!1)));let r=0;const a=x(e.providerOutput.isBuffering$,t,i).pipe($(()=>{const u=e.providerOutput.isBuffering$.getValue(),d=t.getValue()||i.getValue();return u&&!d}),pe());this.subscription.add(a.subscribe(u=>{u?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))}));const n=new ie;this.subscription.add(n);const o=x(M(window,"beforeunload"),this.events.willDestruct$,e.current$.pipe(q(u=>Boolean(u==null?void 0:u.provider))));e.providerOutput.isLive$.pipe(pe()).subscribe(u=>{switch(P(this.providerContainer),n.unsubscribe(),u){case!0:{const d=new y(void 0);n.add(this.providerContainer.providerOutput.liveTime$.subscribe(l=>d.next(l&&Math.floor(l/1e3)))),n.add(nn({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:o,looped$:this.events.looped$,position$:d}).pipe($(({from:l,to:c})=>({start:l,end:c}))).subscribe(this.events.watchCoverageLive$));break}case!1:n.add(nn({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:o,position$:this.providerContainer.providerOutput.position$}).pipe($(({from:d,to:l})=>({start:d,end:l}))).subscribe(this.events.watchCoverageRecord$));break}}),this.subscription.add(x(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:u==null?void 0:u.videoWidth,height:u==null?void 0:u.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(u=>{var d,l;const c=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(d=u==null?void 0:u.size)===null||d===void 0?void 0:d.width,height:(l=u==null?void 0:u.size)===null||l===void 0?void 0:l.height},{width:c==null?void 0:c.videoWidth,height:c==null?void 0:c.videoHeight})}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe($(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new ie;this.subscription.add(t),this.subscription.add(e.current$.pipe(pe((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(q(i=>i.length>0),ge()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:i})=>i===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=pi(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})),this.desiredState.videoTrack.startTransitionTo(t.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(x(this.desiredState.videoTrack.stateChangeStarted$.pipe($(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe($(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe($(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe($(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe($(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe($(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe($(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe($(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe($(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;P(this.providerContainer),P(t),Nf(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Of(i)),this.providerContainer.current$.subscribe(({type:i})=>Pi("provider",i)),t.duration$.subscribe(i=>Pi("duration",i)),t.availableVideoTracks$.pipe(q(i=>!!i.length),ge()).subscribe(i=>Pi("tracks",i)),this.events.fatalError$.subscribe(new Ye("fatalError")),this.events.managedError$.subscribe(new Ye("managedError")),t.position$.subscribe(new Ye("position")),t.currentVideoTrack$.pipe($(i=>i==null?void 0:i.quality)).subscribe(new Ye("quality")),this.info.currentBuffer$.subscribe(new Ye("buffer")),t.isBuffering$.subscribe(new Ye("isBuffering"))].forEach(i=>this.subscription.add(i)),Pi("codecs",Im())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>this.events.managedError$.next({id:"WakeLock",category:L.DOM,message:String(r)}))};this.subscription.add(x(M(document,"visibilitychange"),M(document,"fullscreenchange"),this.desiredState.playbackState.transitionEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===m.PLAYING,n=Boolean(e)&&!(e!=null&&e.released);r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}}const ev=`${Mo}@${Bo}`;export{Ee as ChromecastState,oi as HttpConnectionType,sv as Observable,m as PlaybackState,Zm as Player,ev as SDK_VERSION,rv as Subject,av as Subscription,nv as ValueSubject,b as VideoFormat,ae as VideoQuality};
|
|
6
|
+
import{ValueSubject as b,Subject as C,Subscription as ie,isNonNullable as w,ErrorCategory as x,isNullable as J,fromEvent as N,assertNever as O,merge as L,tap as Gr,map as $,observableFrom as ke,filterChanged as pe,assertNonNullable as R,debounce as Le,timeout as Vo,combine as et,once as ge,mapTo as wt,filter as q,now as he,Observable as mi,abortable as Me,getExponentialDelay as Yr,interval as Ho,Logger as Go}from"@vkontakte/videoplayer-shared/es2018.esm.js";import{Observable as Bv,Subject as Mv,Subscription as Nv,ValueSubject as Uv}from"@vkontakte/videoplayer-shared/es2018.esm.js";import Yo from"lodash/debounce.js";const qo="2.0.83-dev.65744ed.0",zo="es2018.esm.js";var m;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(m||(m={}));var y;(function(s){s.MPEG="MPEG",s.DASH="DASH",s.DASH_SEP="DASH_SEP",s.DASH_SEP_VK="DASH_SEP",s.DASH_WEBM="DASH_WEBM",s.DASH_WEBM_VK="DASH_WEBM",s.DASH_ONDEMAND="DASH_ONDEMAND",s.DASH_ONDEMAND_VK="DASH_ONDEMAND",s.DASH_LIVE="DASH_LIVE",s.DASH_LIVE_CMAF="DASH_LIVE_CMAF",s.DASH_LIVE_WEBM="DASH_LIVE_WEBM",s.HLS="HLS",s.HLS_ONDEMAND="HLS_ONDEMAND",s.HLS_JS="HLS",s.HLS_LIVE="HLS_LIVE",s.HLS_LIVE_CMAF="HLS_LIVE_CMAF",s.WEB_RTC_LIVE="WEB_RTC_LIVE"})(y||(y={}));var _e;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(_e||(_e={}));var Ee;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})(Ee||(Ee={}));var fi;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(fi||(fi={}));var V;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(V||(V={}));var jo=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 Wo{constructor(e){var t;this.connection$=new b(void 0),this.castState$=new b(Ee.NOT_AVAILABLE),this.errorEvent$=new C,this.realCastState$=new b(Ee.NOT_AVAILABLE),this.subscription=new ie,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=w((t=window.chrome)===null||t===void 0?void 0:t.cast),a=Boolean(window.__onGCastApiAvailable);r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||jo("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:x.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(){w(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();J(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();J(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(N(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 O(r.sessionState)}})).add(L(N(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Gr(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),$(r=>r.castState)),ke([i.getCastState()])).pipe(pe(),$(Qo),Gr(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===Ee.CONNECTED,o=w(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;(J(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===Ee.CONNECTED?w(this.connection$.getValue())?Ee.CONNECTED:Ee.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:x.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const Qo=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return Ee.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return Ee.AVAILABLE;case cast.framework.CastState.CONNECTING:return Ee.CONNECTING;case cast.framework.CastState.CONNECTED:return Ee.CONNECTED;default:return O(s)}};var qr=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},st=function(s){try{return!!s()}catch(e){return!0}},Jo=st,as=!Jo(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),vn=as,Sn=Function.prototype,ar=Sn.call,Ko=vn&&Sn.bind.bind(ar,ar),rt=vn?Ko:function(s){return function(){return ar.apply(s,arguments)}},gn=rt,Xo=gn({}.toString),Zo=gn("".slice),ns=function(s){return Zo(Xo(s),8,-1)},ed=rt,td=st,id=ns,ys=Object,sd=ed("".split),rd=td(function(){return!ys("z").propertyIsEnumerable(0)})?function(s){return id(s)=="String"?sd(s,""):ys(s)}:ys,os=function(s){return s==null},ad=os,nd=TypeError,Sr=function(s){if(ad(s))throw nd("Can't call method on "+s);return s},od=rd,dd=Sr,vi=function(s){return od(dd(s))},ud=function(){},zt={},_i=function(s){return s&&s.Math==Math&&s},je=_i(typeof globalThis=="object"&&globalThis)||_i(typeof window=="object"&&window)||_i(typeof self=="object"&&self)||_i(typeof qr=="object"&&qr)||function(){return this}()||Function("return this")(),nr=typeof document=="object"&&document.all,ld=typeof nr=="undefined"&&nr!==void 0,bn={all:nr,IS_HTMLDDA:ld},yn=bn,cd=yn.all,Oe=yn.IS_HTMLDDA?function(s){return typeof s=="function"||s===cd}:function(s){return typeof s=="function"},hd=je,fd=Oe,zr=hd.WeakMap,pd=fd(zr)&&/native code/.test(String(zr)),jr=Oe,Tn=bn,md=Tn.all,_t=Tn.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:jr(s)||s===md}:function(s){return typeof s=="object"?s!==null:jr(s)},vd=st,ft=!vd(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),jt={},Sd=je,Wr=_t,or=Sd.document,gd=Wr(or)&&Wr(or.createElement),En=function(s){return gd?or.createElement(s):{}},bd=ft,yd=st,Td=En,$n=!bd&&!yd(function(){return Object.defineProperty(Td("div"),"a",{get:function(){return 7}}).a!=7}),Ed=ft,$d=st,An=Ed&&$d(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Ad=_t,wd=String,_d=TypeError,kt=function(s){if(Ad(s))return s;throw _d(wd(s)+" is not an object")},kd=as,ki=Function.prototype.call,at=kd?ki.bind(ki):function(){return ki.apply(ki,arguments)},gr={},Ts=gr,Es=je,Rd=Oe,Qr=function(s){return Rd(s)?s:void 0},br=function(s,e){return arguments.length<2?Qr(Ts[s])||Qr(Es[s]):Ts[s]&&Ts[s][e]||Es[s]&&Es[s][e]},Pd=rt,yr=Pd({}.isPrototypeOf),Dd=typeof navigator!="undefined"&&String(navigator.userAgent)||"",wn=je,$s=Dd,Jr=wn.process,Kr=wn.Deno,Xr=Jr&&Jr.versions||Kr&&Kr.version,Zr=Xr&&Xr.v8,Be,Wi;Zr&&(Be=Zr.split("."),Wi=Be[0]>0&&Be[0]<4?1:+(Be[0]+Be[1]));!Wi&&$s&&(Be=$s.match(/Edge\/(\d+)/),(!Be||Be[1]>=74)&&(Be=$s.match(/Chrome\/(\d+)/),Be&&(Wi=+Be[1])));var Id=Wi,ea=Id,xd=st,_n=!!Object.getOwnPropertySymbols&&!xd(function(){var s=Symbol();return!String(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&ea&&ea<41}),Cd=_n,kn=Cd&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Ld=br,Od=Oe,Bd=yr,Md=kn,Nd=Object,Rn=Md?function(s){return typeof s=="symbol"}:function(s){var e=Ld("Symbol");return Od(e)&&Bd(e.prototype,Nd(s))},Ud=String,Tr=function(s){try{return Ud(s)}catch(e){return"Object"}},Fd=Oe,Vd=Tr,Hd=TypeError,Er=function(s){if(Fd(s))return s;throw Hd(Vd(s)+" is not a function")},Gd=Er,Yd=os,ds=function(s,e){var t=s[e];return Yd(t)?void 0:Gd(t)},As=at,ws=Oe,_s=_t,qd=TypeError,zd=function(s,e){var t,i;if(e==="string"&&ws(t=s.toString)&&!_s(i=As(t,s))||ws(t=s.valueOf)&&!_s(i=As(t,s))||e!=="string"&&ws(t=s.toString)&&!_s(i=As(t,s)))return i;throw qd("Can't convert object to primitive value")},Qi={},jd={get exports(){return Qi},set exports(s){Qi=s}},Wd=!0,ta=je,Qd=Object.defineProperty,Jd=function(s,e){try{Qd(ta,s,{value:e,configurable:!0,writable:!0})}catch(t){ta[s]=e}return e},Kd=je,Xd=Jd,ia="__core-js_shared__",Zd=Kd[ia]||Xd(ia,{}),Pn=Zd,sa=Pn;(jd.exports=function(s,e){return sa[s]||(sa[s]=e!==void 0?e:{})})("versions",[]).push({version:"3.27.2",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.27.2/LICENSE",source:"https://github.com/zloirock/core-js"});var eu=Sr,tu=Object,us=function(s){return tu(eu(s))},iu=rt,su=us,ru=iu({}.hasOwnProperty),nt=Object.hasOwn||function(e,t){return ru(su(e),t)},au=rt,nu=0,ou=Math.random(),du=au(1 .toString),Dn=function(s){return"Symbol("+(s===void 0?"":s)+")_"+du(++nu+ou,36)},uu=je,lu=Qi,ra=nt,cu=Dn,hu=_n,fu=kn,Nt=uu.Symbol,ks=lu("wks"),pu=fu?Nt.for||Nt:Nt&&Nt.withoutSetter||cu,Ue=function(s){return ra(ks,s)||(ks[s]=hu&&ra(Nt,s)?Nt[s]:pu("Symbol."+s)),ks[s]},mu=at,aa=_t,na=Rn,vu=ds,Su=zd,gu=Ue,bu=TypeError,yu=gu("toPrimitive"),Tu=function(s,e){if(!aa(s)||na(s))return s;var t=vu(s,yu),i;if(t){if(e===void 0&&(e="default"),i=mu(t,s,e),!aa(i)||na(i))return i;throw bu("Can't convert object to primitive value")}return e===void 0&&(e="number"),Su(s,e)},Eu=Tu,$u=Rn,$r=function(s){var e=Eu(s,"string");return $u(e)?e:e+""},Au=ft,wu=$n,_u=An,Ri=kt,oa=$r,ku=TypeError,Rs=Object.defineProperty,Ru=Object.getOwnPropertyDescriptor,Ps="enumerable",Ds="configurable",Is="writable";jt.f=Au?_u?function(e,t,i){if(Ri(e),t=oa(t),Ri(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Is in i&&!i[Is]){var r=Ru(e,t);r&&r[Is]&&(e[t]=i.value,i={configurable:Ds in i?i[Ds]:r[Ds],enumerable:Ps in i?i[Ps]:r[Ps],writable:!1})}return Rs(e,t,i)}:Rs:function(e,t,i){if(Ri(e),t=oa(t),Ri(i),wu)try{return Rs(e,t,i)}catch(r){}if("get"in i||"set"in i)throw ku("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var ls=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},Pu=ft,Du=jt,Iu=ls,Si=Pu?function(s,e,t){return Du.f(s,e,Iu(1,t))}:function(s,e,t){return s[e]=t,s},xu=Qi,Cu=Dn,da=xu("keys"),Ar=function(s){return da[s]||(da[s]=Cu(s))},wr={},Lu=pd,In=je,Ou=_t,Bu=Si,xs=nt,Cs=Pn,Mu=Ar,Nu=wr,ua="Object already initialized",dr=In.TypeError,Uu=In.WeakMap,Ji,pi,Ki,Fu=function(s){return Ki(s)?pi(s):Ji(s,{})},Vu=function(s){return function(e){var t;if(!Ou(e)||(t=pi(e)).type!==s)throw dr("Incompatible receiver, "+s+" required");return t}};if(Lu||Cs.state){var Ge=Cs.state||(Cs.state=new Uu);Ge.get=Ge.get,Ge.has=Ge.has,Ge.set=Ge.set,Ji=function(s,e){if(Ge.has(s))throw dr(ua);return e.facade=s,Ge.set(s,e),e},pi=function(s){return Ge.get(s)||{}},Ki=function(s){return Ge.has(s)}}else{var xt=Mu("state");Nu[xt]=!0,Ji=function(s,e){if(xs(s,xt))throw dr(ua);return e.facade=s,Bu(s,xt,e),e},pi=function(s){return xs(s,xt)?s[xt]:{}},Ki=function(s){return xs(s,xt)}}var Hu={set:Ji,get:pi,has:Ki,enforce:Fu,getterFor:Vu},Gu=as,xn=Function.prototype,la=xn.apply,ca=xn.call,Yu=typeof Reflect=="object"&&Reflect.apply||(Gu?ca.bind(la):function(){return ca.apply(la,arguments)}),qu=ns,zu=rt,Cn=function(s){if(qu(s)==="Function")return zu(s)},Ln={},On={},Bn={}.propertyIsEnumerable,Mn=Object.getOwnPropertyDescriptor,ju=Mn&&!Bn.call({1:2},1);On.f=ju?function(e){var t=Mn(this,e);return!!t&&t.enumerable}:Bn;var Wu=ft,Qu=at,Ju=On,Ku=ls,Xu=vi,Zu=$r,el=nt,tl=$n,ha=Object.getOwnPropertyDescriptor;Ln.f=Wu?ha:function(e,t){if(e=Xu(e),t=Zu(t),tl)try{return ha(e,t)}catch(i){}if(el(e,t))return Ku(!Qu(Ju.f,e,t),e[t])};var il=st,sl=Oe,rl=/#|\.prototype\./,gi=function(s,e){var t=nl[al(s)];return t==dl?!0:t==ol?!1:sl(e)?il(e):!!e},al=gi.normalize=function(s){return String(s).replace(rl,".").toLowerCase()},nl=gi.data={},ol=gi.NATIVE="N",dl=gi.POLYFILL="P",ul=gi,fa=Cn,ll=Er,cl=as,hl=fa(fa.bind),Nn=function(s,e){return ll(s),e===void 0?s:cl?hl(s,e):function(){return s.apply(e,arguments)}},Pi=je,fl=Yu,pl=Cn,ml=Oe,vl=Ln.f,Sl=ul,Ct=gr,gl=Nn,Lt=Si,pa=nt,bl=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 fl(s,this,arguments)};return e.prototype=s.prototype,e},cs=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?Pi:r?Pi[t]:(Pi[t]||{}).prototype,o=i?Ct:Ct[t]||Lt(Ct,t,{})[t],u=o.prototype,d,l,c,h,p,v,f,S,g;for(h in e)d=Sl(i?h:t+(r?".":"#")+h,s.forced),l=!d&&n&&pa(n,h),v=o[h],l&&(s.dontCallGetSet?(g=vl(n,h),f=g&&g.value):f=n[h]),p=l&&f?f:e[h],!(l&&typeof v==typeof p)&&(s.bind&&l?S=gl(p,Pi):s.wrap&&l?S=bl(p):a&&ml(p)?S=pl(p):S=p,(s.sham||p&&p.sham||v&&v.sham)&&Lt(S,"sham",!0),Lt(o,h,S),a&&(c=t+"Prototype",pa(Ct,c)||Lt(Ct,c,{}),Lt(Ct[c],h,p),s.real&&u&&(d||!u[h])&&Lt(u,h,p)))},ur=ft,yl=nt,Un=Function.prototype,Tl=ur&&Object.getOwnPropertyDescriptor,_r=yl(Un,"name"),El=_r&&function(){}.name==="something",$l=_r&&(!ur||ur&&Tl(Un,"name").configurable),Al={EXISTS:_r,PROPER:El,CONFIGURABLE:$l},Fn={},wl=Math.ceil,_l=Math.floor,kl=Math.trunc||function(e){var t=+e;return(t>0?_l:wl)(t)},Rl=kl,kr=function(s){var e=+s;return e!==e||e===0?0:Rl(e)},Pl=kr,Dl=Math.max,Il=Math.min,xl=function(s,e){var t=Pl(s);return t<0?Dl(t+e,0):Il(t,e)},Cl=kr,Ll=Math.min,Ol=function(s){return s>0?Ll(Cl(s),9007199254740991):0},Bl=Ol,Rr=function(s){return Bl(s.length)},Ml=vi,Nl=xl,Ul=Rr,ma=function(s){return function(e,t,i){var r=Ml(e),a=Ul(r),n=Nl(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}},Fl={includes:ma(!0),indexOf:ma(!1)},Vl=rt,Ls=nt,Hl=vi,Gl=Fl.indexOf,Yl=wr,va=Vl([].push),ql=function(s,e){var t=Hl(s),i=0,r=[],a;for(a in t)!Ls(Yl,a)&&Ls(t,a)&&va(r,a);for(;e.length>i;)Ls(t,a=e[i++])&&(~Gl(r,a)||va(r,a));return r},Vn=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],zl=ql,jl=Vn,Wl=Object.keys||function(e){return zl(e,jl)},Ql=ft,Jl=An,Kl=jt,Xl=kt,Zl=vi,ec=Wl;Fn.f=Ql&&!Jl?Object.defineProperties:function(e,t){Xl(e);for(var i=Zl(t),r=ec(t),a=r.length,n=0,o;a>n;)Kl.f(e,o=r[n++],i[o]);return e};var tc=br,ic=tc("document","documentElement"),sc=kt,rc=Fn,Sa=Vn,ac=wr,nc=ic,oc=En,dc=Ar,ga=">",ba="<",lr="prototype",cr="script",Hn=dc("IE_PROTO"),Os=function(){},Gn=function(s){return ba+cr+ga+s+ba+"/"+cr+ga},ya=function(s){s.write(Gn("")),s.close();var e=s.parentWindow.Object;return s=null,e},uc=function(){var s=oc("iframe"),e="java"+cr+":",t;return s.style.display="none",nc.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Gn("document.F=Object")),t.close(),t.F},Di,Gi=function(){try{Di=new ActiveXObject("htmlfile")}catch(e){}Gi=typeof document!="undefined"?document.domain&&Di?ya(Di):uc():ya(Di);for(var s=Sa.length;s--;)delete Gi[lr][Sa[s]];return Gi()};ac[Hn]=!0;var Yn=Object.create||function(e,t){var i;return e!==null?(Os[lr]=sc(e),i=new Os,Os[lr]=null,i[Hn]=e):i=Gi(),t===void 0?i:rc.f(i,t)},lc=st,cc=!lc(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),hc=nt,fc=Oe,pc=us,mc=Ar,vc=cc,Ta=mc("IE_PROTO"),hr=Object,Sc=hr.prototype,qn=vc?hr.getPrototypeOf:function(s){var e=pc(s);if(hc(e,Ta))return e[Ta];var t=e.constructor;return fc(t)&&e instanceof t?t.prototype:e instanceof hr?Sc:null},gc=Si,zn=function(s,e,t,i){return i&&i.enumerable?s[e]=t:gc(s,e,t),s},bc=st,yc=Oe,Tc=_t,Ec=Yn,Ea=qn,$c=zn,Ac=Ue,fr=Ac("iterator"),jn=!1,tt,Bs,Ms;[].keys&&(Ms=[].keys(),"next"in Ms?(Bs=Ea(Ea(Ms)),Bs!==Object.prototype&&(tt=Bs)):jn=!0);var wc=!Tc(tt)||bc(function(){var s={};return tt[fr].call(s)!==s});wc?tt={}:tt=Ec(tt);yc(tt[fr])||$c(tt,fr,function(){return this});var Wn={IteratorPrototype:tt,BUGGY_SAFARI_ITERATORS:jn},_c=Ue,kc=_c("toStringTag"),Qn={};Qn[kc]="z";var Pr=String(Qn)==="[object z]",Rc=Pr,Pc=Oe,Yi=ns,Dc=Ue,Ic=Dc("toStringTag"),xc=Object,Cc=Yi(function(){return arguments}())=="Arguments",Lc=function(s,e){try{return s[e]}catch(t){}},hs=Rc?Yi:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=Lc(e=xc(s),Ic))=="string"?t:Cc?Yi(e):(i=Yi(e))=="Object"&&Pc(e.callee)?"Arguments":i},Oc=Pr,Bc=hs,Mc=Oc?{}.toString:function(){return"[object "+Bc(this)+"]"},Nc=Pr,Uc=jt.f,Fc=Si,Vc=nt,Hc=Mc,Gc=Ue,$a=Gc("toStringTag"),Jn=function(s,e,t,i){if(s){var r=t?s:s.prototype;Vc(r,$a)||Uc(r,$a,{configurable:!0,value:e}),i&&!Nc&&Fc(r,"toString",Hc)}},Yc=Wn.IteratorPrototype,qc=Yn,zc=ls,jc=Jn,Wc=zt,Qc=function(){return this},Jc=function(s,e,t,i){var r=e+" Iterator";return s.prototype=qc(Yc,{next:zc(+!i,t)}),jc(s,r,!1,!0),Wc[r]=Qc,s},Kc=cs,Xc=at,Kn=Al,Zc=Jc,eh=qn,th=Jn,Aa=zn,ih=Ue,wa=zt,Xn=Wn,sh=Kn.PROPER;Kn.CONFIGURABLE;Xn.IteratorPrototype;var Ii=Xn.BUGGY_SAFARI_ITERATORS,Ns=ih("iterator"),_a="keys",xi="values",ka="entries",rh=function(){return this},ah=function(s,e,t,i,r,a,n){Zc(t,e,i);var o=function(g){if(g===r&&h)return h;if(!Ii&&g in l)return l[g];switch(g){case _a:return function(){return new t(this,g)};case xi:return function(){return new t(this,g)};case ka:return function(){return new t(this,g)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,l=s.prototype,c=l[Ns]||l["@@iterator"]||r&&l[r],h=!Ii&&c||o(r),p=e=="Array"&&l.entries||c,v,f,S;if(p&&(v=eh(p.call(new s)),v!==Object.prototype&&v.next&&(th(v,u,!0,!0),wa[u]=rh)),sh&&r==xi&&c&&c.name!==xi&&(d=!0,h=function(){return Xc(c,this)}),r)if(f={values:o(xi),keys:a?h:o(_a),entries:o(ka)},n)for(S in f)(Ii||d||!(S in l))&&Aa(l,S,f[S]);else Kc({target:e,proto:!0,forced:Ii||d},f);return n&&l[Ns]!==h&&Aa(l,Ns,h,{name:r}),wa[e]=h,f},nh=function(s,e){return{value:s,done:e}},oh=vi,Dr=ud,Ra=zt,Zn=Hu,dh=jt.f,uh=ah,Ci=nh,lh=Wd,ch=ft,eo="Array Iterator",hh=Zn.set,fh=Zn.getterFor(eo);uh(Array,"Array",function(s,e){hh(this,{type:eo,target:oh(s),index:0,kind:e})},function(){var s=fh(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,Ci(void 0,!0)):t=="keys"?Ci(i,!1):t=="values"?Ci(e[i],!1):Ci([i,e[i]],!1)},"values");var Pa=Ra.Arguments=Ra.Array;Dr();Dr();Dr();if(!lh&&ch&&Pa.name!=="values")try{dh(Pa,"name",{value:"values"})}catch(s){}var ph=Ue,mh=zt,vh=ph("iterator"),Sh=Array.prototype,gh=function(s){return s!==void 0&&(mh.Array===s||Sh[vh]===s)},bh=hs,Da=ds,yh=os,Th=zt,Eh=Ue,$h=Eh("iterator"),to=function(s){if(!yh(s))return Da(s,$h)||Da(s,"@@iterator")||Th[bh(s)]},Ah=at,wh=Er,_h=kt,kh=Tr,Rh=to,Ph=TypeError,Dh=function(s,e){var t=arguments.length<2?Rh(s):e;if(wh(t))return _h(Ah(t,s));throw Ph(kh(s)+" is not iterable")},Ih=at,Ia=kt,xh=ds,Ch=function(s,e,t){var i,r;Ia(s);try{if(i=xh(s,"return"),!i){if(e==="throw")throw t;return t}i=Ih(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return Ia(i),t},Lh=Nn,Oh=at,Bh=kt,Mh=Tr,Nh=gh,Uh=Rr,xa=yr,Fh=Dh,Vh=to,Ca=Ch,Hh=TypeError,qi=function(s,e){this.stopped=s,this.result=e},La=qi.prototype,Gh=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=Lh(e,i),d,l,c,h,p,v,f,S=function(E){return d&&Ca(d,"normal",E),new qi(!0,E)},g=function(E){return r?(Bh(E),o?u(E[0],E[1],S):u(E[0],E[1])):o?u(E,S):u(E)};if(a)d=s.iterator;else if(n)d=s;else{if(l=Vh(s),!l)throw Hh(Mh(s)+" is not iterable");if(Nh(l)){for(c=0,h=Uh(s);h>c;c++)if(p=g(s[c]),p&&xa(La,p))return p;return new qi(!1)}d=Fh(s,l)}for(v=a?s.next:d.next;!(f=Oh(v,d)).done;){try{p=g(f.value)}catch(E){Ca(d,"throw",E)}if(typeof p=="object"&&p&&xa(La,p))return p}return new qi(!1)},Yh=$r,qh=jt,zh=ls,jh=function(s,e,t){var i=Yh(e);i in s?qh.f(s,i,zh(0,t)):s[i]=t},Wh=cs,Qh=Gh,Jh=jh;Wh({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Qh(e,function(i,r){Jh(t,i,r)},{AS_ENTRIES:!0}),t}});var Kh=gr,Xh=Kh.Object.fromEntries,Zh={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},ef=Zh,tf=je,sf=hs,rf=Si,Oa=zt,af=Ue,Ba=af("toStringTag");for(var Us in ef){var Ma=tf[Us],Fs=Ma&&Ma.prototype;Fs&&sf(Fs)!==Ba&&rf(Fs,Ba,Us),Oa[Us]=Oa.Array}var nf=Xh,of=nf,df=of,uf=df,bi=uf,Ft;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(Ft||(Ft={}));var Vt=(s,e=0,t=Ft.OFFSET_P)=>{switch(t){case Ft.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Ft.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}default:O(t)}return s},P=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)},ae;(function(s){s.INVARIANT="Invariant quality",s.Q_144P="144p",s.Q_240P="240p",s.Q_360P="360p",s.Q_480P="480p",s.Q_720P="720p",s.Q_1080P="1080p",s.Q_1440P="1440p",s.Q_2160P="2160p",s.Q_4320P="4320p"})(ae||(ae={}));const Ne={[ae.Q_144P]:{width:256,height:144},[ae.Q_240P]:{width:428,height:240},[ae.Q_360P]:{width:640,height:360},[ae.Q_480P]:{width:856,height:480},[ae.Q_720P]:{width:1280,height:720},[ae.Q_1080P]:{width:1920,height:1080},[ae.Q_1440P]:{width:2560,height:1440},[ae.Q_2160P]:{width:3840,height:2160},[ae.Q_4320P]:{width:7680,height:4320}},zi=(s,e)=>Ne[s].height>Ne[e].height,lf=(s,e)=>Ne[s].height>=Ne[e].height,li=(s,e)=>Ne[s].height<Ne[e].height,cf=(s,e)=>Ne[s].height<=Ne[e].height,hf=s=>s.sort((e,t)=>e===t?0:e===ae.INVARIANT?1:t===ae.INVARIANT?-1:li(e,t)?1:-1)[0],ff=Object.keys(Ne).sort((s,e)=>li(s,e)?-1:1),Rt=({width:s,height:e})=>{const t=Math.min(s,e),i=Math.max(s,e);return ff.find(r=>{const a=Ne[r];return a.width>=i&&a.height>=t})},pf=s=>Ne[s].height,Xi=s=>s===ae.INVARIANT;class de{constructor(e){this.transitionStarted$=new C,this.transitionEnded$=new C,this.transitionUpdated$=new C,this.forceChanged$=new C,this.stateChangeStarted$=L(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=L(this.transitionEnded$,this.forceChanged$),this.state=e}setState(e){const t=this.transition,i=this.state;this.transition=void 0,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||w(t)&&t.to===e||(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}}const mf=s=>{switch(s){case y.MPEG:case y.DASH:case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.HLS:case y.HLS_ONDEMAND:return!1;case y.DASH_LIVE:case y.DASH_LIVE_CMAF:case y.HLS_LIVE:case y.HLS_LIVE_CMAF:case y.DASH_LIVE_WEBM:case y.WEB_RTC_LIVE:return!0;default:return O(s)}};var Y;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Y||(Y={}));const vf=5,Sf=5,gf=500,Na=7e3;class bf{constructor(e){this.subscription=new ie,this.loadMediaTimeoutSubscription=new ie,this.videoState=new de(Y.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!==Y.STOPPED&&(this.videoState.startTransitionTo(Y.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==m.PAUSED&&o.state===V.Requested&&i!==Y.STOPPED){this.seek(o.position/1e3);return}switch(a){case m.READY:{switch(i){case Y.PLAYING:case Y.PAUSED:case Y.READY:break;case Y.STOPPED:this.videoState.startTransitionTo(Y.READY),this.prepare();break;default:O(i)}break}case m.PLAYING:{switch(i){case Y.PLAYING:break;case Y.PAUSED:this.videoState.startTransitionTo(Y.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case Y.READY:this.videoState.startTransitionTo(Y.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case Y.STOPPED:this.videoState.startTransitionTo(Y.READY),this.prepare();break;default:O(i)}break}case m.PAUSED:{switch(i){case Y.PLAYING:this.videoState.startTransitionTo(Y.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case Y.PAUSED:break;case Y.READY:this.videoState.startTransitionTo(Y.PAUSED),this.videoState.setState(Y.PAUSED);break;case Y.STOPPED:this.videoState.startTransitionTo(Y.READY),this.prepare();break;default:O(i)}break}default:O(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(mf(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new ie;this.subscription.add(e),this.subscription.add(L(this.videoState.stateChangeStarted$.pipe($(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe($(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));const t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const r=new C;e.add(r.pipe(Le(gf)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(N(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===V.Applying||Math.abs(o-a)>vf)&&r.next(o),a=o})),e.add(N(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(N(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(N(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(N(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<Sf&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(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:O(n)}}),t(N(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(N(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const i=L(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Le(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(Y.PAUSED),P(this.params.desiredState.playbackState,m.PAUSED)):(this.videoState.setState(Y.PLAYING),P(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:V.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)===Y.PAUSED||e===Y.PLAYING)&&(this.videoState.setState(Y.PAUSED),P(this.params.desiredState.playbackState,m.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===Y.PLAYING||e===Y.PAUSED)&&(this.videoState.setState(Y.PLAYING),P(this.params.desiredState.playbackState,m.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===Y.READY&&this.videoState.setState(Y.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===m.READY&&P(this.params.desiredState.playbackState,m.READY)}handleRemoteStop(){this.videoState.getState()!==Y.STOPPED&&this.videoState.setState(Y.STOPPED)}handleRemoteVolumeChange(e){var t,i;const r=this.params.output.volume$.getValue(),a={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(i=e.muted)!==null&&i!==void 0?i:r.muted};(a.volume!==r.volume||a.muted!==a.muted)&&this.params.output.volume$.next(a)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const i=this.params.source;let r,a,n;switch(e){case y.MPEG:{const l=i[e];R(l);const c=hf(Object.keys(l));R(c);const h=l[c];R(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case y.HLS:case y.HLS_ONDEMAND:{const l=i[e];R(l),r=l.url,a="application/x-mpegurl",n=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:{const l=i[e];R(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_LIVE_CMAF:{const l=i[e];R(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const l=i[e];R(l),r=Vt(l.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case y.DASH:case y.DASH_LIVE:case y.WEB_RTC_LIVE:{const l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:x.VIDEO_PIPELINE,message:l,thrown:c}),c}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return O(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 w(u)&&(o.metadata.title=u),w(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===V.Applying||i.state===V.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(Vo(Na).subscribe(()=>a(`timeout(${Na})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===V.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:x.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}class Ua{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 io extends Ua{constructor(){super(),this.listeners||Ua.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 so=class{constructor(){Object.defineProperty(this,"signal",{value:new io,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&&(so.prototype[Symbol.toStringTag]="AbortController",io.prototype[Symbol.toStringTag]="AbortSignal");function ro(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 yf(s){typeof s=="function"&&(s={fetch:s});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!ro({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(p){c=new Error("Aborted"),c.name="AbortError"}if(l.aborted)return Promise.reject(c);const h=new Promise((p,v)=>{l.addEventListener("abort",()=>v(c),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([h,n(u,d)])}return n(u,d)},Request:a}}const fs=ro({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),ao=fs?yf({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ht=fs?ao.fetch:window.fetch;fs?ao.Request:window.Request;const $t=fs?so:window.AbortController,ni=s=>s.range?s.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class ci{constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){var t;const{url:i}=e.request,r=(t=this.dashJsRequestQueue.get(i))!==null&&t!==void 0?t:[];r.push(e),this.dashJsRequestQueue.set(i,r)}async executeNextRequests(){for(const[e,t]of this.dashJsRequestQueue.entries()){const i=this.activeRequests.get(e);if(i){t.length&&this.onBigRequestProgress(i);const r=t[0];if(!r||!r.request.range)continue;const[a,n]=ni(r.request);if(a>=i.from&&n<=i.to)continue;this.activeRequests.delete(e)}if(t.length){const r=this.sendBigRequest(e,t.map(({request:a})=>a));this.activeRequests.set(e,r)}}}abort(e){var t;if(e){const{request:i}=e,r=((t=this.dashJsRequestQueue.get(i.url))!==null&&t!==void 0?t:[]).includes(e),a=this.activeRequests.get(i.url);r&&a&&a.abortController.abort()}else for(const{abortController:i}of this.activeRequests.values())i.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const i=t.map(ni),r=i[0][0];let a=i[0][1];for(let h=1;h<i.length&&a<this.params.minDataSize;h++){const p=i[h][1];p-r<=2*this.params.minDataSize&&(a=Math.max(a,p))}r===0?a=Math.max(a,r+this.params.minInitSize):a=Math.max(a,r+this.params.minDataSize);const n=new URL(e,location.href);n.searchParams.append("bytes",`${r}-${a}`);const o=n.toString(),u=new $t,d=u.signal,l={url:e,from:r,to:a,loaded:0,data:null,abortController:u};d.addEventListener("abort",()=>this.onBigRequestAbort(l));const c=h=>{var p,v;throw(v=(p=this.params).onError)===null||v===void 0||v.call(p,{id:"BigRequestParsing",category:x.PARSER,message:"Error parsing response data",thrown:h}),h};return Ht(o,{signal:d}).then(h=>{var p,v,f;if(l.response=h,!h.ok||!h.body){this.onBigRequestError(l);return}const[S,g]=h.body.tee();(v=(p=this.params).onDownloadStream)===null||v===void 0||v.call(p,g);const E=S.getReader(),I=parseInt((f=h.headers.get("Content-Length"))!==null&&f!==void 0?f:"",10)||a-r+1;l.data=new ArrayBuffer(I);const _=new Uint8Array(l.data),A=async({done:B,value:K})=>{B?this.onBigRequestProgress(l):K&&(_.set(K,l.loaded),l.loaded+=K.byteLength,this.onBigRequestProgress(l),await(E==null?void 0:E.read().then(A,ci.suppressStreamErrors).catch(c)))};E==null||E.read().then(A,ci.suppressStreamErrors).catch(c)},ci.suppressAbort).catch(h=>this.onBigRequestError(l,h)),l}onBigRequestProgress({url:e,from:t,to:i,loaded:r,data:a,response:n}){var o,u,d,l,c,h,p,v;if(!this.activeRequests.has(e)||!a)return;const f=(o=this.dashJsRequestQueue.get(e))!==null&&o!==void 0?o:[];for(const S of f){const{request:g}=S,[E,I]=ni(g),_=E>=t&&I<=t+r,A=t>=E&&t+r<I,B=a.slice(E-t,Math.min(I-t+1,r));if((_||A)&&(g.requestStartDate=(u=g.requestStartDate)!==null&&u!==void 0?u:new Date,g.firstByteDate=(d=g.firstByteDate)!==null&&d!==void 0?d:new Date,g.bytesLoaded=B.byteLength,g.bytesTotal=i-t),_){g.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[]).filter(G=>G!==S)),(c=S.success)===null||c===void 0||c.call(S,B,"",e);const K=n?Array.from(n.headers.entries()).map(([G,U])=>`${G}: ${U}`).join(`\r
|
|
7
|
+
`):"";(h=this.dashMetrics)===null||h===void 0||h.addHttpRequest(g,e,(p=n==null?void 0:n.status)!==null&&p!==void 0?p:200,K,[])}else A&&((v=S.progress)===null||v===void 0||v.call(S,{loaded:r,total:i-t,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:t,to:i},r){var a,n,o,u;if((n=(a=this.params).onError)===null||n===void 0||n.call(a,{id:"BigRequest",category:x.NETWORK,message:"Download error",thrown:r}),!this.activeRequests.has(e))return;const d=(o=this.dashJsRequestQueue.get(e))!==null&&o!==void 0?o:[];for(const l of d){const[c,h]=ni(l.request);(c>=t&&c<i||h>t&&h<=i)&&((u=l==null?void 0:l.error)===null||u===void 0||u.call(l,l.request,String(r)))}if(this.activeRequests.delete(e),r)throw r}onBigRequestAbort({url:e,from:t,to:i}){var r,a;if(!this.activeRequests.has(e))return;const n=(r=this.dashJsRequestQueue.get(e))!==null&&r!==void 0?r:[];for(const o of n){const[u,d]=ni(o.request);(u>=t&&u<i||d>t&&d<=i)&&((a=o==null?void 0:o.abort)===null||a===void 0||a.call(o,o.request))}this.activeRequests.delete(e)}static suppressAbort(e){if(!(e instanceof DOMException)||!(e.name==="AbortError"||e.code===20))throw e}static suppressStreamErrors(){}}class Zi{constructor(e,t,i){this.baseLoader=e,this.config=i,this.bigRequest=t,t.setMetrics(i.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(Zi.shouldDelegateToBase(t))return this.baseLoader.load(e);this.bigRequest.queueDashJSRequest(e),this.bigRequest.executeNextRequests()}abort(e){if(!e){this.baseLoader.abort(),this.bigRequest.abort();return}const{request:t}=e;Zi.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const Tf=(s,e)=>t=>({create:i=>{const r=s(t).create(i);return new Zi(r,e,i)}}),Ef=(s,e)=>{const t=new ci(e);return s.extend("SchemeLoaderFactory",function(){const{parent:i}=this,r=i.getLoader;return{getLoader:a=>{const n=r(a);return Tf(n,t)}}},!0),()=>t.destroy()};var $f=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)},Af=s=>{const e=new b(1/0),t=new C,i=new b(void 0),r=new b(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},u=l=>{var c,h,p,v,f;const S=bi(l.getAllResponseHeaders().trim().split(/[\n\r]+/).map(I=>I.split(": ")));if("x-playback-duration"in S||"x-playback-duration-millis"in S){const I=parseInt((c=l.getResponseHeader("X-Playback-Duration"))!==null&&c!==void 0?c:"",10),_=parseInt((h=l.getResponseHeader("X-Playback-Duration-Millis"))!==null&&h!==void 0?h:"",10),A=(p=_!=null?_:I*1e3)!==null&&p!==void 0?p:NaN;w(A)&&!isNaN(A)&&e.next(A)}const g=(v=S["x-delivery-type"])!==null&&v!==void 0?v:fi.HTTP1,E=(f={1:!0,0:!1}[S["x-reused"]])!==null&&f!==void 0?f:void 0;i.next(g),r.next(E)},d=l=>{l.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return s.extend("XHRLoader",function(){const{parent:l}=this,c=l.load.bind(l);return{load:function(h){if(h.request.type==="MPD"){const p=h.onload,v=h.progress;h.onload=function(...f){return u(this),p(...f)},h.progress=function(...f){return d(this),v(...f)},o()}return c(h)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:i}},Gt=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},wf=s=>s.extend("RequestModifier",()=>({modifyRequestURL:Gt}),!0),_f=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 ze=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=s.getState(),o=e(),u=J(r),d=new ie;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},Pt=(s,e,t)=>ze(e,()=>s.loop,i=>{w(i)&&(s.loop=i)},{onError:t}),ot=(s,e,t,i)=>ze(e,()=>({muted:s.muted,volume:s.volume}),r=>{w(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}),pt=(s,e,t,i)=>ze(e,()=>s.playbackRate,r=>{w(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),kf=s=>["__",s.language,s.label].join("|"),Rf=(s,e)=>{if(s.id===e)return!0;const[t,i,r]=e.split("|");return s.language===i&&s.label===r};class We{constructor(){this.available$=new C,this.current$=new b(void 0),this.error$=new C,this.subscription=new ie,this.externalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:x.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(ze(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{w(a)&&this.setExternal(a)},{equal:(a,n)=>w(a)&&w(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe($(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(ze(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(ze(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(N(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();this.select(i)})),this.subscription.add(L(N(e,"addtrack"),N(e,"removetrack"),ke(["init"])).pipe($(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),pe((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(L(N(e,"change"),ke(["init"])).pipe($(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),$(i=>i&&this.htmlTextTrackToITextTrack(i).id),pe()).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(N(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 p=(d=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&d!==void 0?d:null;p&&p.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(N(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;w(t.align)&&(r.align=t.align),w(t.position)&&(r.position=t.position),w(t.size)&&(r.size=t.size),w(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){R(this.video);const t=[...this.video.textTracks];return e?t:t.filter(We.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,r=e.id!==""?e.id:kf(e);return this.externalTracks.has(r)?{id:r,type:"external",language:t,label:i,url:this.externalTracks.get(r).url}:{id:r,type:"internal",language:t,label:i}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.id===""&&e.label===""&&e.language==="")}setExternal(e){e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks.keys()).filter(t=>!e.find(i=>i.id===t)).forEach(t=>this.detach(t))}select(e){R(this.video);for(const t of this.htmlTextTracksAsArray(!0))w(e)&&Rf(t,e)?t.mode="showing":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),this.externalTracks.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);t&&this.video.removeChild(t),this.externalTracks.delete(e)}}var dt=s=>{const e=document.createElement("video");return e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),s.appendChild(e),e};class Ir{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){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0}}var no=()=>{const{userAgent:s}=window.navigator;return!/chrome/i.test(s)&&/webkit|safari|khtml/i.test(s)};const pr=3;class Pf{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<pr&&(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||pr))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 oo=(s,e,t=pr)=>{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 Df=50,If=s=>s.webkitAudioDecodedByteCount!=="undefined"?!!s.webkitAudioDecodedByteCount:s.mozHasAudio!=="undefined"?s.mozHasAudio:s.audioTracks?!!s.audioTracks.length:!0,ut=s=>{const e=v=>N(s,v).pipe(wt(void 0)),i=L(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>N(s,v))).pipe($(v=>v.type==="ended"?s.readyState<2:s.readyState<3),pe()),r=L(N(s,"progress"),N(s,"timeupdate")).pipe($(()=>oo(s.buffered,s.currentTime))),a=no()?et({play:e("play").pipe(ge()),playing:e("playing")}).pipe(wt(void 0)):e("playing"),n=N(s,"playing").pipe(Le(Df),$(()=>If(s))),o=N(s,"volumechange").pipe($(()=>({muted:s.muted,volume:s.volume}))),u=N(s,"ratechange").pipe($(()=>s.playbackRate)),d=N(s,"error").pipe(q(()=>Boolean(s.error||s.played.length)),$(()=>{var v;const f=s.error;return{id:f?`MediaError#${f.code}`:"HtmlVideoError",category:x.VIDEO_PIPELINE,message:f?f.message:"Error event from HTML video element",thrown:(v=s.error)!==null&&v!==void 0?v:void 0}})),l=N(s,"timeupdate").pipe($(()=>s.currentTime)),c=new C,h=.3;let p;return l.subscribe(v=>{s.loop&&w(p)&&w(v)&&p>=s.duration-h&&v<=h&&c.next(p),p=v}),{playing$:a,pause$:e("pause").pipe(q(()=>!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$:N(s,"durationchange").pipe($(()=>s.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:o,isAudioAvailable$:n,playbackRateState$:u}},xr=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var xf=cs,Cf=us,Lf=Rr,Of=kr;xf({target:"Array",proto:!0},{at:function(e){var t=Cf(this),i=Lf(t),r=Of(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});var Bf=br,uo=Bf,Mf=uo,Nf=Mf("Array","at"),Uf=Nf,Ff=Uf,Vf=Ff,Hf=Vf,Xe=Hf;let Cr=!1,Ze={};const Gf=s=>{Cr=s},Yf=()=>{Ze={}},qf=s=>{s(Ze)},Li=(s,e)=>{var t;Cr&&(Ze.meta=(t=Ze.meta)!==null&&t!==void 0?t:{},Ze.meta[s]=e)};class Ye{constructor(e){this.name=e}next(e){var t,i;if(!Cr)return;Ze.series=(t=Ze.series)!==null&&t!==void 0?t:{};const r=(i=Ze.series[this.name])!==null&&i!==void 0?i:[];r.push([Date.now(),e]),Ze.series[this.name]=r}}const zf=new Ye("best_bitrate"),jf=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class Wf{constructor(){this.history={}}recordSelection(e){this.history[e.id]=he()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const yi=(s,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:d})=>{var l,c,h,p;const v=i.usePixelRatio&&(l=window.devicePixelRatio)!==null&&l!==void 0?l:1,f=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*v*i.containerSizeFactor,height:e.height*v*i.containerSizeFactor},S=f&&Rt(f),g=i.considerPlaybackRate&&w(o)?o:1,E=s.filter(F=>!Xi(F.quality)).sort((F,M)=>zi(F.quality,M.quality)?-1:1),I=(c=Xe(E,-1))===null||c===void 0?void 0:c.quality,_=(h=Xe(E,0))===null||h===void 0?void 0:h.quality,A=J(r)||w(r.min)&&w(r.max)&&li(r.max,r.min)||w(r.min)&&_&&zi(r.min,_)||w(r.max)&&I&&li(r.max,I),B=g*jf(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),G=E.filter(F=>{const M=S?li(F.quality,S):!0,te=w(t)&&isFinite(t)&&w(F.bitrate)?t-a>=F.bitrate*B:!0,ue=i.lazyQualitySwitch&&w(i.minBufferToSwitchUp)&&u&&!Xi(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&zi(F.quality,u.quality),me=A||(J(r.max)||cf(F.quality,r.max))&&(J(r.min)||lf(F.quality,r.min));return M&&te&&!ue&&me})[0];G&&G.bitrate&&zf.next(G.bitrate);const U=(p=G!=null?G:E[Math.ceil((E.length-1)/2)])!==null&&p!==void 0?p:s[0],X=U&&d&&d.history[U.id]&&he()-d.history[U.id]<=i.trackCooldown&&(!d.last||U.id!==d.last.id);if(U!=null&&U.id&&d&&!X&&d.recordSelection(U),X&&(d!=null&&d.last)){const F=d.last;return d==null||d.recordSwitch(F),F}return d==null||d.recordSwitch(U),U};var Ae=s=>new URL(s).hostname;const Qf=300,es=(s,e=Qf)=>new mi(t=>{const{width:i,height:r}=s.getBoundingClientRect();if(t.next({width:i,height:r}),!window.ResizeObserver)return;const a=new ResizeObserver(Yo(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),w(u)&&w(d)&&t.next({width:u,height:d})},e));return a.observe(s),()=>a.disconnect()}),Jf=5e3,oi={};var z;(function(s){s.DOWNLOADING_LIB="downloading_lib",s.STOPPED="stopped",s.STREAM_INITIALIZED="stream_initialized",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(z||(z={}));const Se=(s,e)=>new mi(t=>{const i=r=>t.next(r);return s.on(e,i),()=>s.off(e,i)});class Fa{constructor(e){this.subscription=new ie,this.videoState=new de(z.DOWNLOADING_LIB),this.textTracksManager=new We,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new b(void 0),this.maxSeekBackTime$=new b(1/0),this.availableFrom$=new b(void 0),this.elementSize$=new b(void 0),this.liveOffset=new Ir,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===z.DOWNLOADING_LIB||t===z.STREAM_INITIALIZED))switch((r==null?void 0:r.to)!==m.PAUSED&&a.state===V.Requested&&t!==z.STOPPED&&i!==m.STOPPED&&(n?this.seek(a.position-this.liveOffset.getTotalPausedTime()):this.seek(a.position)),i){case m.STOPPED:{switch(t){case z.STOPPED:break;case z.PLAYING:case z.PAUSED:case z.READY:this.stop();break;default:O(t)}break}case m.READY:{switch(t){case z.STOPPED:this.prepare();break;case z.PLAYING:case z.PAUSED:case z.READY:break;default:O(t)}break}case m.PLAYING:{switch(t){case z.PLAYING:break;case z.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 z.READY:this.play();break;case z.STOPPED:this.prepare();break;default:O(t)}break}case m.PAUSED:{switch(t){case z.PLAYING:this.pause(),this.liveOffset.pause();break;case z.PAUSED:break;case z.READY:this.videoState.setState(z.PAUSED),P(this.params.desiredState.playbackState,m.PAUSED);break;case z.STOPPED:this.prepare();break;default:O(t)}break}default:O(i)}},this.video=dt(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(Ae(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:x.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"),Jf);import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(oi.MediaPlayer=r.MediaPlayer,oi.Debug=r.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){R(oi.MediaPlayer,"dashjs not loaded"),R(oi.Debug,"dashjs not loaded"),this.player=oi.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(t=>(t.height&&(this.frameRatesByFrameHeight[t.height]=t.frameRate?xr(t.frameRate+""):void 0),!0)),(this.params.format===y.DASH_WEBM||this.params.format===y.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=Ef(this.player,{minInitSize:this.params.tuning.bigRequestMinInitSize,minDataSize:this.params.tuning.bigRequestMinDataSize,onError:t=>this.params.output.error$.next(t),onDownloadStream:t=>this.params.dependencies.throughputEstimator.trackStream(t)}):this.params.tuning.stripRangeHeader&&_f(this.player),$f(this.player),this.params.tuning.requestQuick&&wf(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(z.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=f=>{e.error$.next({id:"DashIFProvider",category:x.WTF,message:"DashIFProvider internal logic error",thrown:f})},r=(f,S)=>this.subscription.add(f.subscribe(S,i));r(es(this.video),this.elementSize$),r(Se(this.player,"error").pipe($(f=>{const S=typeof f.error=="object"?f.error.code:f.error,g=typeof f.error=="object"?f.error.message:void 0;return{id:`DashJS#${S}`,message:g}})),e.error$),r(Se(this.player,"playbackError").pipe($(f=>({id:"DashJSPlayback",message:f.error}))),e.error$);const a=Se(this.player,"qualityChangeRendered").pipe(q(({mediaType:f})=>f==="video"),$(({newQuality:f})=>{var S;return(S=this.videoTracks.find(({bitrateInfo:g})=>g.qualityIndex===f))===null||S===void 0?void 0:S.track}));a.pipe(q(w)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(q(({to:f})=>f===z.STREAM_INITIALIZED),ge()).subscribe(()=>{this.subscription.add(ze(t.videoTrack,()=>{var f,S;const g=this.player.getQualityFor("video");return(S=(f=this.videoTracks.find(({bitrateInfo:E})=>E.qualityIndex===g))===null||f===void 0?void 0:f.track)===null||S===void 0?void 0:S.id},f=>{var S;if(J(f))return;const g=(S=this.videoTracks.find(({track:E})=>E.id===f))===null||S===void 0?void 0:S.bitrateInfo;g&&this.player.setQualityFor("video",g.qualityIndex)},{changed$:a.pipe($(f=>f==null?void 0:f.id)),onError:i}))},i)),this.subscription.add(ze(t.autoVideoTrackSwitching,()=>{var f,S,g;return(g=(S=(f=this.player.getSettings().streaming)===null||f===void 0?void 0:f.abr)===null||S===void 0?void 0:S.autoSwitchBitrate)===null||g===void 0?void 0:g.video},f=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:f}}}}),{onError:i})),r(Se(this.player,"bufferStateChanged").pipe(q(({mediaType:f})=>f==="video"),$(({state:f})=>f==="bufferStalled")),e.isBuffering$),r(Se(this.player,"fragmentLoadingStarted"),({mediaType:f,request:{url:S}})=>{var g,E;const I=this.player.getDashMetrics(),_=I.getLatestFragmentRequestHeaderValueByID(f,"X-Reused"),A=(g=I.getLatestFragmentRequestHeaderValueByID(f,"X-Delivery-Type"))!==null&&g!==void 0?g:fi.HTTP1,B=(E={1:!0,0:!1}[_])!==null&&E!==void 0?E:void 0;this.params.output.httpConnectionType$.next(A),this.params.output.httpConnectionReused$.next(B),e.hostname$.next(Ae(S))}),r(Se(this.player,"streamInitialized"),({streamInfo:{duration:f,manifestInfo:{isDynamic:S,availableFrom:g}}})=>{this.isLive$.next(S),this.availableFrom$.next(g.getTime()),S||e.duration$.next(f),this.videoTracks=[];const E=this.player.getQualityFor("video");let I;for(const _ of this.player.getBitrateInfoListFor("video")){const A=_.qualityIndex.toString(10),B=Rt(_),K=_.bitrate/1e3,G={width:_.width,height:_.height},U=this.frameRatesByFrameHeight[_.height];if(B){const X={id:A,quality:B,bitrate:K,size:G,fps:U};this.videoTracks.push({track:X,bitrateInfo:_}),_.qualityIndex===E&&(I=X)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:_})=>_)),I&&e.currentVideoTrack$.next(I),this.videoState.setState(z.STREAM_INITIALIZED),this.videoState.startTransitionTo(z.READY)}),r(Se(this.player,"fragmentLoadingCompleted"),({request:f})=>{if(!f.requestEndDate||!f.firstByteDate||!f.bytesLoaded)return;const S=f.requestEndDate.getTime()-f.firstByteDate.getTime(),g=f.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(g,S)}),r(L(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const f=this.params.dependencies.throughputEstimator.throughput$.getValue(),S=yi(this.videoTracks.map(({track:E})=>E),{container:this.elementSize$.getValue(),throughput:f,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),g=this.videoTracks.find(({track:E})=>E===S);g!=null&&g.bitrateInfo&&this.player.setQualityFor("video",g==null?void 0:g.bitrateInfo.qualityIndex,!1)}),r(et({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(q(w))}).pipe(q(({isLive:f})=>f),$(({maxSeekBackTime:f})=>-f/1e3)),this.params.output.duration$);const n=Se(this.player,"playbackTimeUpdated").pipe($(({time:f})=>f!=null?f:0));r(et({availableFrom:this.availableFrom$.pipe(q(w)),currentTime:n}),({availableFrom:f,currentTime:S})=>this.params.output.liveTime$.next(f+S*1e3)),r(n.pipe(q(()=>this.isLive$.getValue()===!1)),e.position$),r(Se(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),r(Se(this.player,"playbackEnded"),e.endedEvent$),r(Se(this.player,"playbackProgress").pipe($(()=>oo(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(Se(this.player,"playbackPlaying"),()=>{this.videoState.setState(z.PLAYING),P(t.playbackState,m.PLAYING)}),r(Se(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(z.PAUSED),P(this.params.desiredState.playbackState,m.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(Se(this.player,"playbackPaused"),()=>{this.videoState.setState(z.PAUSED),P(t.playbackState,m.PAUSED)}),r(Se(this.player,"canPlay"),()=>{var f;((f=this.videoState.getTransition())===null||f===void 0?void 0:f.to)===z.READY&&this.videoState.setState(z.READY)}),r(this.isLive$,e.isLive$),r(es(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=L(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Le(0));r(o,this.syncPlayback);const{playbackDuration$:u,ping$:d,connectionType$:l,connectionReused$:c}=Af(this.player);r(l,this.params.output.httpConnectionType$),r(c,this.params.output.httpConnectionReused$),r(u,this.maxSeekBackTime$),r(d.pipe(ge()),e.firstBytesEvent$),r(Se(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(et({isLive:this.isLive$,isShort:e.duration$.pipe($(f=>f<60))}),({isLive:f,isShort:S})=>{const g=!f&&S;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:g}}})}),r(n.pipe(q(f=>f>this.params.tuning.insufficientBufferRuleMargin),ge()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(Se(this.player,"manifestLoaded").pipe(ge()).subscribe(()=>{this.subscription.add(Se(this.player,"playbackPlaying").pipe(ge(),wt(void 0)).subscribe(e.firstFrameEvent$,i))},i)),this.subscription.add(Pt(this.video,t.isLooped,i));const{volumeState$:h,looped$:p,playbackRateState$:v}=ut(this.video);this.subscription.add(ot(this.video,t.volume,h,i)),this.subscription.add(h.subscribe(e.volume$,i)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(pt(this.video,t.playbackRate,v,i))}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(z.STOPPED),P(this.params.desiredState.playbackState,m.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(z.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=Vt(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Ft.PLAYBACK_SHIFT);this.player.attachSource(r)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(z.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(z.PAUSED),this.video.pause()}destroy(){var e,t;this.subscription.unsubscribe(),this.textTracksManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(i){}this.video.remove(),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var Ti=s=>{switch(s){case"mobile":return ae.Q_144P;case"lowest":return ae.Q_240P;case"low":return ae.Q_360P;case"sd":case"medium":return ae.Q_480P;case"hd":case"high":return ae.Q_720P;case"fullhd":case"full":return ae.Q_1080P;case"quadhd":case"quad":return ae.Q_1440P;case"ultrahd":case"ultra":return ae.Q_2160P}},mt=async s=>{const e=s.muted;try{await s.play()}catch(t){if(t instanceof DOMException&&(t.code===20||t.name==="AbortError"))return!1;if(e)return console.warn(t),!1;s.muted=!0;try{await s.play()}catch(i){return s.muted=!1,console.warn(i),!1}}return!0};function Te(){return he()}function lo(s){return Te()-s}function Va(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 Kf(s,e,t){const i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function ji(s,e,t,i){const r=window.XMLHttpRequest;let a,n,o,u=!1,d=0,l,c,h=!1,p="arraybuffer",v=7e3,f=2e3,S=()=>{if(u)return;R(l);const M=lo(l);let te;if(M<f){te=f-M,setTimeout(S,te);return}f*=2,f>v&&(f=v),n&&n.abort(),n=new r,B()};const g=M=>(a=M,F),E=M=>(c=M,F),I=()=>(p="json",F),_=()=>{if(!u){if(--d>=0){S(),i&&i();return}u=!0,c&&c(),t&&t()}},A=M=>(h=M,F),B=()=>{l=Te(),n=new r,n.open("get",s);let M=0,te,ue=0;const me=()=>(R(l),Math.max(l,Math.max(te||0,ue||0)));if(a&&n.addEventListener("progress",k=>{const H=Te();a.updateChunk&&k.loaded>M&&(a.updateChunk(me(),k.loaded-M),M=k.loaded,te=H)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>_())),n.addEventListener("load",()=>{if(u)return;R(n);const k=n.status;if(k>=200&&k<300){if(n.response.byteLength&&a){const H=n.response.byteLength-M;H&&a.updateChunk&&a.updateChunk(me(),H)}c&&c(),n&&e(n.response)}else _()}),n.addEventListener("error",()=>{_()}),h){const k=()=>{R(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ue=Te(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=p,n.send(),F},F={withBitrateReporting:g,withParallel:A,withJSONResponse:I,withRetryCount:M=>(d=M,F),withRetryInterval:(M,te)=>(w(M)&&(f=M),w(te)&&(v=te),F),withTimeout:M=>(o=M,F),withFinally:E,send:B,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return F}const Xf=100,Zf=2e3,ep=500;let tp=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-ep;if(t-e>Zf){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>Xf&&(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 ip{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=Te(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=Te()-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=ji(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=Te()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=Te();if(Object.keys(this.activeRequests).length>=e)return!1;const 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 Oi=1e4,Bi=3,sp=300,rp=2e3,ap=6e4,np=10,op=1,dp=500;class up{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 tp(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Va(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=Va(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;Boolean(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||w(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=()=>{Kf(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 ip(Bi,Oi,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 _=a&&(!l||l===this.rep);return _||t("Not running!"),_},h=(_,A,B)=>{u&&u.abort(),u=ji(this.urlResolver.resolve(_,!1),A,B,()=>this._retryCallback()).withTimeout(Oi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Bi).withFinally(()=>{u=null}).send()},p=(_,A,B)=>{R(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(_,!1),A,B,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},v=_=>{const A=i.playbackRate;i.playbackRate!==_&&(t(`Playback rate switch: ${A}=>${_}`),i.playbackRate=_)},f=_=>{this.lowLatency=_,t(`lowLatency changed to ${_}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)v(1);else{let _=this._getBufferSizeSec();if(this.bufferStates.length<5){v(1);return}const B=Te()-1e4;let K=0;for(let U=0;U<this.bufferStates.length;U++){const X=this.bufferStates[U];_=Math.min(_,X.buf),X.ts<B&&K++}this.bufferStates.splice(0,K),t(`update playback rate; minBuffer=${_} drop=${K} jitter=${this.sourceJitter}`);let G=_-op;this.sourceJitter>=0?G-=this.sourceJitter/2:this.sourceJitter-=1,G>3?v(1.15):G>1?v(1.1):G>.3?v(1.05):v(1)}},g=_=>{let A;const B=()=>A&&A.start?A.start.length:0,K=k=>A.start[k]/1e3,G=k=>A.dur[k]/1e3,U=k=>A.fragIndex+k,X=(k,H)=>({chunkIdx:U(k),startTS:K(k),dur:G(k),discontinuity:H}),F=()=>{let k=0;if(A&&A.dur){let H=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,ne=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,fe=H;this.sourceJitter>1&&(fe+=this.sourceJitter-1);let ve=A.dur.length-1;for(;ve>=0&&(fe-=A.dur[ve],!(fe<=0));--ve);k=Math.min(ve,A.dur.length-1-ne),k=Math.max(k,0)}return X(k,!0)},M=k=>{const H=B();if(!(H<=0)){if(w(k)){for(let ne=0;ne<H;ne++)if(K(ne)>k)return X(ne)}return F()}},te=k=>{const H=B(),ne=k?k.chunkIdx+1:0,fe=ne-A.fragIndex;if(!(H<=0)){if(!k||fe<0||fe-H>np)return t(`Resync: offset=${fe} bChunks=${H} chunk=`+JSON.stringify(k)),F();if(!(fe>=H))return X(ne-A.fragIndex,!1)}},ue=(k,H,ne)=>{d&&d.abort(),d=ji(this.urlResolver.resolve(k,!0,this.lowLatency),H,ne,()=>this._retryCallback()).withTimeout(Oi).withRetryCount(Bi).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(k,H)=>{ue(_,ne=>{if(!c())return;A=ne;const fe=Boolean(A.lowLatency);fe!==this.lowLatency&&f(fe);let ve=0;for(let we=0;we<A.dur.length;++we)ve+=A.dur[we];ve>0&&(R(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ve/A.dur.length)),r({name:"index",zeroTime:A.zeroTime,shiftDuration:A.shiftDuration}),this.sourceJitter=A.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,A.jitter/1e3)):1,k(M(H))},()=>this._handleNetworkError())},nextChunk:te}},E=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),R(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:_=>{const{videoElement:A,logger:B}=this.params;let K=g(e.jidxUrl),G,U,X,F,M=0,te,ue,me;const k=()=>{te&&(clearTimeout(te),te=void 0);const Z=Math.max(dp,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),be=M+Z,$e=Te(),Re=Math.min(1e4,be-$e);M=$e;const vt=()=>{d||c()&&K.seek(()=>{c()&&(M=Te(),H(),k())})};Re>0?te=window.setTimeout(()=>{this.paused?k():vt()},Re):vt()},H=()=>{let Z;for(;Z=K.nextChunk(F);)F=Z,Fe(Z);const be=K.nextChunk(X);if(be){if(X&&be.discontinuity){B("Detected discontinuity; restarting playback"),this.paused?k():(E(),this._initPlayerWith(e));return}we(be)}else k()},ne=(Z,be)=>{if(!c()||!this.sourceBuffer)return;let $e,Re,vt;const Ve=lt=>{window.setTimeout(()=>{c()&&ne(Z,be)},lt)};if(this.sourceBuffer.updating)B("Source buffer is updating; delaying appendBuffer"),Ve(100);else{const lt=Te(),St=A.currentTime;!this.paused&&A.buffered.length>1&&ue===St&<-me>500&&(B("Stall suspected; trying to fix"),this._fixupStall()),ue!==St&&(ue=St,me=lt);const Jt=this._getBufferSizeSec();if(Jt>30)B(`Buffered ${Jt} seconds; delaying appendBuffer`),Ve(2e3);else try{this.sourceBuffer.appendBuffer(Z),this.videoPlayStarted?(this.bufferStates.push({ts:lt,buf:Jt}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),be&&be()}catch(Dt){if(Dt.name==="QuotaExceededError")B("QuotaExceededError; delaying appendBuffer"),vt=this.sourceBuffer.buffered.length,vt!==0&&($e=this.sourceBuffer.buffered.start(0),Re=St,Re-$e>4&&this.sourceBuffer.remove($e,Re-3)),Ve(1e3);else throw Dt}}},fe=()=>{U&&G&&(B([`Appending chunk, sz=${U.byteLength}:`,JSON.stringify(X)]),ne(U,function(){U=null,H()}))},ve=Z=>e.fragUrlTemplate.replace("%%id%%",Z.chunkIdx),we=Z=>{c()&&p(ve(Z),(be,$e)=>{if(c()){if($e/=1e3,U=be,X=Z,n=Z.startTS,$e){const Re=Math.min(10,Z.dur/$e);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Re:Re}fe()}},()=>this._handleNetworkError())},Fe=Z=>{c()&&(R(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ve(Z),!1)))},Qt=Z=>{c()&&(e.cachedHeader=Z,ne(Z,()=>{G=!0,fe()}))};a=!0,K.seek(Z=>{if(c()){if(M=Te(),!Z){k();return}F=Z,!J(_)||Z.startTS>_?we(Z):(X=Z,H())}},_),e.cachedHeader?Qt(e.cachedHeader):h(e.headerUrl,Qt,()=>this._handleNetworkError())},stop:E,getTimestampSec:()=>n},l}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),w(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 w(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let h,p,v;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(p=this._getBufferSizeSec(),v=c/this.bitrate,p>10&&v>.8||p>15&&v>.5||p>20&&v>.3)){e(`Not switching: buffer=${Math.floor(p)}; 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,p)=>{const v=Te();if(this.chunkRateEstimator.addInterval(h,v,p)){const S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:v-h,speed:S}),!0}},get:()=>{const h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}}))();let n=-1/0,o,u=!0;const d=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&lo(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,h)=>{const p=a.updateChunk(c,h);return p&&d(),p},notifySwitch:c=>{const h=Te();c<o&&(n=h),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=ji(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Oi).withRetryCount(Bi).withRetryInterval(sp,rp).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;mt(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))},ap))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var j;(function(s){s.STOPPED="stopped",s.MANIFEST_READY="manifest_ready",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(j||(j={}));const lp=[j.PAUSED,j.PLAYING,j.READY],cp=[j.PAUSED,j.PLAYING,j.READY];class hp{constructor(e){this.subscription=new ie,this.videoState=new de(j.STOPPED),this.representations$=new b([]),this.textTracksManager=new We,this.maxSeekBackTime$=new b(1/0),this.zeroTime$=new b(void 0),this.liveOffset=new Ir,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:x.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),p=(n=Ti(c.name))!==null&&n!==void 0?n:Rt(c.video),v=c.bitrate/1e3,f={...c.video};if(!p)continue;const S={id:h,quality:p,bitrate:v,size:f};l.push({track:S,representation:c})}this.representations$.next(l),this.params.output.availableVideoTracks$.next(l.map(({track:c})=>c)),((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===j.MANIFEST_READY&&this.videoState.setState(j.MANIFEST_READY);break}case"qualitySwitch":{const d=r.quality,l=(u=this.representations$.getValue().find(({representation:c})=>c===d))===null||u===void 0?void 0:u.track;this.params.output.hostname$.next(new URL(d.headerUrl,this.params.source.url).hostname),w(l)&&this.params.output.currentVideoTrack$.next(l);break}case"bandwidth":{const{size:d,duration:l}=r;this.params.dependencies.throughputEstimator.addRawSpeed(d,l);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{var r;const a=this.videoState.getState(),n=this.videoState.getTransition(),o=this.params.desiredState.playbackState.getState(),u=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${a}; videoTransition: ${JSON.stringify(n)}; desiredPlaybackState: ${o}; seekState: ${JSON.stringify(d)};`}),o===m.STOPPED){a!==j.STOPPED&&(this.videoState.startTransitionTo(j.STOPPED),this.dash.destroy(),this.video.setAttribute("src",""),this.video.load(),this.videoState.setState(j.STOPPED));return}if(!n){if(cp.includes(a)){const l=(r=this.params.desiredState.videoTrack.getTransition())===null||r===void 0?void 0:r.to;w(l)&&this.setVideoTrack(l);const c=this.params.desiredState.autoVideoTrackSwitching.getTransition();c&&this.setAutoQuality(c.to)}if((u==null?void 0:u.to)!==m.PAUSED&&d.state===V.Requested&&lp.includes(a)){this.seek(d.position-this.liveOffset.getTotalPausedTime());return}switch(a){case j.STOPPED:this.videoState.startTransitionTo(j.MANIFEST_READY),this.dash.attachSource(Vt(this.params.source.url));return;case j.MANIFEST_READY:this.videoState.startTransitionTo(j.READY),this.prepare();break;case j.READY:if(o===m.PAUSED)this.videoState.setState(j.PAUSED);else if(o===m.PLAYING){this.videoState.startTransitionTo(j.PLAYING);const l=u==null?void 0:u.from;l&&l===m.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(j.PAUSED)})}return;case j.PLAYING:o===m.PAUSED&&(this.videoState.startTransitionTo(j.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case j.PAUSED:o===m.PLAYING&&(this.videoState.startTransitionTo(j.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(j.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return O(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:x.WTF,message:"DashLiveProvider internal logic error",thrown:r})};L(this.videoState.stateChangeStarted$.pipe($(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe($(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=dt(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.hostname$.next(Ae(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=ut(this.video);this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===j.READY&&this.videoState.setState(j.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(j.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===V.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(j.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(pe(),$(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(et({zeroTime:this.zeroTime$.pipe(q(w)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Pt(this.video,this.params.desiredState.isLooped,t)).add(ot(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(pt(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(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:r}})=>{const a=r&&pf(r);this.dash.setMaxAutoQuality(a)})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case j.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(m.STOPPED);break;case j.MANIFEST_READY:case j.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 j.PAUSED:this.params.desiredState.playbackState.setState(m.PAUSED);break;case j.PLAYING:this.params.desiredState.playbackState.setState(m.PLAYING);break;default:return O(r.to)}},t)).add(L(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Le(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const e=new up({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&&w(u)?u:(a=yi(o.map(({track:h})=>h),{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()}))===null||a===void 0?void 0:a.id,c=(n=o.find(({track:h})=>h.id===l))===null||n===void 0?void 0:n.representation;R(c,"Representations missing"),this.dash.startPlay(c,d),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(l),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(d)}setVideoTrack(e){var t;const i=(t=this.representations$.getValue().find(({track:r})=>r.id===e))===null||t===void 0?void 0:t.representation;R(i,`No such representation ${e}`),this.dash.switchByName(i.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=-e,i=t<=this.maxSeekBackTime$.getValue()?t:0;this.params.output.position$.next(e/1e3),this.liveOffset.resetTo(i),this.dash.reinit(Vt(this.params.source.url,i))}}var co=s=>{var e,t;const i=s.get("X-Delivery-Type"),r=s.get("X-Reused"),a=i===null?fi.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}},Et=(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 fp=s=>{const e=document.createElement("a");return e.href=s,e.origin},pp=s=>{const e=document.createElement("a");return e.href=s,e.host};class ho{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(R(this._xhr),((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=bi(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(pp(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 ts{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 p=f=>{r(ts._str2ua(f.substr(u))),u=f.length};let v=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(v=Gt(v)),this._lastXhr=new ho(v,e.failoverHosts,f=>{this._lastXhr=void 0,p(f);const S=Date.now()-d;this._params.onBandwidthChange({size:f.length,duration:S,speed:8*f.length/(S/1e3)}),this._onDashCallback("loading",{size:f.length,done:!0}),a==null||a()},f=>{if(f.length-u>o&&p(f),c===0){c=Date.now();return}h=f.length-l;const S=Date.now()-c;h>=100*1024&&S>=1e3&&(this._params.onBandwidthChange({size:h,duration:S,speed:8*h/(S/1e3)}),h=0,l=f.length,c=Date.now()),this._onDashCallback("loading",{size:f.length,done:!1})},n,(f,S,g)=>this._params.onError(f,S,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=ts._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 mp{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=Gt(i)),new ho(i,t,r=>{this.attachManifest(r,t,fp(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,p,v,f,S,g,E,I,_,A,B,K,G,U,X,F,M;const te=d.getElementsByTagName("SegmentBase")[0],ue=te&&n(te,"indexRange").split("-"),me=te&&te.getElementsByTagName("Initialization")[0],k=me&&n(me,"range").split("-");if(!k||!ue){const Fe=d.parentElement;if((Fe==null?void 0:Fe.getAttribute("contentType"))==="text"){const Qt=(l=d.getAttribute("id"))!==null&&l!==void 0?l:void 0,Z=(i?i+"/":"")+((v=(p=(h=(c=d.getElementsByTagName("BaseURL"))===null||c===void 0?void 0:c[0])===null||h===void 0?void 0:h.childNodes)===null||p===void 0?void 0:p[0])===null||v===void 0?void 0:v.data),be=(f=Fe.getAttribute("lang"))!==null&&f!==void 0?f:void 0;Z&&u.push({id:Qt,url:Z,language:be})}return}const H=.1,ne=Number((S=d.attributes.getNamedItem("bandwidth"))===null||S===void 0?void 0:S.value),fe=(i?i+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ve;const we=(E=(g=d.attributes.getNamedItem("frameRate"))===null||g===void 0?void 0:g.value)!==null&&E!==void 0?E:void 0;ve=we?xr(we):void 0,o.push({width:Number((I=d.attributes.getNamedItem("width"))===null||I===void 0?void 0:I.value),height:Number((_=d.attributes.getNamedItem("height"))===null||_===void 0?void 0:_.value),bandwidth:ne,baseURL:fe,failoverHosts:t,indexFrom:Number(ue[0]),indexTo:Number(ue[1]),initFrom:Number(k[0]),initTo:Number(k[1]),codecs:(B=(A=d.attributes.getNamedItem("codecs"))===null||A===void 0?void 0:A.value)!==null&&B!==void 0?B:void 0,mimeType:(G=(K=d.attributes.getNamedItem("mimeType"))===null||K===void 0?void 0:K.value)!==null&&G!==void 0?G:void 0,fps:ve,bufferSize:H*ne/8,bufferLength:H,name:(X=(U=d.attributes.getNamedItem("okQuality"))===null||U===void 0?void 0:U.value)!==null&&X!==void 0?X:void 0,id:(M=(F=d.attributes.getNamedItem("id"))===null||F===void 0?void 0:F.value)!==null&&M!==void 0?M: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");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(this._representations)}_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 p=d+(n.getUint32(a,!1)&2147483647),v=u+n.getUint32(a+4,!1);a+=12,e.refs.push({fromTime:u/o,toTime:v/o,fromOffset:d,toOffset:p-1}),d=p,u=v}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 p=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),p)}const l=this._appendVector[String(d.fromTime)];l!==r&&(r=l,this._params.onRepresentationPlay(l));let c;if(this._findRef(d.toTime)){const p=this._buffer.getByTime(this._video.currentTime);if(!p){this._onDashCallback("buffering");return}c=p.to-this._video.currentTime,c<e.bufferLength&&(this._onDashCallback("buffering"),a!==p.to&&(a=p.to,window.setTimeout(()=>{try{const v=this._buffer.getNextWithGap(p);v&&(this._video.currentTime=v.from)}catch(v){throw this._params.onError("GapSyncError",`Seek Error ${String(v)}`,v),v}},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 ts({mediaSource:i,sourceBuffer:d,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(d){throw this._params.onError("DashSourceOpen",`Source open exception ${String(d)}`,d),d}this._loadInitAndSidx(e),i.duration||(i.duration=this._duration),this._loopTimeout||o(),i.removeEventListener("sourceopen",u),i.removeEventListener("webkitsourceopen",u)};i.addEventListener("sourceopen",u,!1),i.addEventListener("webkitsourceopen",u,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener("waiting",()=>{const d=this._video&&this._video.played.length;d&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(d-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,i=!1,r=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const a=this._findRef(t);if(a){if(i){this._isLastRef(a)&&t>=a.toTime&&(t=a.fromTime);const n=this._findRef(this._video.currentTime),o=Math.abs(this._video.currentTime-t),u=r||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||a===n||o<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=u?t:a.fromTime}this._appendVector[String(a.fromTime)]=e,this._stream.load(e,a.fromOffset,a.toOffset,(n,o)=>this._stream.append(n,o),()=>{this._lastLoadOffset=a.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},n=>this._params.onResponseHeaders(n),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const i=this._buffer.getByTime(this._video.currentTime),r=this._findRef(this._video.currentTime);if(!i||!r){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const a=.1;if(r.toTime<i.to+a){const n=this._findRef(r.toTime);n&&n.toTime<i.to+a?(this._buffer.smartRemove(r.fromTime-a,n.toTime+a,(o,u)=>this._stream.remove(o,u)),this._loadRef(e,n.toTime)):(this._buffer.smartRemove(r.fromTime-a,r.toTime+a,(o,u)=>this._stream.remove(o,u)),this._loadRef(e,r.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t){this._stream&&this._buffer.getByTime(e)?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0,t)}updateRefsForCurrentTime(){const e=this._video.currentTime;(!this._stream||J(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return;if(Array.isArray(i)&&i.length===0){this._params.onError("emptyrefs","Empty refs");return}let r;for(let a=0;a<i.length;a++){const n=i[a];if(n.fromTime<=e&&n.toTime>e)return n;n.fromTime>e&&(!r||n.fromTime<r.fromTime)&&(r=n)}if(!r){const a=i[i.length-1];if(e>a.toTime)return a}return r}_isLastRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return!1;const r=i[i.length-1];return e.fromTime===r.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const i=this._video.buffered.start(t),r=this._video.buffered.end(t);if(e>i&&e<r)return Math.round(r*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var W;(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"})(W||(W={}));const vp=[W.PAUSED,W.PLAYING];class Sp{constructor(e){this.videoState=new de(W.STOPPED),this.subscription=new ie,this.representations$=new b([]),this.currentRepresentation$=new b(void 0),this.textTracksManager=new We,this.elementSize$=new b(void 0),this.dashLiteEvents={idxRequestPing$:new C,responseHeaders$:new C,manifestReady$:new C,representationPlay$:new C,error$:new C},this.handleManifestReady=t=>{var i,r,a;const n=[];for(const o of t){const u=(r=(i=o.name)!==null&&i!==void 0?i:o.id)!==null&&r!==void 0?r:o.height.toString(10),d=(a=o.name&&Ti(o.name))!==null&&a!==void 0?a:Rt(o),l=o.bandwidth/1e3,c={width:o.width,height:o.height},h=o.fps;if(!d)continue;const p={id:u,quality:d,bitrate:l,size:c,fps:h};n.push({track:p,representation:o})}this.representations$.next(n),this.params.output.availableVideoTracks$.next(n.map(({track:o})=>o)),this.videoState.setState(W.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var i;const r=(i=this.representations$.getValue().find(({representation:a})=>a===t))===null||i===void 0?void 0:i.track;r&&(this.params.output.currentVideoTrack$.next(r),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(r.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return 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!==W.STOPPED&&(this.videoState.startTransitionTo(W.STOPPED),this.dash.destroy(),this.video.setAttribute("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(W.STOPPED),P(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(!i)switch((a==null?void 0:a.to)!==m.PAUSED&&n.state===V.Requested&&vp.includes(t)&&this.seek(n.position,n.forcePrecise),t){case W.STOPPED:this.videoState.startTransitionTo(W.MANIFEST_LOADED),this.prepare();return;case W.MANIFEST_LOADED:this.videoState.startTransitionTo(W.INITIAL_REPRESENTATION_SELECTED);return;case W.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(W.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case W.METADATA_LOADED:this.videoState.startTransitionTo(W.READY),this.dash.updateRefsForCurrentTime();return;case W.READY:r===m.READY?P(this.params.desiredState.playbackState,m.READY):r===m.PAUSED?(this.videoState.setState(W.PAUSED),P(this.params.desiredState.playbackState,m.PAUSED)):r===m.PLAYING&&(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed());return;case W.PLAYING:r===m.PAUSED?(this.videoState.startTransitionTo(W.PAUSED),this.video.pause()):(a==null?void 0:a.to)===m.PLAYING&&P(this.params.desiredState.playbackState,m.PLAYING);return;case W.PAUSED:r===m.PLAYING?(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===m.PAUSED&&P(this.params.desiredState.playbackState,m.PAUSED);return;default:return O(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),L(this.videoState.stateChangeStarted$.pipe($(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe($(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=dt(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(Ae(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Pf(this.video),this.dash=new mp({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:t=>this.dashLiteEvents.manifestReady$.next(t),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:x.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:x.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=ut(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.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(a.seeking$.subscribe(()=>{J(this.params.desiredState.seekState.getState().state!==V.Applying)&&(this.videoState.getState()===W.PLAYING||this.videoState.getState()===W.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(Pt(this.video,t.isLooped,i)),this.subscription.add(ot(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(pt(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),n(es(this.video),this.elementSize$),this.subscription.add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===W.READY&&this.videoState.setState(W.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),P(this.params.desiredState.playbackState,m.PAUSED)})).add(a.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING),P(this.params.desiredState.playbackState,m.PLAYING)},i)).add(a.loadedMetadata$.subscribe(()=>{this.videoState.setState(W.METADATA_LOADED)},i)).add(a.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},i)).add(this.dashLiteEvents.error$.pipe($(({id:o,message:u,thrown:d})=>({id:`DashLite_${o}`,category:x.WTF,message:u,thrown:d}))).subscribe(this.params.output.error$)).add(L(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$,this.params.output.element$,this.elementSize$,N(this.video,"progress")).pipe($(()=>{var o,u,d;const l=this.currentRepresentation$.getValue(),c=this.representations$.getValue(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition(),p=this.params.desiredState.videoTrack.getState(),v=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),f=this.elementSize$.getValue(),S=r();h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to);let g;if(!S&&w(p))g=p;else{const E=Et(this.video.buffered,this.video.currentTime*1e3),I=S?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,_=Math.min(E/I,1);g=(u=yi(c.map(({track:A})=>A),{container:f,throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:_,playbackRate:this.video.playbackRate,current:(o=c.find(({representation:A})=>A===l))===null||o===void 0?void 0:o.track}))===null||u===void 0?void 0:u.id}return w(g)?(d=c.find(({track:E})=>E.id===g))===null||d===void 0?void 0:d.representation:void 0}),pe()).subscribe(this.currentRepresentation$,i)).add(et({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(q(o=>o.to===W.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(q(w))}).pipe(ge()).subscribe(()=>this.videoState.setState(W.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(q(w),pe((o,u)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?o.height<=u.height:o===u)).subscribe(o=>{const u=Et(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(Ae(o.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:u,reused:d}=co(o);this.params.output.httpConnectionType$.next(u),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(ge(),wt(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(o=>this.params.dependencies.throughputEstimator.addRawRtt(o))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,i)).add(this.dashLiteEvents.representationPlay$.pipe(q(w)).subscribe(this.handleRepresentationPlay,i)).add(L(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Le(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}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 O(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){mt(this.video).then(e=>{e||(this.videoState.setState(W.PAUSED),P(this.params.desiredState.playbackState,m.PAUSED,!0))})}}var Ie;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(Ie||(Ie={}));var is;(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"})(is||(is={}));var xe;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(xe||(xe={}));var ee;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(ee||(ee={}));var Yt;(function(s){s.MP4="mp4",s.WEBM="webm"})(Yt||(Yt={}));var ss;(function(s){s[s.RECTANGULAR=0]="RECTANGULAR",s[s.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",s[s.CUBEMAP=2]="CUBEMAP",s[s.MESH=3]="MESH"})(ss||(ss={}));var mr=(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 gp=(s,e={})=>{const i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},bp=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Ha=bp?gp:window.requestIdleCallback;var Vs,Hs;let fo=!1;try{fo=no()&&parseInt((Hs=(Vs=navigator.userAgent.match(/Version\/(\d+)/))===null||Vs===void 0?void 0:Vs[1])!==null&&Hs!==void 0?Hs:"",10)<16}catch(s){console.error(s)}class yp{constructor(e){this.bufferFull$=new C,this.error$=new C,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const i=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!i),this.currentTask=null}this.queue.length&&this.pull()}catch(i){this.error$.next({id:"BufferTaskQueueUnknown",category:x.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let i;fo&&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)}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"&&i==="remove"||this.error$.next({id:`BufferTaskQueue:${i}`,category:x.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:O(t)}}}var Ga=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};class Qe{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 po extends Qe{}class Tp extends Qe{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 Ep extends Qe{parseChildrenBoxes(){return Wt(this.content)}}class $p extends Qe{constructor(e){super(e),this.data=this.content}}class Ei extends Qe{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class Ap extends Ei{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 wp extends Qe{parseChildrenBoxes(){return Wt(this.content)}}class _p extends Qe{parseChildrenBoxes(){return Wt(this.content)}}var Tt;(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"})(Tt||(Tt={}));class kp extends Ei{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=Tt.MONOSCOPIC;break;case 1:this.stereoMode=Tt.TOP_BOTTOM;break;case 2:this.stereoMode=Tt.LEFT_RIGHT;break;case 3:this.stereoMode=Tt.STEREO_CUSTOM;break;case 4:this.stereoMode=Tt.RIGHT_LEFT;break}this.cursor+=1}}class Rp extends Ei{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class Pp extends Ei{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class Dp extends Qe{parseChildrenBoxes(){return Wt(this.content)}}class Ip extends Ei{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 xp extends Qe{parseChildrenBoxes(){return Wt(this.content)}}class Cp extends Qe{parseChildrenBoxes(){return Wt(this.content)}}const Lp={ftyp:Tp,moov:Ep,mdat:$p,sidx:Ap,trak:wp,mdia:Dp,tkhd:Ip,minf:xp,sv3d:_p,st3d:kp,prhd:Rp,proj:Cp,equi:Pp,unknown:po};class Op{createBox(e,t){const i=Lp[e];return i?new i(t):new po(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return ps.createBox(i,new DataView(e.buffer,e.byteOffset))}}const ps=new Op;function ui(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:ps.createBox(e,new DataView(s.buffer,i-7))}i++}return null}function Bp(s,e){const t=[];let i=s.byteOffset;for(;i<s.byteLength;){const r=ui(new DataView(s.buffer,i,s.byteLength),e);if(r)t.push(r),i+=r.source.byteOffset+r.source.byteLength;else break}return t}function Wt(s){const e=[];let t=0;for(;t<s.byteLength;){const i=ps.createFromView(new DataView(s.buffer,s.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const Mp=new TextDecoder("ascii"),Np=s=>Mp.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",Up=s=>{const e=ps.createFromView(s);let t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=a.subsegmentDuration/e.timescale*1e3,o={status:ee.NONE,time:{from:t,to:t+n},byte:{from:i,to:i+a.referencedSize-1}};return t+=n,i+=a.referencedSize,o})},Fp=s=>{const e=Bp(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},Vp=s=>{const e={is3dVideo:!1,stereoMode:0,projectionType:ss.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(ui(s,"sv3d")){e.is3dVideo=!0;const i=ui(s,"st3d");i&&(e.stereoMode=i.stereoMode);const r=ui(s,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const a=ui(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},Hp={validateData:Np,parseInit:Vp,getIndexRange:()=>{},parseSegments:Up,parseFeedableSegmentChunk:Fp};var T;(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"})(T||(T={}));var D;(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"})(D||(D={}));const Ya={[T.EBML]:{type:D.Master},[T.EBMLVersion]:{type:D.UnsignedInteger},[T.EBMLReadVersion]:{type:D.UnsignedInteger},[T.EBMLMaxIDLength]:{type:D.UnsignedInteger},[T.EBMLMaxSizeLength]:{type:D.UnsignedInteger},[T.DocType]:{type:D.String},[T.DocTypeVersion]:{type:D.UnsignedInteger},[T.DocTypeReadVersion]:{type:D.UnsignedInteger},[T.Void]:{type:D.Binary},[T.Segment]:{type:D.Master},[T.SeekHead]:{type:D.Master},[T.Seek]:{type:D.Master},[T.SeekID]:{type:D.Binary},[T.SeekPosition]:{type:D.UnsignedInteger},[T.Info]:{type:D.Master},[T.TimestampScale]:{type:D.UnsignedInteger},[T.Duration]:{type:D.Float},[T.Tracks]:{type:D.Master},[T.TrackEntry]:{type:D.Master},[T.Video]:{type:D.Master},[T.Projection]:{type:D.Master},[T.ProjectionType]:{type:D.UnsignedInteger},[T.ProjectionPrivate]:{type:D.Master},[T.Chapters]:{type:D.Master},[T.Cluster]:{type:D.Master},[T.Timestamp]:{type:D.UnsignedInteger},[T.SilentTracks]:{type:D.Master},[T.SilentTrackNumber]:{type:D.UnsignedInteger},[T.Position]:{type:D.UnsignedInteger},[T.PrevSize]:{type:D.UnsignedInteger},[T.SimpleBlock]:{type:D.Binary},[T.BlockGroup]:{type:D.Master},[T.EncryptedBlock]:{type:D.Binary},[T.Attachments]:{type:D.Master},[T.Tags]:{type:D.Master},[T.Cues]:{type:D.Master},[T.CuePoint]:{type:D.Master},[T.CueTime]:{type:D.UnsignedInteger},[T.CueTrackPositions]:{type:D.Master},[T.CueTrack]:{type:D.UnsignedInteger},[T.CueClusterPosition]:{type:D.UnsignedInteger},[T.CueRelativePosition]:{type:D.UnsignedInteger},[T.CueDuration]:{type:D.UnsignedInteger},[T.CueBlockNumber]:{type:D.UnsignedInteger},[T.CueCodecState]:{type:D.UnsignedInteger},[T.CueReference]:{type:D.Master},[T.CueRefTime]:{type:D.UnsignedInteger}},mo=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=rs(s,t),r=i in Ya,a=r?Ya[i].type:D.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=rs(u),c=d*2**((o-1)*8)+l,h=t+o;let p;return h+c>s.byteLength?p=new DataView(s.buffer,s.byteOffset+h):p=new DataView(s.buffer,s.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:p,valueSize:c}},rs=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{const t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},qe=(s,e)=>{switch(e){case D.SignedInteger:return s.getInt8(0);case D.UnsignedInteger:return rs(s);case D.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case D.String:return new TextDecoder("ascii").decode(s);case D.UTF8:return new TextDecoder("utf-8").decode(s);case D.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case D.Master:return s;case D.Binary:return s;default:O(e)}},qt=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=mo(i);if(!e(r))return;r.type===D.Master&&qt(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},Gp=s=>{if(s.getUint32(0)!==T.EBML)return!1;let e,t,i;const r=mo(s);return qt(r.value,({tag:a,type:n,value:o})=>(a===T.EBMLReadVersion?e=qe(o,n):a===T.DocType?t=qe(o,n):a===T.DocTypeReadVersion&&(i=qe(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},vo=[T.Info,T.SeekHead,T.Tracks,T.TrackEntry,T.Video,T.Projection,T.ProjectionType,T.ProjectionPrivate,T.Chapters,T.Cluster,T.Cues,T.Attachments,T.Tags],Yp=[T.Timestamp,T.SilentTracks,T.SilentTrackNumber,T.Position,T.PrevSize,T.SimpleBlock,T.BlockGroup,T.EncryptedBlock],qp=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,d,l=!1;const c=0;return qt(s,({tag:h,type:p,value:v,valueSize:f})=>{if(h===T.SeekID){const S=qe(v,p);d=rs(S)}else h!==T.SeekPosition&&(d=void 0);return h===T.Segment?(e=v.byteOffset,t=v.byteOffset+f):h===T.Info?a=!0:h===T.SeekHead?n=!0:h===T.TimestampScale?i=qe(v,p):h===T.Duration?r=qe(v,p):h===T.SeekPosition&&d===T.Cues?u=qe(v,p):h===T.Tracks?qt(v,({tag:S,type:g,value:E})=>S===T.ProjectionType?(l=qe(E,g)===1,!1):!0):a&&n&&vo.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:ss.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},zp=s=>{if(J(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},jp=(s,e)=>{let t=!1,i=!1;const r=o=>w(o.time)&&w(o.position),a=[];let n;return qt(s,({tag:o,type:u,value:d})=>{switch(o){case T.Cues:t=!0;break;case T.CuePoint:n&&r(n)&&a.push(n),n={};break;case T.CueTime:n&&(n.time=qe(d,u));break;case T.CueTrackPositions:break;case T.CueClusterPosition:n&&(n.position=qe(d,u));break;default:t&&vo.includes(o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{const{time:d,position:l}=o,c=a[u+1];return{status:ee.NONE,time:{from:d,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},Wp=s=>{let e=0,t=!1;try{qt(s,i=>i.tag===T.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Yp.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[T.SimpleBlock,T.BlockGroup,T.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},Qp={validateData:Gp,parseInit:qp,getIndexRange:zp,parseSegments:jp,parseFeedableSegmentChunk:Wp};class qa{constructor(e,t,i,r,{fetcher:a,tuning:n,getCurrentPosition:o,compatibilityMode:u=!1}){switch(this.onLastSegment$=new b(!1),this.fullyBuffered$=new b(!1),this.playingRepresentation$=new b(void 0),this.playingRepresentationInit$=new b(void 0),this.error$=new C,this.gaps=[],this.subscription=new ie,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new $t,this.destroyAbortController=new $t,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=Me(this.destroyAbortController.signal,async function*(d){const l=this.representations.get(d);R(l,`Cannot find representation ${d}`),this.playingRepresentationId=d,this.downloadingRepresentationId=d,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${l.mime}; codecs="${l.codecs}"`),this.sourceBufferTaskQueue=new yp(this.sourceBuffer),this.subscription.add(N(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},f=>this.error$.next({id:"SegmentEjection",category:x.WTF,message:"Error when trying to clear segments ejected by browser",thrown:f}))),this.subscription.add(N(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:x.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(f=>{if(!this.sourceBuffer)return;const S=Math.min(this.bufferLimit,Ga(this.sourceBuffer.buffered)*.8);this.bufferLimit=S,this.pruneBuffer(this.getCurrentPosition(),f)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(f=>this.error$.next(f))),yield this.loadInit(l,"high",!0);const c=this.initData.get(l.id),h=this.segments.get(l.id),p=this.parsedInitData.get(l.id);if(R(c,"No init buffer for starting representation"),R(h,"No segments for starting representation"),!(c instanceof ArrayBuffer))return;let v=0;for(const f of h)f.time.from-v>0&&this.gaps.push({representation:l.id,from:v,to:f.time.from}),v=f.time.to;w(l.duration)&&l.duration-v>0&&this.gaps.push({representation:l.id,from:v,to:l.duration}),yield this.sourceBufferTaskQueue.append(c,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(p)}.bind(this)),this.switchTo=Me(this.destroyAbortController.signal,async function*(d){if(d===this.downloadingRepresentationId||d===this.switchingToRepresentationId)return;this.switchingToRepresentationId=d;const l=this.representations.get(d);R(l,`No such representation ${d}`);let c=this.initData.get(d);if(J(c)?yield this.loadInit(l,"high",!1):c instanceof Promise&&(yield c),c=this.initData.get(d),!c||!(c instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=d,this.abort(),yield this.sourceBufferTaskQueue.append(c,this.downloadAbortController.signal);const h=this.getCurrentPosition();w(h)&&this.maintain(h)}.bind(this)),this.fetcher=a,this.tuning=n,this.compatibilityMode=u,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.container=i,i){case Yt.MP4:this.containerParser=Hp;break;case Yt.WEBM:this.containerParser=Qp;break;default:O(i)}this.initData=new Map(r.map(d=>[d.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(d=>[d.id,d])),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 $t,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(J(e)||J(this.downloadingRepresentationId)||J(this.playingRepresentationId)||J(this.sourceBuffer))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=Et(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)&&Ga(this.sourceBuffer.buffered)>=this.bufferLimit){const d=Et(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=Xe(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===ee.FED&&!o.length&&Et(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const u=Xe(i,-1);u&&u.status===ee.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===u))}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;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(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){const r=e.findIndex(({status:c,time:{from:h,to:p}},v)=>{const f=h<=i&&p>=i,S=h>i||f||v===0&&i===0,g=Math.min(this.forwardBufferTarget,this.bufferLimit),E=this.preloadOnly&&h<=i+g||p<=i+g;return(c===ee.NONE||c===ee.PARTIALLY_EJECTED&&S&&E&&this.sourceBuffer&&!mr(this.sourceBuffer.buffered,i))&&S&&E});if(r===-1)return[];if(t!==xe.BYTE_RANGE)return e.slice(r,r+1);const a=e;let n=0,o=0;const u=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=d||o<=l);c++){const h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status===ee.NONE||h.status===ee.PARTIALLY_EJECTED)u.push(h);else break}return u}async loadSegments(e,t,i="auto"){if(!e.length)return;let r,a,n=e;const{type:o}=t.segmentReference;switch(o){case xe.BYTE_RANGE:{r=t.segmentReference.url,a={from:Xe(e,0).byte.from,to:Xe(e,-1).byte.to};break}case xe.TEMPLATE:{const d=Xe(e,0);r=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:O(o)}for(const d of n)d.status=ee.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:u}=this.downloadAbortController;if(this.failedDownloads&&(await Me(u,async function*(){const d=Yr(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,d))}.bind(this))(),u.aborted))for(const d of this.activeSegments)e.includes(d.segment)&&this.abortSegment(d.segment);return void this.fetcher.fetch(r,{range:a,onProgress:(d,l)=>{if(!u.aborted)try{this.onSomeDataLoaded(d,t.id,a?a.from:0,l,u)}catch(c){this.error$.next({id:"SegmentFeeding",category:x.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}},signal:u,priority:i}).then(()=>this.failedDownloads=0,d=>{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&&w(r)&&(i=Et((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:x.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,i,r,a){if(!this.activeSegments.size)return;const n=()=>{this.abort()},o=c=>{var h;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),c.segment.status=ee.FED,"size"in c.segment&&(c.segment.size=c.fedBytes);for(const p of this.representations.values())if(p.id!==t)for(const v of(h=this.segments.get(p.id))!==null&&h!==void 0?h:[])v.status===ee.FED&&v.time.from===c.segment.time.from&&v.time.to===c.segment.time.to&&(v.status=ee.NONE);this.activeSegments.delete(c),this.detectGapsWhenIdle(t,[c.segment])},u=this.representations.get(t);if(!u)return;const d=u.segmentReference.type,l=e.byteLength;for(const c of this.activeSegments){const{segment:h}=c,p=d===xe.BYTE_RANGE,v=p?h.byte.to-h.byte.from+1:l;if(c.representationId!==t||!(!p||h.byte.from>=i&&h.byte.to<i+e.byteLength))continue;if(a.aborted){n();continue}const S=p?h.byte.from-i:0,g=p?h.byte.to-i:e.byteLength,E=S<r,I=g<=r;if(h.status===ee.DOWNLOADING&&E&&I){h.status=ee.DOWNLOADED,this.activeSegments.delete(c);const _=new DataView(e.buffer,e.byteOffset+S,v);this.sourceBufferTaskQueue.append(_,a).then(A=>A&&!a.aborted?o(c):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&E&&(c.loadedBytes=Math.min(v,r-S),c.loadedBytes>c.feedingBytes)){const _=new DataView(e.buffer,e.byteOffset+S+c.feedingBytes,c.loadedBytes-c.feedingBytes),A=c.loadedBytes===v?_:this.containerParser.parseFeedableSegmentChunk(_);A!=null&&A.byteLength&&(h.status=ee.PARTIALLY_FED,c.feedingBytes+=A.byteLength,this.sourceBufferTaskQueue.append(A,a).then(B=>{if(a.aborted)n();else if(B)c.fedBytes+=A.byteLength,c.fedBytes===v&&o(c);else{if(c.feedingBytes<v)return;n()}}))}}}abortSegment(e){e.status===ee.PARTIALLY_FED||e.status===ee.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=ee.NONE),e.status=ee.PARTIALLY_EJECTED):e.status=ee.NONE;for(const t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);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=Ha(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!i&&this.failedDownloads>0?Me(this.destroyAbortController.signal,async function*(){const o=Yr(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(o=>{if(!o)return;const{init:u,dataView:d,segments:l}=o,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c),this.segments.set(e.id,l),this.parsedInitData.set(e.id,u)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:x.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||J(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,n=-1/0,o=!1;const u=d=>{var l;a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const c="size"in d?(l=d.size)!==null&&l!==void 0?l:0:d.byte.to-d.byte.from;r+=c};for(const d of this.segments.values())for(const l of d){if(l.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;l.status===ee.FED&&u(l)}if(o=isFinite(a)&&isFinite(n),!o){r=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const l of d){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;l.status===ee.FED&&u(l)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const l=this.sourceBuffer.buffered.start(d)*1e3,c=this.sourceBuffer.buffered.end(d)*1e3;for(const h of this.segments.values())for(const p of h)if(p.status===ee.NONE&&Math.round(p.time.from)<=Math.round(l)&&Math.round(p.time.to)>=Math.round(c)){a=l,n=c;break}}if(o=isFinite(a)&&isFinite(n),!o&&i){r=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const l of this.segments.values())for(const c of l)c.time.from>e+d&&c.status===ee.FED&&u(c)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}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=Ha(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:x.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(J(this.sourceBuffer)||J(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}const t=1;for(const i of this.segments.values())for(const r of i){const{status:a}=r;if(a!==ee.FED&&a!==ee.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(l=>l.from-t<=n&&l.to+t>=o),d=e.filter(l=>n>=l.from-t&&n<=l.to+t||o>=l.from-t&&o<=l.to+t);u||(d.length===1?r.status=ee.PARTIALLY_EJECTED:r.status=ee.NONE)}}}var Ut;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(Ut||(Ut={}));class Jp{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new b(void 0),this.lastConnectionReused$=new b(void 0),this.lastRequestFirstBytes$=new b(void 0),this.abortAllController=new $t,this.subscription=new ie,this.fetchManifest=Me(this.abortAllController.signal,async function*(r){let a=r;this.requestQuic&&(a=Gt(a));const n=yield Ht(a,{signal:this.abortAllController.signal}).catch(di);return n?(this.onHeadersReceived(n.headers),n.text()):null}.bind(this)),this.fetch=Me(this.abortAllController.signal,async function*(r,{rangeMethod:a=this.compatibilityMode?Ut.HEADER:Ut.PARAM,range:n,onProgress:o,priority:u="auto",signal:d,measureThroughput:l=!0}={}){var c,h,p,v;let f=r;const S=new Headers;if(n)switch(a){case Ut.HEADER:{S.append("Range",`bytes=${n.from}-${n.to}`);break}case Ut.PARAM:{const k=new URL(f,location.href);k.searchParams.append("bytes",`${n.from}-${n.to}`),f=k.toString();break}default:O(a)}this.requestQuic&&(f=Gt(f));let g=this.abortAllController.signal;if(d){const k=new $t;if(this.subscription.add(L(N(this.abortAllController.signal,"abort"),N(d,"abort")).subscribe(()=>{try{k.abort()}catch(H){di(H)}})),this.abortAllController.signal.aborted||d.aborted)try{k.abort()}catch(H){di(H)}g=k.signal}const E=he(),I=yield Ht(f,{priority:u,headers:S,signal:g}).catch(di),_=he();if((c=this.throughputEstimator)===null||c===void 0||c.addRawRtt(_-E),!I)return null;if(!I.ok||!I.body)return Promise.reject(new Error(`Fetch error ${I.status}: ${I.statusText}`));this.onHeadersReceived(I.headers);const A=parseInt((h=I.headers.get("Content-Length"))!==null&&h!==void 0?h:"",10)||n&&n.to-n.from+1||NaN;if(!A){const k=yield I.arrayBuffer();return(p=this.throughputEstimator)===null||p===void 0||p.addRawSpeed(k.byteLength,he()-_),o==null||o(new DataView(k),k.byteLength),k}if(!o&&!l)return I.arrayBuffer();const[B,K]=I.body.tee(),G=B.getReader();l&&((v=this.throughputEstimator)===null||v===void 0||v.trackStream(K));let U=0;const X=new ArrayBuffer(A),F=new Uint8Array(X),M=new DataView(X);let te=!1;const ue=k=>{te=!0,di(k)},me=Me(g,async function*({done:k,value:H}){U===0&&this.lastRequestFirstBytes$.next(he()-E),!g.aborted&&(k?o==null||o(M,U):H&&(F.set(H,U),U+=H.byteLength,o==null||o(M,U),yield G==null?void 0:G.read().then(me,ue)))}.bind(this));return yield G==null?void 0:G.read().then(me,ue),te?null:X}.bind(this)),this.fetchByteRangeRepresentation=Me(this.abortAllController.signal,async function*(r,a,n){var o;if(r.type!==xe.BYTE_RANGE)return null;const{from:u,to:d}=r.initRange;let l=u,c=d,h=!1,p,v;r.indexRange&&(p=r.indexRange.from,v=r.indexRange.to,h=d+1===p,h&&(l=Math.min(p,u),c=Math.max(v,d))),l=Math.min(l,0);const f=yield this.fetch(r.url,{range:{from:l,to:c},priority:n,measureThroughput:!1});if(!f)return null;const S=new DataView(f,u-l,d-l+1);if(!a.validateData(S))throw new Error("Invalid media file");const g=a.parseInit(S),E=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(g);if(!E)throw new ReferenceError("No way to load representation index");let I;if(h)I=new DataView(f,E.from-l,E.to-E.from+1);else{const A=yield this.fetch(r.url,{range:E,priority:n,measureThroughput:!1});if(!A)return null;I=new DataView(A)}const _=a.parseSegments(I,g,E);return{init:g,dataView:new DataView(f),segments:_}}.bind(this)),this.fetchTemplateRepresentation=Me(this.abortAllController.signal,async function*(r,a){if(r.type!==xe.TEMPLATE)return null;const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield this.fetch(n,{priority:a,measureThroughput:!1});if(!o)return null;const u=r.segments.map(d=>({...d,status:ee.NONE,size:void 0}));return{init:{},segments:u,dataView:new DataView(o)}}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=co(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var r,a;const{type:n}=e;switch(n){case xe.BYTE_RANGE:return(r=await this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case xe.TEMPLATE:return(a=await this.fetchTemplateRepresentation(e,i))!==null&&a!==void 0?a:null;default:O(n)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const di=s=>{if(!(s instanceof DOMException)||!(s.name==="AbortError"||s.code===20))throw s};var Kp=_t,Xp=ns,Zp=Ue,em=Zp("match"),tm=function(s){var e;return Kp(s)&&((e=s[em])!==void 0?!!e:Xp(s)=="RegExp")},im=hs,sm=String,rm=function(s){if(im(s)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return sm(s)},am=kt,nm=function(){var s=am(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},om=at,dm=nt,um=yr,lm=nm,za=RegExp.prototype,cm=function(s){var e=s.flags;return e===void 0&&!("flags"in za)&&!dm(s,"flags")&&um(za,s)?om(lm,s):e},Lr=rt,hm=us,fm=Math.floor,Gs=Lr("".charAt),pm=Lr("".replace),Ys=Lr("".slice),mm=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,vm=/\$([$&'`]|\d{1,2})/g,Sm=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=vm;return r!==void 0&&(r=hm(r),u=mm),pm(a,u,function(d,l){var c;switch(Gs(l,0)){case"$":return"$";case"&":return s;case"`":return Ys(e,0,t);case"'":return Ys(e,n);case"<":c=r[Ys(l,1,-1)];break;default:var h=+l;if(h===0)return d;if(h>o){var p=fm(h/10);return p===0?d:p<=o?i[p-1]===void 0?Gs(l,1):i[p-1]+Gs(l,1):d}c=i[h-1]}return c===void 0?"":c})},gm=cs,bm=at,Or=rt,ja=Sr,ym=Oe,Tm=os,Em=tm,Ot=rm,$m=ds,Am=cm,wm=Sm,_m=Ue,km=_m("replace"),Rm=TypeError,So=Or("".indexOf),Pm=Or("".replace),Wa=Or("".slice),Dm=Math.max,Qa=function(s,e,t){return t>s.length?-1:e===""?t:So(s,e,t)};gm({target:"String",proto:!0},{replaceAll:function(e,t){var i=ja(this),r,a,n,o,u,d,l,c,h,p=0,v=0,f="";if(!Tm(e)){if(r=Em(e),r&&(a=Ot(ja(Am(e))),!~So(a,"g")))throw Rm("`.replaceAll` does not allow non-global regexes");if(n=$m(e,km),n)return bm(n,e,i,t);if(r)return Pm(Ot(i),e,t)}for(o=Ot(i),u=Ot(e),d=ym(t),d||(t=Ot(t)),l=u.length,c=Dm(1,l),p=Qa(o,u,0);p!==-1;)h=d?Ot(t(u,p,o)):wm(u,o,p,[],void 0,t),f+=Wa(o,v,p)+h,v=p+l,p=Qa(o,u,p+c);return v<o.length&&(f+=Wa(o,v)),f}});var Im=uo,xm=Im("String","replaceAll"),Cm=xm,Lm=Cm,Om=Lm,Bm=Om,Ja=Bm;const Ka=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},qs=(s,e)=>{let t=s;t=Ja(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=Ja(t,n,(o,u)=>J(a)?o:J(u)?a:a.padStart(parseInt(u,10),"0"))}return t},Mm=(s,e)=>{var t,i,r,a,n,o,u,d,l,c,h,p,v,f,S,g,E,I,_,A,B,K,G,U,X,F,M,te,ue,me,k,H,ne,fe,ve,we,Fe;const Z=new DOMParser().parseFromString(s,"application/xml"),be={video:[],audio:[],text:[]},$e=Z.children[0],Re=$e.getElementsByTagName("Period")[0],vt=Re.children;let Ve;const lt=$e.getAttribute("mediaPresentationDuration"),St=Re.getAttribute("duration");if(lt)Ve=Ka(lt);else if(St){const He=Ka(St);w(He)&&(Ve=He)}let Jt=0;const Dt=(i=(t=$e.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],$o=Dt.includes(is.WEBM_AS_IN_FFMPEG)||Dt.includes(is.WEBM_AS_IN_SPEC)?Yt.WEBM:Yt.MP4;for(const He of vt){const $i=He.getAttribute("mimeType"),Ao=He.getAttribute("codecs"),Br=(r=He.getAttribute("contentType"))!==null&&r!==void 0?r:$i==null?void 0:$i.split("/")[0],wo=(n=(a=He.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],_o=He.querySelectorAll("Representation"),ko=He.querySelector("SegmentTemplate");if(Br!=="text")for(const ye of _o){const Kt=(o=ye.getAttribute("mimeType"))!==null&&o!==void 0?o:$i,Mr=(d=(u=ye.getAttribute("codecs"))!==null&&u!==void 0?u:Ao)!==null&&d!==void 0?d:"",Ai=(c=(l=ye.getAttribute("contentType"))!==null&&l!==void 0?l:Kt==null?void 0:Kt.split("/")[0])!==null&&c!==void 0?c:Br,Ro=(p=(h=He.getAttribute("profiles"))===null||h===void 0?void 0:h.split(","))!==null&&p!==void 0?p:[],Po=parseInt((v=ye.getAttribute("width"))!==null&&v!==void 0?v:"",10),Nr=parseInt((f=ye.getAttribute("height"))!==null&&f!==void 0?f:"",10),Ur=parseInt((S=ye.getAttribute("bandwidth"))!==null&&S!==void 0?S:"",10)/1e3,Fr=(g=ye.getAttribute("frameRate"))!==null&&g!==void 0?g:"",Do=(E=ye.getAttribute("quality"))!==null&&E!==void 0?E:void 0,Io=Fr?xr(Fr):void 0,xo=(I=ye.getAttribute("id"))!==null&&I!==void 0?I:(Jt++).toString(10),Co=Ai==="video"?`${Nr}p`:Ai==="audio"?`${Ur}Kbps`:Mr,Lo=`${xo}@${Co}`,Oo=(B=(A=(_=ye.querySelector("BaseURL"))===null||_===void 0?void 0:_.textContent)===null||A===void 0?void 0:A.trim())!==null&&B!==void 0?B:"",Vr=new URL(Oo,e).toString(),Bo=[...Dt,...wo,...Ro];let vs;const Mo=ye.querySelector("SegmentBase"),gt=(K=ye.querySelector("SegmentTemplate"))!==null&&K!==void 0?K:ko;if(Mo){const Xt=(U=(G=ye.querySelector("SegmentBase Initialization"))===null||G===void 0?void 0:G.getAttribute("range"))!==null&&U!==void 0?U:"",[Zt,gs]=Xt.split("-").map(bt=>parseInt(bt,10)),ei={from:Zt,to:gs},ti=(X=ye.querySelector("SegmentBase"))===null||X===void 0?void 0:X.getAttribute("indexRange"),[bs,wi]=ti?ti.split("-").map(bt=>parseInt(bt,10)):[],ii=ti?{from:bs,to:wi}:void 0;vs={type:xe.BYTE_RANGE,url:Vr,initRange:ei,indexRange:ii}}else if(gt){const Xt={representationId:(F=ye.getAttribute("id"))!==null&&F!==void 0?F:void 0,bandwidth:(M=ye.getAttribute("bandwidth"))!==null&&M!==void 0?M:void 0},Zt=parseInt((te=gt.getAttribute("timescale"))!==null&&te!==void 0?te:"",10),gs=(ue=gt.getAttribute("initialization"))!==null&&ue!==void 0?ue:"",ei=gt.getAttribute("media"),ti=(k=parseInt((me=gt.getAttribute("startNumber"))!==null&&me!==void 0?me:"",10))!==null&&k!==void 0?k:1,bs=qs(gs,Xt);if(!ei)throw new ReferenceError("No media attribute in SegmentTemplate");const wi=(H=gt.querySelectorAll("SegmentTimeline S"))!==null&&H!==void 0?H:[],ii=[];if(wi.length){let bt=ti,yt=0;for(const si of wi){const It=parseInt((ne=si.getAttribute("d"))!==null&&ne!==void 0?ne:"",10)*1e3,ri=parseInt((fe=si.getAttribute("r"))!==null&&fe!==void 0?fe:"",10)||0,ai=(we=parseInt((ve=si.getAttribute("t"))!==null&&ve!==void 0?ve:"",10))!==null&&we!==void 0?we:void 0;for(let Hr=0;Hr<ri+1;Hr++){const No=qs(ei,{...Xt,segmentNumber:bt.toString(10),segmentTime:ai.toString(10)}),Uo=ai?ai/Zt:yt;yt+=It/Zt;const Fo=yt;bt++,ii.push({time:{from:Uo,to:Fo},url:No})}}}else if(w(Ve)){const yt=parseInt((Fe=gt.getAttribute("duration"))!==null&&Fe!==void 0?Fe:"",10)/Zt*1e3,si=Math.ceil(Ve/yt);let It=0;for(let ri=1;ri<si;ri++){const ai=qs(ei,{...Xt,segmentNumber:ri.toString(10),segmentTime:It.toString(10)});ii.push({time:{from:It,to:It+yt},url:ai}),It+=yt}}vs={type:xe.TEMPLATE,baseUrl:Vr,initUrl:bs,segments:ii}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ai||!Kt)continue;const Ss={video:Ie.VIDEO,audio:Ie.AUDIO,text:Ie.TEXT}[Ai];Ss&&be[Ss].push({id:Lo,kind:Ss,segmentReference:vs,profiles:Bo,duration:Ve,bitrate:Ur,mime:Kt,codecs:Mr,width:Po,height:Nr,fps:Io,quality:Do})}}return{duration:Ve,container:$o,representations:be}},Nm=["timeupdate","progress","play","seeked","stalled","waiting"];var De;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(De||(De={}));let Um=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new ie,this.state$=new de(De.NONE),this.currentVideoRepresentation$=new b(void 0),this.currentVideoRepresentationInit$=new b(void 0),this.error$=new C,this.lastConnectionType$=new b(void 0),this.lastConnectionReused$=new b(void 0),this.lastRequestFirstBytes$=new b(void 0),this.forceEnded$=new C,this.gapWatchdogStarted=!1,this.destroyController=new $t,this.initManifest=Me(this.destroyController.signal,async function*(t,i){this.element=t,this.state$.startTransitionTo(De.MANIFEST_READY);const r=yield this.fetcher.fetchManifest(i).catch(o=>this.error$.next({id:"LoadManifest",category:x.NETWORK,message:"Failed to load manifest",thrown:o}));if(!r)return;let a;try{a=Mm(r!=null?r:"",i)}catch(o){this.error$.next({id:"ManifestParsing",category:x.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!a)return;const n=({mime:o,codecs:u})=>{var d,l,c;return Boolean(((d=t.canPlayType)===null||d===void 0?void 0:d.call(t,o))&&((c=(l=window.MediaSource)===null||l===void 0?void 0:l.isTypeSupported)===null||c===void 0?void 0:c.call(l,`${o}; codecs="${u}"`)))};this.manifest={...a,representations:bi(Object.entries(a.representations).map(([o,u])=>[o,u.filter(n)]))},this.manifest.representations.video.length?this.state$.setState(De.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:x.PARSER,message:"No playable video representations"})}.bind(this)),this.initRepresentations=Me(this.destroyController.signal,async function*(t,i){R(this.manifest),R(this.element),this.state$.startTransitionTo(De.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};this.videoBufferManager=new qa(Ie.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],w(i)&&(this.audioBufferManager=new qa(Ie.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,r),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));const a=L(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe($(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=L(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe($(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.subscription.add(L(this.forceEnded$,et({allBuffersFull:a,someBufferEnded:n}).pipe(q(({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:x.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:u})}})),this.subscription.add(L(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield new Promise(o=>{var u;return(u=this.source)===null||u===void 0?void 0:u.addEventListener("sourceopen",o)})),w(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&w(i)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)]):yield this.videoBufferManager.startWith(t),this.state$.setState(De.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=Ho(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),a=>{this.error$.next({id:"GapWatchdog",category:x.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Jp({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initBuffer(){R(this.element),this.state$.setState(De.RUNNING),this.subscription.add(L(...Nm.map(e=>N(this.element,e)),N(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:x.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(N(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(N(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&mr(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){const i={[Ie.VIDEO]:this.videoBufferManager,[Ie.AUDIO]:this.audioBufferManager,[Ie.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),mr(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(De.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(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3,t=[];for(const i of this.bufferManagers)for(const r of i.gaps)i.playingRepresentation$.getValue()===r.representation&&r.from<=e&&r.to>e&&(this.element.duration*1e3-r.to<this.tuning.endGapTolerance?t.push(1/0):t.push(r.to));if(t.length){const i=Math.max(...t);i===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=i/1e3}}};const Fm=135,Vm=76;class Hm{constructor(){this.fov={x:Fm,y:Vm},this.rotation={x:0,y:0,z:0}}}const Bt=10,Xa=175;class Gm{constructor(e,t={}){this.rotating=!1,this.torqueLossTS=0,this.hold=!1,this.options=t,this.camera=e,this.torqueLossTS=performance.now(),this.rotationSpeed={x:0,y:0,z:0},this.rotationMoment={x:0,y:0,z:0}}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.rotation.x+e,this.camera.rotation.y+t,this.camera.rotation.z+i)}pointCameraTo(e=0,t=0,i=0){this.camera.rotation.x=e,this.camera.rotation.y=this.limitCameraRotationY(t),this.camera.rotation.z=i}setRotationSpeed(e,t,i){e===void 0&&(e=this.rotationSpeed.x),t===void 0&&(t=this.rotationSpeed.y),i===void 0&&(i=this.rotationSpeed.z),this.rotationSpeed.x=e,this.rotationSpeed.y=t,this.rotationSpeed.z=i,this.torqueLossTS=performance.now()}startRotation(){this.rotating=!0}stopRotation(e=!1){e&&this.setRotationSpeed(0,0,0),this.rotating=!1,this.torqueLossTS=performance.now()}limitCameraRotationY(e){return Math.max(-Xa,Math.min(e,Xa))}temporalFn(e){const t=100-5e-4*(e-this.torqueLossTS);return Math.sign(t)*Math.sqrt(Math.abs(t))/10}tick(e){if(!this.lastTick){this.lastTick=e;return}const i=(e-this.lastTick)/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*i*Bt,this.rotationSpeed.y*i*Bt,this.rotationSpeed.z*i*Bt);else{let r=0,a=0,n=0;const o=this.temporalFn(e);this.rotationSpeed.x&&(this.rotationSpeed.x=Math.sign(this.rotationSpeed.x)*Math.max(Math.abs(this.rotationSpeed.x)-o,0),r=this.rotationSpeed.x*i*Bt),this.rotationSpeed.y&&(this.rotationSpeed.y=Math.sign(this.rotationSpeed.y)*Math.max(Math.abs(this.rotationSpeed.y)-o,0),a=this.rotationSpeed.y*i*Bt),this.rotationSpeed.z&&(this.rotationSpeed.z=Math.sign(this.rotationSpeed.z)*Math.max(Math.abs(this.rotationSpeed.z)-o,0),n=this.rotationSpeed.z*i*Bt),this.turnCamera(r,a,n)}this.rotationSpeed.x===0&&this.rotationSpeed.y===0&&this.rotationSpeed.z===0&&this.stopRotation(),this.lastTick=e}}const Ym=`
|
|
8
|
+
attribute vec2 a_vertex;
|
|
9
|
+
attribute vec2 a_texel;
|
|
10
|
+
|
|
11
|
+
varying vec2 v_texel;
|
|
12
|
+
|
|
13
|
+
void main(void) {
|
|
14
|
+
// direct vertex drawing
|
|
15
|
+
gl_Position = vec4(a_vertex, 0.0, 1.0);
|
|
16
|
+
// save texel vector to pass to fragment shader
|
|
17
|
+
v_texel = a_texel;
|
|
18
|
+
}
|
|
19
|
+
`,qm=`
|
|
20
|
+
#ifdef GL_ES
|
|
21
|
+
precision highp float;
|
|
22
|
+
precision highp int;
|
|
23
|
+
#else
|
|
24
|
+
precision mediumhp float;
|
|
25
|
+
#endif
|
|
26
|
+
|
|
27
|
+
varying vec2 v_texel; // [0..1, 0..1]
|
|
28
|
+
|
|
29
|
+
uniform sampler2D u_texture;
|
|
30
|
+
uniform vec2 u_focus; // current central point [-180..180, -90..90] (degrees)
|
|
31
|
+
|
|
32
|
+
const float PI = 3.14159265358979323846264;
|
|
33
|
+
const float PI_2 = PI * 0.5;
|
|
34
|
+
const float PI2 = PI * 2.0;
|
|
35
|
+
|
|
36
|
+
void main(void) {
|
|
37
|
+
// center point of output projection
|
|
38
|
+
float lambda0 = u_focus.x / 360.0; // [-0.5, 0.5]
|
|
39
|
+
float phi0 = u_focus.y / 180.0; // [-0.5, 0.5]
|
|
40
|
+
|
|
41
|
+
float x = PI2 * (v_texel.x - 0.5 - lambda0); // [-pi..+pi] (rad)
|
|
42
|
+
float y = PI * (v_texel.y - 0.5 - phi0); // [-pi/2..+pi/2] (rad)
|
|
43
|
+
|
|
44
|
+
float p = sqrt(x * x + y * y); // rou
|
|
45
|
+
float c = atan(p);
|
|
46
|
+
float cos_c = cos(c);
|
|
47
|
+
float sin_c = sin(c);
|
|
48
|
+
|
|
49
|
+
// geo coordinates of projection
|
|
50
|
+
float lambda = lambda0 + atan(
|
|
51
|
+
x * sin_c,
|
|
52
|
+
p * cos(phi0) * cos_c - y * sin(phi0) * sin_c
|
|
53
|
+
);
|
|
54
|
+
float phi = asin(cos_c * sin(phi0) + (y * sin_c * cos(phi0)) / p);
|
|
55
|
+
|
|
56
|
+
// reprojected texture coordinates
|
|
57
|
+
vec2 tc = vec2(
|
|
58
|
+
mod(lambda / PI2 - 0.5, 1.0), // [0..1]
|
|
59
|
+
mod(phi / PI - 0.5, 1.0) // [0..1]
|
|
60
|
+
);
|
|
61
|
+
|
|
62
|
+
// sample using new coordinates
|
|
63
|
+
gl_FragColor = texture2D(u_texture, tc);
|
|
64
|
+
}
|
|
65
|
+
`;class zm{constructor(e,t,i={}){this.videoInitialized=!1,this.lastCameraRotationX=0,this.lastCameraRotationY=0,this.lastCameraRotationT=0,this.lastCameraRotationDX=0,this.lastCameraRotationDY=0,this.mouseDown=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.options=i,this.canvas=document.createElement("canvas");const r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.canvas.classList.add("player-scene3d"),this.container.appendChild(this.canvas),this.camera=new Hm,this.cameraRotationManager=new Gm(this.camera),this.updateViewportSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.onMouseDownHandlerFn=this.mouseDownHandler.bind(this),this.onMouseMoveHandlerFn=this.mouseMoveHandler.bind(this),this.onMouseUpHandlerFn=this.mouseUpHandler.bind(this),this.mouseLeaveHandlerFn=this.mouseLeaveHandler.bind(this),this.initControls(),this.renderFn=this.render.bind(this)}play(){this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",()=>{this.updateViewportSize(),this.vertexBuffer=this.createVertexBuffer(),this.videoInitialized=!0,this.doPlay()})}stop(){this.active=!1}startCameraRotation(e,t,i){this.cameraRotationManager.setRotationSpeed(e,t,i),this.cameraRotationManager.startRotation()}stopCameraRotation(e=!1){this.cameraRotationManager.stopRotation(e)}destroy(e){this.stop(),this.container.removeEventListener("mousedown",this.onMouseDownHandlerFn),this.container.removeEventListener("mousemove",this.onMouseMoveHandlerFn),this.container.removeEventListener("mouseup",this.onMouseUpHandlerFn),this.canvas.remove(),e==null||e()}doPlay(){this.active=!0,requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateViewportSize(),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.rotation.x,-this.camera.rotation.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(Ym,this.gl.VERTEX_SHADER),i=this.createShader(qm,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.rotation.x/360,t=.5-this.camera.rotation.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)}updateViewportSize(){this.frameWidth=this.sourceVideoElement.videoWidth||this.sourceVideoElement.width,this.frameHeight=this.sourceVideoElement.videoHeight||this.sourceVideoElement.height,this.viewportWidth=this.sourceVideoElement.offsetWidth,this.viewportHeight=this.sourceVideoElement.offsetHeight,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}initControls(){this.container.addEventListener("mousedown",this.onMouseDownHandlerFn),this.container.addEventListener("mousemove",this.onMouseMoveHandlerFn),this.container.addEventListener("mouseup",this.onMouseUpHandlerFn),this.container.addEventListener("mouseleave",this.mouseLeaveHandlerFn)}mouseDownHandler(e){e.target===this.canvas&&(this.cameraRotationManager.stopRotation(!0),this.lastCameraRotationX=e.offsetX,this.lastCameraRotationY=e.offsetY,this.lastCameraRotationT=e.timeStamp,this.mouseDown=!0)}mouseMoveHandler(e){if(this.mouseDown){const t=e.offsetX-this.lastCameraRotationX,i=this.lastCameraRotationY-e.offsetY;this.cameraRotationManager.pointCameraTo(this.camera.rotation.x+t,this.camera.rotation.y+i),this.lastCameraRotationX=e.offsetX,this.lastCameraRotationY=e.offsetY,this.lastCameraRotationDX=t,this.lastCameraRotationDY=i,this.lastCameraRotationT=e.timeStamp}}mouseUpHandler(e){this.mouseDown=!1;const t=e.timeStamp-this.lastCameraRotationT;this.cameraRotationManager.setRotationSpeed(this.lastCameraRotationDX*40/t,this.lastCameraRotationDY*40/t)}mouseLeaveHandler(){this.mouseDown=!1,this.lastCameraRotationX=this.lastCameraRotationY=0}}var le;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(le||(le={}));const jm=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a})=>{var n;const o=(n=a?Ti(a):void 0)!==null&&n!==void 0?n:Rt({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r}},Wm=({id:s,bitrate:e})=>({id:s,bitrate:e}),Qm=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=Xe(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:Xe(s,-1)};class Jm{constructor(e){this.subscription=new ie,this.videoState=new de(le.STOPPED),this.elementSize$=new b(void 0),this.textTracksManager=new We,this.videoTracks=[],this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Wf,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(!this.videoState.getTransition()){if(a.state===V.Requested&&(r==null?void 0:r.to)!==m.PAUSED&&t!==le.STOPPED&&i!==m.STOPPED&&this.seek(a.position,a.forcePrecise),i===m.STOPPED){t!==le.STOPPED&&(this.videoState.startTransitionTo(le.STOPPED),this.player.stop(),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(le.STOPPED),P(this.params.desiredState.playbackState,m.STOPPED,!0));return}switch(t){case le.STOPPED:this.videoState.startTransitionTo(le.READY),this.prepare();return;case le.READY:i===m.PAUSED?(this.videoState.setState(le.PAUSED),P(this.params.desiredState.playbackState,m.PAUSED)):i===m.PLAYING?(this.videoState.startTransitionTo(le.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===m.READY&&P(this.params.desiredState.playbackState,m.READY);return;case le.PLAYING:i===m.PAUSED?(this.videoState.startTransitionTo(le.PAUSED),this.video.pause()):(r==null?void 0:r.to)===m.PLAYING&&P(this.params.desiredState.playbackState,m.PLAYING);return;case le.PAUSED:i===m.PLAYING?(this.videoState.startTransitionTo(le.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===m.PAUSED&&P(this.params.desiredState.playbackState,m.PAUSED);return;default:return O(t)}}},this.init3DScene=t=>{this.scene3D||(this.scene3D=new zm(this.params.container,this.video,t),this.scene3D.play())},this.destroy3DScene=()=>{this.scene3D&&this.scene3D.destroy(()=>{this.scene3D=null})},this.params=e,this.video=dt(this.params.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(Ae(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Um({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=ut(this.video),r=d=>{e.error$.next({id:"DashVKProvider",category:x.WTF,message:"DashVKProvider internal logic error",thrown:d})},a=(d,l)=>this.subscription.add(d.subscribe(l,r));a(i.timeUpdate$,e.position$),a(i.durationChange$,e.duration$),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.isAudioAvailable$,e.isAudioAvailable$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.lastRequestFirstBytes$.pipe(q(w),ge(),wt(void 0)),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Pt(this.video,t.isLooped,r)),this.subscription.add(ot(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(pt(this.video,t.playbackRate,i.playbackRateState$,r)),a(es(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(le.PLAYING),P(t.playbackState,m.PLAYING)},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(le.PAUSED),P(t.playbackState,m.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===le.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d===De.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[];const c=this.player.getRepresentations();R(c,"Manifest not loaded or empty");const h=Array.from(c.audio).sort((f,S)=>S.bitrate-f.bitrate),p=Array.from(c.video).sort((f,S)=>S.bitrate-f.bitrate);if(!this.params.tuning.isAudioDisabled)for(const f of h){const S=Wm(f);S&&this.audioTracks.push({track:S,representation:f})}for(const f of p){const S=jm(f);if(S){this.videoTracks.push({track:S,representation:f});const g=!this.params.tuning.isAudioDisabled&&Qm(h,p,f);g&&this.audioRepresentations.set(f.id,g)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:f})=>f)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:f})=>f)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length);const v=this.selectVideoRepresentation();R(v),this.player.initRepresentations(v.id,(l=this.audioRepresentations.get(v.id))===null||l===void 0?void 0:l.id)}else d===De.REPRESENTATIOS_READY&&(this.videoState.setState(le.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:x.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(L(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,N(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!==De.RUNNING||l||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation();if(c){this.player.switchRepresentation(Ie.VIDEO,c.id).catch(n);const h=this.audioRepresentations.get(c.id);h&&this.player.switchRepresentation(Ie.AUDIO,h.id).catch(n)}},r)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(pe(),$(d=>{var l;return d&&((l=this.videoTracks.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=>{if(d)if(d.is3dVideo)try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(l){}else this.destroy3DScene(),e.is3DVideo$.next(!1)},r)),this.params.desiredState.cameraRotation.stateChangeEnded$.subscribe(()=>{if(this.scene3D){const d=this.params.desiredState.cameraRotation.getState();d?this.scene3D.startCameraRotation(d.x,d.y,d.z):this.scene3D.stopCameraRotation(!1)}}),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe($(({to:d})=>d===m.READY),pe());this.subscription.add(L(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(L(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===m.READY)));const u=L(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Le(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,i,r,a,n;const o=this.params.desiredState.autoVideoTrackSwitching.getState(),u=this.params.desiredState.videoTrack.getState(),d=(e=this.videoTracks.find(({track:{id:g}})=>g===u))===null||e===void 0?void 0:e.track,l=this.params.output.currentVideoTrack$.getValue(),c=Et(this.video.buffered,this.video.currentTime*1e3),h=o?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=Math.min(c/Math.min(h,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),v=Math.max(d&&!o&&(i=(t=this.audioRepresentations.get(d.id))===null||t===void 0?void 0:t.bitrate)!==null&&i!==void 0?i:0,l&&(a=(r=this.audioRepresentations.get(l.id))===null||r===void 0?void 0:r.bitrate)!==null&&a!==void 0?a:0),f=yi(this.videoTracks.map(({track:g})=>g),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:p,current:l,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),S=o?f!=null?f:d:d!=null?d:f;return S&&((n=this.videoTracks.find(({track:g})=>g===S))===null||n===void 0?void 0:n.representation)}async prepare(){this.player.initManifest(this.video,this.params.source.url)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}destroy(){this.subscription.unsubscribe(),this.destroy3DScene(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){mt(this.video).then(e=>{e||(this.videoState.setState(le.PAUSED),P(this.params.desiredState.playbackState,m.PAUSED,!0))})}}const Km=5e3,Je={};var Q;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Q||(Q={}));const Mi=(s,e)=>new mi(t=>{const i=(r,a)=>t.next(a);return s.on(e,i),()=>s.off(e,i)});class Xm{constructor(e){this.subscription=new ie,this.videoState=new de(Q.INITIALIZING),this.textTracksManager=new We,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!==Q.INITIALIZING)switch((r==null?void 0:r.to)!==m.PAUSED&&a.state===V.Requested&&this.seek(a.position),i){case m.STOPPED:switch(t){case Q.STOPPED:break;case Q.READY:case Q.PLAYING:case Q.PAUSED:this.stop();break;default:O(t)}break;case m.READY:switch(t){case Q.STOPPED:this.prepare();break;case Q.READY:case Q.PLAYING:case Q.PAUSED:break;default:O(t)}break;case m.PLAYING:switch(t){case Q.PLAYING:break;case Q.STOPPED:this.prepare();break;case Q.READY:case Q.PAUSED:this.playIfAllowed();break;default:O(t)}break;case m.PAUSED:switch(t){case Q.PAUSED:break;case Q.STOPPED:this.prepare();break;case Q.READY:this.videoState.setState(Q.PAUSED),P(this.params.desiredState.playbackState,m.PAUSED);break;case Q.PLAYING:this.pause();break;default:O(t)}break;default:O(i)}},this.video=dt(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(Ae(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.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:x.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),Km);import("hls.js/dist/hls.min.js").then(r=>{e||(Je.Hls=r.default,Je.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){R(Je.Hls,"hls.js not loaded"),this.hls=new Je.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(Q.STOPPED)}subscribe(){R(Je.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:x.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=ut(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.isAudioAvailable$,t.isAudioAvailable$),this.subscription.add(Pt(this.video,e.isLooped,i)),this.subscription.add(ot(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(pt(this.video,e.playbackRate,r.playbackRateState$,i)),this.subscription.add(Mi(this.hls,Je.Events.ERROR).subscribe(d=>{var l;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:x.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(Q.PLAYING),P(e.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(Q.PAUSED),P(e.playbackState,m.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())===null||d===void 0?void 0:d.to)===Q.READY&&this.videoState.setState(Q.READY),this.videoState.getState()===Q.PLAYING&&this.playIfAllowed()},i)),a(Mi(this.hls,Je.Events.MANIFEST_PARSED).pipe($(({levels:d})=>d.reduce((l,c)=>{var h,p;const v=c.name||c.height.toString(10),{width:f,height:S}=c,g=(p=Ti((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&p!==void 0?p:Rt({width:f,height:S});if(!g)return l;const E=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,I={id:v.toString(),quality:g,bitrate:c.bitrate/1e3,size:{width:f,height:S},fps:E};return this.trackLevels.set(v,{track:I,level:c}),l.push(I),l},[]))),t.availableVideoTracks$),a(Mi(this.hls,Je.Events.LEVEL_LOADING).pipe($(({url:d})=>Ae(d))),t.hostname$),this.subscription.add(ze(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=Mi(this.hls,Je.Events.LEVEL_SWITCHED).pipe($(({level:d})=>n(this.hls.levels[d])));o.pipe(q(w)).subscribe(t.currentVideoTrack$,i),this.subscription.add(ze(e.videoTrack,()=>{var d;return(d=n(this.hls.levels[this.hls.currentLevel]))===null||d===void 0?void 0:d.id},d=>{var l;if(J(d))return;const c=(l=this.trackLevels.get(d))===null||l===void 0?void 0:l.level;if(!c)return;const h=this.hls.levels.indexOf(c),p=this.hls.currentLevel,v=this.hls.levels[p];!v||c.bitrate>v.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o.pipe($(d=>d==null?void 0:d.id)),onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const u=L(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Le(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(Q.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(Q.PLAYING),await mt(this.video)||(this.videoState.setState(Q.PAUSED),P(this.params.desiredState.playbackState,m.PAUSED,!0))}pause(){this.videoState.startTransitionTo(Q.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.setAttribute("src",""),this.video.load(),this.videoState.setState(Q.STOPPED),P(this.params.desiredState.playbackState,m.STOPPED,!0)}}const Za="X-Playback-Duration";var en=async s=>{const e=await Ht(s,{method:"HEAD"});return e.headers.has(Za)?parseInt(e.headers.get(Za),10):void 0};const Zm=s=>{let e=null;if(s.QUALITY&&(e=Ti(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Rt({width:t,height:i})}return e!=null?e:null},go=async(s,e=s)=>{var t;const a=(await(await Ht(s)).text()).split(`
|
|
66
|
+
`),n=[];for(let o=0;o<a.length;o++){const d=a[o].match(/^#EXT-X-STREAM-INF:(.+)/);if(!d)continue;const l=bi(d[1].split(",").map(g=>g.split("="))),c=(t=l.QUALITY)!==null&&t!==void 0?t:`stream-${l.BANDWIDTH}`,h=Zm(l);let p;l.BANDWIDTH&&(p=parseInt(l.BANDWIDTH,10)/1e3||void 0),!p&&l["AVERAGE-BANDWIDTH"]&&(p=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const v=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0;let f;if(l.RESOLUTION){const[g,E]=l.RESOLUTION.split("x").map(I=>parseInt(I,10));g&&E&&(f={width:g,height:E})}const S=new URL(a[++o],e).toString();h&&n.push({id:c,quality:h,url:S,bandwidth:p,size:f,fps:v})}return n};var se;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(se||(se={}));class ev{constructor(e){var t;this.subscription=new ie,this.videoState=new de(se.STOPPED),this.textTracksManager=new We,this.manifests$=new b([]),this.liveOffset=new Ir,this.manifestStartTime$=new b(void 0),this.syncPlayback=()=>{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!==se.STOPPED&&(this.videoState.startTransitionTo(se.STOPPED),this.video.setAttribute("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(se.STOPPED),P(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(r===se.STOPPED){this.videoState.startTransitionTo(se.READY),this.prepare();return}if(o||u){const c=this.videoState.getState();this.videoState.setState(se.CHANGING_MANIFEST),this.videoState.startTransitionTo(c),this.prepare(),l.state===V.None&&this.params.desiredState.seekState.setState({state:V.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==m.PAUSED&&l.state===V.Requested){this.videoState.startTransitionTo(se.READY),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case se.READY:a===m.READY?P(this.params.desiredState.playbackState,m.READY):a===m.PAUSED?(this.videoState.setState(se.PAUSED),this.liveOffset.pause(),P(this.params.desiredState.playbackState,m.PAUSED)):a===m.PLAYING&&(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed());return;case se.PLAYING:a===m.PAUSED?(this.videoState.startTransitionTo(se.PAUSED),this.liveOffset.pause(),this.video.pause()):(n==null?void 0:n.to)===m.PLAYING&&P(this.params.desiredState.playbackState,m.PLAYING);return;case se.PAUSED:a===m.PLAYING?(this.videoState.startTransitionTo(se.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)):this.seek(-this.liveOffset.getTotalOffset())):(n==null?void 0:n.to)===m.PAUSED&&(P(this.params.desiredState.playbackState,m.PAUSED),this.liveOffset.pause());return;case se.CHANGING_MANIFEST:break;default:return O(r)}},this.params=e,this.video=dt(e.container),this.params.output.element$.next(this.video);const i={id:"master",quality:ae.INVARIANT,url:this.params.source.url};this.manifests$.next([i]),go(Vt(this.params.source.url),this.params.source.url).then(r=>{this.manifests$.next([i,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:x.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ae(this.params.source.url)),this.maxSeekBackTime$=new b((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)return;const d=a?"master":o;return a&&!n&&r.startTransitionTo("master"),u.find(l=>l.id===d)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:x.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=ut(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.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(ot(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(se.PLAYING),P(t.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(se.PAUSED),P(t.playbackState,m.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===se.READY&&this.videoState.setState(se.READY),this.videoState.getState()===se.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(pe(),$(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&&w(d.to)){const c=d.to;this.params.desiredState.videoTrack.setState(c);const h=this.manifests$.getValue().find(p=>p.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Ae(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===se.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===V.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(et({startTime:this.manifestStartTime$.pipe(q(w)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe($(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));const n=L(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,ke(["init"])).pipe(Le(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();if(J(e))return;const t=Vt(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),en(t).then(i=>{var r;if(!J(i))this.maxSeekBackTime$.next(i);else{const a=(r=this.params.source.maxSeekBackTime)!==null&&r!==void 0?r:this.maxSeekBackTime$.getValue();if(J(a)||!isFinite(a))try{Ht(t).then(n=>n.text()).then(n=>{var o;const u=(o=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(n))===null||o===void 0?void 0:o[1];if(u){const d=new URL(u,t).toString();en(d).then(l=>{J(l)||this.maxSeekBackTime$.next(l)})}})}catch(n){}}})}playIfAllowed(){mt(this.video).then(e=>{e||(this.videoState.setState(se.PAUSED),this.liveOffset.pause(),P(this.params.desiredState.playbackState,m.PAUSED,!0))})}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 oe;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(oe||(oe={}));class tv{constructor(e){this.subscription=new ie,this.videoState=new de(oe.STOPPED),this.textTracksManager=new We,this.manifests$=new b([]),this.syncPlayback=()=>{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!==oe.STOPPED&&(this.videoState.startTransitionTo(oe.STOPPED),this.video.setAttribute("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(oe.STOPPED),P(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.seekState.getState();if(i===oe.STOPPED){this.videoState.startTransitionTo(oe.READY),this.prepare();return}if(n||o){const l=this.videoState.getState();this.videoState.setState(oe.CHANGING_MANIFEST),this.videoState.startTransitionTo(l);const{currentTime:c}=this.video;this.prepare(),d.state===V.None&&this.params.desiredState.seekState.setState({state:V.Requested,position:c*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==m.PAUSED&&d.state===V.Requested&&this.seek(d.position),i){case oe.READY:r===m.READY?P(this.params.desiredState.playbackState,m.READY):r===m.PAUSED?(this.videoState.setState(oe.PAUSED),P(this.params.desiredState.playbackState,m.PAUSED)):r===m.PLAYING&&(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed());return;case oe.PLAYING:r===m.PAUSED?(this.videoState.startTransitionTo(oe.PAUSED),this.video.pause()):(a==null?void 0:a.to)===m.PLAYING&&P(this.params.desiredState.playbackState,m.PLAYING);return;case oe.PAUSED:r===m.PLAYING?(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===m.PAUSED&&P(this.params.desiredState.playbackState,m.PAUSED);return;case oe.CHANGING_MANIFEST:break;default:return O(i)}},this.params=e,this.video=dt(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:ae.INVARIANT,url:this.params.source.url};this.manifests$.next([t]),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(Ae(this.params.source.url)),go(this.params.source.url).then(i=>{this.manifests$.next([t,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:x.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),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)return;const d=a?"master":o;return a&&!n&&r.startTransitionTo("master"),u.find(l=>l.id===d)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:x.WTF,message:"HlsProvider internal logic error",thrown:o})},r=ut(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));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.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(Pt(this.video,t.isLooped,i)),this.subscription.add(ot(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(oe.PLAYING),P(t.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(oe.PAUSED),P(t.playbackState,m.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===oe.READY&&this.videoState.setState(oe.READY),this.videoState.getState()===oe.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&&w(d.to)){const c=d.to;this.params.desiredState.videoTrack.setState(c);const h=this.manifests$.getValue().find(p=>p.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Ae(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===oe.CHANGING_MANIFEST&&this.videoState.setState(u.to),o.state===V.Requested&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe($(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));const n=L(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Le(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();J(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){mt(this.video).then(e=>{e||(this.videoState.setState(oe.PAUSED),P(this.params.desiredState.playbackState,m.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var ce;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(ce||(ce={}));class iv{constructor(e){this.subscription=new ie,this.videoState=new de(ce.STOPPED),this.trackUrls={},this.textTracksManager=new We,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(i===m.STOPPED){t!==ce.STOPPED&&(this.videoState.startTransitionTo(ce.STOPPED),this.video.setAttribute("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(ce.STOPPED),P(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(t===ce.STOPPED){this.videoState.startTransitionTo(ce.READY),this.prepare();return}if(n){const{currentTime:u}=this.video;this.prepare(),o.state===V.None&&this.params.desiredState.seekState.setState({state:V.Requested,position:u*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!==m.PAUSED&&o.state===V.Requested&&this.seek(o.position),t){case ce.READY:i===m.READY?P(this.params.desiredState.playbackState,m.READY):i===m.PAUSED?(this.videoState.setState(ce.PAUSED),P(this.params.desiredState.playbackState,m.PAUSED)):i===m.PLAYING&&(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed());return;case ce.PLAYING:i===m.PAUSED?(this.videoState.startTransitionTo(ce.PAUSED),this.video.pause()):(r==null?void 0:r.to)===m.PLAYING&&P(this.params.desiredState.playbackState,m.PLAYING);return;case ce.PAUSED:i===m.PLAYING?(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===m.PAUSED&&P(this.params.desiredState.playbackState,m.PAUSED);return;default:return O(t)}},this.params=e,this.video=dt(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).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.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:x.WTF,message:"MpegProvider internal logic error",thrown:o})},r=ut(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.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(Pt(this.video,t.isLooped,i)),this.subscription.add(ot(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(pt(this.video,t.playbackRate,r.playbackRateState$,i)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ce.PLAYING),P(t.playbackState,m.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ce.PAUSED),P(t.playbackState,m.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ce.READY&&this.videoState.setState(ce.READY);const u=this.params.desiredState.videoTrack.getTransition();u&&w(u.to)&&(this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to].track)),this.videoState.getState()===ce.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const n=L(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Le(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){var e,t;const i=(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();R(i,"MpegProvider: track is not selected");let{url:r}=this.trackUrls[i];R(r,`MpegProvider: No url for ${i}`),this.params.tuning.requestQuick&&(r=Gt(r)),this.video.setAttribute("src",r),this.video.load(),this.params.output.hostname$.next(Ae(r))}playIfAllowed(){mt(this.video).then(e=>{e||(this.videoState.setState(ce.PAUSED),P(this.params.desiredState.playbackState,m.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}const tn=["stun:videostun.mycdn.me:80"],sv=1e3,rv=3,zs=()=>null;class av{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=zs,this.externalStopCallback=zs,this.externalErrorCallback=zs,this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:tn}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:x.WTF,message:e.message})}async onPeerConnectionStream(e){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),sv)}normalizeOptions(e={}){const t={stunServerList:tn,maxRetryNumber:rv,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var re;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(re||(re={}));class nv{constructor(e){this.videoState=new de(re.STOPPED),this.maxSeekBackTime$=new b(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!==re.STOPPED&&(this.videoState.startTransitionTo(re.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(re.STOPPED),P(this.params.desiredState.playbackState,m.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===re.STOPPED){this.videoState.startTransitionTo(re.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case re.READY:i===m.PAUSED?(this.videoState.setState(re.PAUSED),P(this.params.desiredState.playbackState,m.PAUSED)):i===m.PLAYING&&(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed());return;case re.PLAYING:i===m.PAUSED?(this.videoState.startTransitionTo(re.PAUSED),this.video.pause()):(r==null?void 0:r.to)===m.PLAYING&&P(this.params.desiredState.playbackState,m.PLAYING);return;case re.PAUSED:i===m.PLAYING?(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===m.PAUSED&&P(this.params.desiredState.playbackState,m.PAUSED);return;default:return O(t)}},this.subscription=new ie,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=dt(e.container),this.liveStreamClient=new av(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.video.remove(),this.params.output.element$.next(void 0),this.liveStreamClient.disconnect()}subscribe(){const{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:x.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};L(this.videoState.stateChangeStarted$.pipe($(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe($(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const r=ut(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$),a(r.isAudioAvailable$,e.isAudioAvailable$),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)===re.READY&&this.videoState.setState(re.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(re.PAUSED)},i)).add(r.playing$.subscribe(()=>{this.videoState.setState(re.PLAYING)},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ot(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case re.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(m.STOPPED);break;case re.READY:break;case re.PAUSED:t.playbackState.setState(m.PAUSED);break;case re.PLAYING:t.playbackState.setState(m.PLAYING);break;default:return O(n.to)}},i)).add(L(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Le(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.hostname$.next(Ae(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:ae.INVARIANT}),this.video.srcObject=e,P(this.params.desiredState.playbackState,m.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(re.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:x.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){mt(this.video).then(e=>{e||(this.videoState.setState(re.PAUSED),P(this.params.desiredState.playbackState,m.PAUSED,!0))})}prepare(){this.liveStreamClient.connect()}}class sn{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 Boolean(this.current.done)}}var ov=()=>{var s,e;const t=window.navigator;return t.userAgentData?((e=(s=t.userAgentData)===null||s===void 0?void 0:s.platform)===null||e===void 0?void 0:e.toLowerCase())==="android":window.navigator.userAgent.toLowerCase().includes("android")},js,Ws,Qs,Js,Ks,Xs,Ni,Zs,Ui,er,Fi,tr,Vi,ir,Hi,sr;const bo=ov(),ct=document.createElement("video"),Ke={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&((Ws=(js=window.SourceBuffer)===null||js===void 0?void 0:js.prototype)===null||Ws===void 0?void 0:Ws.appendBuffer)),hls:Boolean(((Qs=ct.canPlayType)===null||Qs===void 0?void 0:Qs.call(ct,"application/x-mpegurl"))||((Js=ct.canPlayType)===null||Js===void 0?void 0:Js.call(ct,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection)},Pe={mp4:Boolean((Ks=ct.canPlayType)===null||Ks===void 0?void 0:Ks.call(ct,"video/mp4")),webm:Boolean((Xs=ct.canPlayType)===null||Xs===void 0?void 0:Xs.call(ct,"video/webm")),cmaf:!0},ht={h264:Boolean((Zs=(Ni=window.MediaSource)===null||Ni===void 0?void 0:Ni.isTypeSupported)===null||Zs===void 0?void 0:Zs.call(Ni,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean((er=(Ui=window.MediaSource)===null||Ui===void 0?void 0:Ui.isTypeSupported)===null||er===void 0?void 0:er.call(Ui,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean((tr=(Fi=window.MediaSource)===null||Fi===void 0?void 0:Fi.isTypeSupported)===null||tr===void 0?void 0:tr.call(Fi,'video/webm; codecs="vp9"')),aac:Boolean((ir=(Vi=window.MediaSource)===null||Vi===void 0?void 0:Vi.isTypeSupported)===null||ir===void 0?void 0:ir.call(Vi,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean((sr=(Hi=window.MediaSource)===null||Hi===void 0?void 0:Hi.isTypeSupported)===null||sr===void 0?void 0:sr.call(Hi,'audio/webm; codecs="opus"'))},Mt=(ht.h264||ht.h265)&&ht.aac,ms=Ke.hls&&Pe.mp4,dv=Boolean(window.WebSocket),uv=()=>Object.keys(ht).filter(s=>ht[s]),lv=(s,e=!1)=>s.filter(t=>{switch(t){case y.DASH:return Ke.mse&&Pe.mp4&&Mt;case y.DASH_SEP:return Ke.mse&&Pe.mp4&&Mt;case y.DASH_WEBM:return Ke.mse&&Pe.webm&&ht.vp9&&ht.opus;case y.DASH_LIVE:return Ke.mse&&Pe.mp4&&Mt;case y.DASH_LIVE_CMAF:return Ke.mse&&Pe.mp4&&Mt&&Pe.cmaf;case y.DASH_ONDEMAND:return Ke.mse&&Pe.mp4&&Mt;case y.HLS:case y.HLS_LIVE:case y.HLS_LIVE_CMAF:case y.HLS_ONDEMAND:return ms||e&&Ke.mse&&Pe.mp4&&Mt;case y.MPEG:return Pe.mp4;case y.DASH_LIVE_WEBM:return!1;case y.WEB_RTC_LIVE:return Ke.webrtc&&dv&&ht.h264&&(Pe.mp4||Pe.webm);default:return O(t)}}),cv=()=>bo?[y.MPEG,y.DASH_WEBM,y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND]:ms?[y.DASH_WEBM,y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG,y.DASH]:[y.DASH_WEBM,y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG],hv=()=>bo?[y.HLS_LIVE,y.HLS_LIVE_CMAF,y.WEB_RTC_LIVE,y.DASH_LIVE,y.DASH_LIVE_CMAF]:ms?[y.WEB_RTC_LIVE,y.HLS_LIVE,y.HLS_LIVE_CMAF,y.DASH_LIVE,y.DASH_LIVE_CMAF]:[y.WEB_RTC_LIVE,y.DASH_LIVE,y.DASH_LIVE_CMAF,y.HLS_LIVE,y.HLS_LIVE_CMAF],rn=s=>s?[y.HLS_LIVE]:[y.DASH_WEBM,y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG];var fv=s=>new mi(e=>{const t=new ie,i=s.desiredPlaybackState$.stateChangeStarted$.pipe($(({from:d,to:l})=>`${d}-${l}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$,n=new C;let o=0,u="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>n.next(d),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="provider change",o=0})),t.add(a.subscribe(()=>{o&&(window.clearTimeout(o),o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const an={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},pv={cacheDuration:12e4},mv={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},vv={maxPausedTime:3e4},nn={maxPausedTime:3e4};class Sv{constructor(e){this.current$=new b({type:void 0}),this.providerError$=new C,this.noAvailableProvidersError$=new C,this.providerOutput={position$:new b(0),duration$:new b(1/0),volume$:new b({muted:!1,volume:1}),currentVideoTrack$:new b(void 0),availableVideoTracks$:new b([]),availableAudioTracks$:new b([]),isAudioAvailable$:new b(!0),autoVideoTrackLimitingAvailable$:new b(!1),currentBuffer$:new b(void 0),isBuffering$:new b(!0),error$:new C,willSeekEvent$:new C,seekedEvent$:new C,loopedEvent$:new C,endedEvent$:new C,firstBytesEvent$:new C,firstFrameEvent$:new C,canplay$:new C,isLive$:new b(void 0),liveTime$:new b(void 0),availableTextTracks$:new b([]),currentTextTrack$:new b(void 0),hostname$:new b(void 0),httpConnectionType$:new b(void 0),httpConnectionReused$:new b(void 0),element$:new b(void 0),is3DVideo$:new b(!1)},this.subscription=new ie,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=lv([...hv(),...cv()],this.params.tuning.useHlsJs).filter(n=>w(e.sources[n])),{formatsToAvoid:i}=this.params.tuning,r=i.length?[...t.filter(n=>!i.includes(n)),...t.filter(n=>i.includes(n))]:t;this.screenFormatsIterator=new sn(r);const a=[...rn(!0),...rn(!1)];this.chromecastFormatsIterator=new sn(a.filter(n=>w(e.sources[n])))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(J(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:x.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const e=this.current$.getValue().destination;R(e,"No current provider"),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!==V.None;this.params.desiredState.seekState.setState({state:V.Requested,position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case _e.SCREEN:return this.createScreenProvider(t);case _e.CHROMECAST:return this.createChromecastProvider(t);default:return O(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 y.DASH:{const o=this.applyFailoverHost(t[e]);return R(o),new Sp({...n,source:o,config:pv})}case y.DASH_SEP:case y.DASH_WEBM:case y.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return R(o),this.params.tuning.useDashJs?new Fa({...n,source:o,format:e,config:nn}):new Jm({...n,source:o})}case y.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return R(o),new Fa({...n,source:o,format:e,config:nn})}case y.HLS:case y.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return R(o),ms||!this.params.tuning.useHlsJs?new tv({...n,source:o}):new Xm({...n,source:o})}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return R(o),new ev({...n,source:o,config:vv})}case y.MPEG:{const o=this.applyFailoverHost(t[e]);return R(o),new iv({...n,source:o})}case y.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return R(o),new hp({...n,source:o,config:mv})}case y.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return R(o),new nv({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return O(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 bf({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()?_e.CHROMECAST:_e.SCREEN}chooseFormat(e){switch(e){case _e.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case _e.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return O(e)}}skipFormat(e){switch(e){case _e.SCREEN:return this.screenFormatsIterator.next();case _e.CHROMECAST:return this.chromecastFormatsIterator.next();default:return O(e)}}handleNoFormatsError(e){switch(e){case _e.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case _e.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return O(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=r=>{const a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return bi(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){const e=new ie;let t=!1,i=0;return e.add(L(this.providerOutput.error$,fv({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:an.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(q(({type:r})=>r!==void 0))}).pipe($(r=>({id:`ProviderHangup:${r}`,category:x.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(q(({to:a})=>a===m.PLAYING),ge()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{if(this.current$.getValue().destination===_e.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const a=r.category===x.NETWORK,n=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),o=i<an.providerErrorLimit;n&&(a&&t||!o)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):o?(i++,this.reinitProvider()):this.switchToNextProvider()}})),e}}var Ce;(function(s){s[s.LOCAL_STORAGE=0]="LOCAL_STORAGE",s[s.SESSION_STORAGE=1]="SESSION_STORAGE",s[s.RUNTIME=2]="RUNTIME"})(Ce||(Ce={}));const yo=new Map;let At=Ce.RUNTIME;const rr=`vk-videoplayer-dummy-key-${Math.random()}`,gv=()=>{try{localStorage.setItem(rr,"test"),localStorage.removeItem(rr),At=Ce.LOCAL_STORAGE}catch(s){if(s instanceof DOMException||s instanceof TypeError)try{sessionStorage.getItem(rr),At=Ce.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)At=Ce.RUNTIME;else throw e}else throw s}};gv();const bv=s=>{var e,t;switch(At){case Ce.LOCAL_STORAGE:return(e=localStorage.getItem(s))!==null&&e!==void 0?e:void 0;case Ce.SESSION_STORAGE:return(t=sessionStorage.getItem(s))!==null&&t!==void 0?t:void 0;case Ce.RUNTIME:return yo.get(s);default:O(At)}},on=(s,e)=>{switch(At){case Ce.LOCAL_STORAGE:try{localStorage.setItem(s,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Ce.SESSION_STORAGE:try{sessionStorage.setItem(s,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Ce.RUNTIME:return void yo.set(s,e);default:O(At)}},vr=(s,e,t)=>t*e+(1-t)*s,To=(s,e)=>s.reduce((t,i)=>t+i,0)/e,yv=(s,e,t,i)=>{let r=0,a=t;const n=To(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 Eo{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 b(e.initial),this.debounced$=new b(e.initial);const i=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ye(`raw_${i}`),this.smoothedSeries$=new Ye(`smoothed_${i}`),this.reportedSeries$=new Ye(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(J(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class Tv extends Eo{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=vr(this.slow,e,this.params.emaAlphaSlow),this.fast=vr(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Ev extends Eo{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=To(this.pastMeasures,this.takenMeasures);this.emaSmoothed=vr(this.emaSmoothed,e,this.params.emaAlpha);const i=yv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class dn{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Tv({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Ev({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}}const $v=5e3,un="one_video_throughput",ln="one_video_rtt",it=window.navigator.connection,cn=()=>{const s=it==null?void 0:it.downlink;if(w(s)&&s!==10)return s*1e3},hn=()=>{const s=it==null?void 0:it.rtt;if(w(s)&&s!==3e3)return s},fn=(s,e,t)=>{const i=t*8,r=i/s;return i/(r+e)};class hi{constructor(e){var t,i;this.subscription=new ie,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=hi.load(un)||(e.useBrowserEstimation?cn():void 0)||$v,a=(i=(t=hi.load(ln))!==null&&t!==void 0?t:e.useBrowserEstimation?hn():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new b(r),this.rtt$=new b(a),this.rttAdjustedThroughput$=new b(fn(r,a,e.rttPenaltyRequestSize)),this.throughput=dn.getSmoothedValue(r,-1,e),this.rtt=dn.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const u=cn();u&&this.throughput.next(u);const d=hn();w(d)&&this.rtt.next(d)};it&&"onchange"in it&&this.subscription.add(N(it,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{on(un,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{on(ln,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(et({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe($(({throughput:n,rtt:o})=>fn(n,o,e.rttPenaltyRequestSize)),q(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 ie;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(N(e,"progress").pipe(ge()).subscribe(a=>{t=a.loaded,i=he()}));break;case 1:case 0:r.add(N(e,"loadstart").subscribe(()=>{t=0,i=he()}));break}r.add(N(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){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let i=0;const r=he();let a=0,n=he();const o=d=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},u=async({done:d,value:l})=>{d?(this.addRawSpeed(i,he()-r,1),this.concurrentDownloads.delete(e)):l&&(i+=l.byteLength,a+=l.byteLength,a>=this.tuningConfig.streamMinSampleSize&&he()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,he()-n,this.concurrentDownloads.size),a=0,n=he()),await(t==null?void 0:t.read().then(u,o)))};this.concurrentDownloads.add(e),t==null||t.read().then(u,o)}addRawSpeed(e,t,i=1){if(hi.sanityCheck(e,t)){const r=e*8/t;this.throughput.next(r*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=bv(e);if(w(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const pn={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},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,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,useHlsJs:!0,isAudioDisabled:!1,webrtc:{connectionRetryMaxNumber:3}},Av=s=>{const e={};for(const t of Object.keys(pn)){const i=pn[t],r=s[t];Array.isArray(i)&&Array.isArray(r)?e[t]=r:typeof i=="object"&&typeof r=="object"?e[t]={...i,...r}:e[t]=r!=null?r:i}return e};var wv=({seekState:s,position$:e})=>L(s.stateChangeEnded$.pipe($(({to:t})=>{var i;return t.state===V.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),q(w)),e.pipe(q(()=>s.getState().state===V.None))),_v=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return R(e,`Wrong container or containerId {${s.container}}`),e};const mn=({playbackState:s,seekState:e,playbackAbort$:t,looped$:i,position$:r})=>new mi(a=>{let n;const o=s.transitionEnded$.pipe(q(p=>(p.from===m.PAUSED||p.from===m.STOPPED)&&p.to===m.PLAYING)),u=s.stateChangeEnded$.pipe(q(p=>p.from===m.PLAYING&&p.to===m.PAUSED)),d=e.stateChangeEnded$.pipe(q(({to:p})=>{var v,f;return p.state===V.Requested&&((f=(v=s.getTransition())===null||v===void 0?void 0:v.from)!==null&&f!==void 0?f:s.getState())===m.PLAYING})),l=e.stateChangeEnded$.pipe(q(({from:p,to:v})=>{var f,S;return p.state===V.Applying&&v.state===V.None&&((S=(f=s.getTransition())===null||f===void 0?void 0:f.from)!==null&&S!==void 0?S:s.getState())===m.PLAYING})),c=L(o,l).pipe($(()=>r.getValue()),q(w)),h=L(L(u,d,t),i).pipe($(()=>r.getValue()),q(w));return new ie().add(c.subscribe(p=>{n=p})).add(h.subscribe(p=>{if(J(n)||n===p)return;const v={from:n,to:p};n=void 0,a.next(v)}))});class xv{constructor(e={}){if(this.subscription=new ie,this.logger=new Go,this.isPlaybackStarted=!1,this.desiredState={playbackState:new de(m.STOPPED),seekState:new de({state:V.None}),volume:new de({volume:1,muted:!1}),videoTrack:new de(void 0),autoVideoTrackSwitching:new de(!1),autoVideoTrackLimits:new de({}),isLooped:new de(!1),playbackRate:new de(1),externalTextTracks:new de([]),currentTextTrack:new de(void 0),textTrackCuesSettings:new de({}),cameraRotation:new de(!1)},this.info={playbackState$:new b(m.STOPPED),position$:new b(0),duration$:new b(1/0),muted$:new b(!1),volume$:new b(1),availableQualities$:new b([]),availableQualitiesFps$:new b({}),availableAudioTracks$:new b([]),isAudioAvailable$:new b(!0),currentQuality$:new b(void 0),isAutoQualityEnabled$:new b(!0),autoQualityLimitingAvailable$:new b(!1),autoQualityLimits$:new b({}),currentPlaybackRate$:new b(1),currentBuffer$:new b({start:0,end:0}),isBuffering$:new b(!0),isStalled$:new b(!1),isEnded$:new b(!1),isLooped$:new b(!1),isLive$:new b(void 0),liveTime$:new b(void 0),currentFormat$:new b(void 0),availableTextTracks$:new b([]),currentTextTrack$:new b(void 0),throughputEstimation$:new b(void 0),rttEstimation$:new b(void 0),videoBitrate$:new b(void 0),hostname$:new b(void 0),httpConnectionType$:new b(void 0),httpConnectionReused$:new b(void 0),chromecastState$:new b(Ee.NOT_AVAILABLE),chromecastDeviceName$:new b(void 0),intrinsicVideoSize$:new b(void 0),is3DVideo$:new b(!1)},this.events={inited$:new C,started$:new C,willPause$:new C,willResume$:new C,willDestruct$:new C,watchCoverageRecord$:new C,watchCoverageLive$:new C,managedError$:new C,fatalError$:new C,ended$:new C,looped$:new C,seeked$:new C,willSeek$:new C,firstBytes$:new C,firstFrame$:new C,canplay$:new C,log$:new C},this.experimental={element$:new b(void 0),enableDebugTelemetry$:new b(!1),dumpTelemetry:qf},this.initLogs(),this.tuning=Av(e),this.chromecastInitializer=new Wo({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new hi(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,p)=>{const v=typeof p;return["number","string","boolean"].includes(v)?p:p===null?null:`<${v}>`})),d=`Player.${String(i)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:x.WTF,message:l,thrown:o}),o}}}})}initVideo(e){var t,i,r;return this.config=e,this.domContainer=_v(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Sv({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},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(),(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=this.desiredState.playbackState;return e.getState()!==m.PLAYING&&e.startTransitionTo(m.PLAYING),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){return this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:V.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()===Ee.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()===Ee.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();t.length||(this.explicitInitialQuality=e);const i=t.find(r=>r.quality===e);return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.setState(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=>({type:"external",...t}))),this}selectTextTrack(e){var t;return(e===void 0||!((t=this.providerContainer)===null||t===void 0)&&t.providerOutput.availableTextTracks$.getValue().find(i=>i.id===e))&&this.desiredState.currentTextTrack.startTransitionTo(e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraRotation(e,t){return this.desiredState.cameraRotation.setState({x:e,y:t,z:0}),this}stopCameraRotation(){return this.desiredState.cameraRotation.setState(!1),this}getExactTime(){R(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(J(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===V.None?void 0:t.position;return w(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}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(L(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe($(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(q(({from:e})=>e===m.STOPPED),ge()).subscribe(()=>{this.initedAt=he(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.pipe(q(()=>!this.isPlaybackStarted),q(e=>e.to===m.PLAYING)).subscribe(()=>{this.isPlaybackStarted=!0,this.events.started$.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();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const u=this.desiredState.seekState.getState();u.state===V.Requested?this.desiredState.seekState.setState({...u,state:V.Applying}):this.events.managedError$.next({id:`WillSeekIn${u.state}`,category:x.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===V.Applying&&(this.desiredState.seekState.setState({state:V.None}),this.events.seeked$.next())})).add(e.current$.pipe($(u=>u.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe($(u=>u.destination),pe()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe($(u=>u.map(({quality:d})=>d).sort((d,l)=>Xi(d)?1:Xi(l)?-1:zi(l,d)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(u=>{const d={};for(const l of u)l.fps&&(d[l.quality]=l.fps);this.info.availableQualitiesFps$.next(d)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(u=>{this.info.currentQuality$.next(u==null?void 0:u.quality),this.info.videoBitrate$.next(u==null?void 0:u.bitrate)})).add(e.providerOutput.hostname$.pipe(pe()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(pe()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(pe()).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.currentBuffer$.pipe($(u=>u?{start:u.from,end:u.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.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe($(u=>u.muted),pe()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe($(u=>u.volume),pe()).subscribe(this.info.volume$)).add(wv({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(L(e.providerOutput.endedEvent$.pipe(wt(!0)),e.providerOutput.seekedEvent$.pipe(wt(!1))).pipe(pe()).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($(u=>({id:"NoProviders",category:x.VIDEO_PIPELINE,message:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(ge(),$(()=>he()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(ge(),$(()=>he()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ge(),$(()=>he()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const t=new b(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new b(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(q(({to:u})=>u===m.PLAYING),ge()).subscribe(()=>i.next(!1)));let r=0;const a=L(e.providerOutput.isBuffering$,t,i).pipe($(()=>{const u=e.providerOutput.isBuffering$.getValue(),d=t.getValue()||i.getValue();return u&&!d}),pe());this.subscription.add(a.subscribe(u=>{u?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))}));const n=new ie;this.subscription.add(n);const o=L(N(window,"beforeunload"),this.events.willDestruct$,e.current$.pipe(q(u=>Boolean(u==null?void 0:u.provider))));e.providerOutput.isLive$.pipe(pe()).subscribe(u=>{switch(R(this.providerContainer),n.unsubscribe(),u){case!0:{const d=new b(void 0);n.add(this.providerContainer.providerOutput.liveTime$.subscribe(l=>d.next(l&&Math.floor(l/1e3)))),n.add(mn({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:o,looped$:this.events.looped$,position$:d}).pipe($(({from:l,to:c})=>({start:l,end:c}))).subscribe(this.events.watchCoverageLive$));break}case!1:n.add(mn({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:o,position$:this.providerContainer.providerOutput.position$}).pipe($(({from:d,to:l})=>({start:d,end:l}))).subscribe(this.events.watchCoverageRecord$));break}}),this.subscription.add(L(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:u==null?void 0:u.videoWidth,height:u==null?void 0:u.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(u=>{var d,l;const c=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(d=u==null?void 0:u.size)===null||d===void 0?void 0:d.width,height:(l=u==null?void 0:u.size)===null||l===void 0?void 0:l.height},{width:c==null?void 0:c.videoWidth,height:c==null?void 0:c.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(u=>{this.info.is3DVideo$.next(u)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe($(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new ie;this.subscription.add(t),this.subscription.add(e.current$.pipe(pe((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(q(i=>i.length>0),ge()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:i})=>i===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=yi(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})),this.desiredState.videoTrack.startTransitionTo(t.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(L(this.desiredState.videoTrack.stateChangeStarted$.pipe($(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe($(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe($(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe($(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe($(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe($(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe($(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe($(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe($(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;R(this.providerContainer),R(t),Yf(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Gf(i)),this.providerContainer.current$.subscribe(({type:i})=>Li("provider",i)),t.duration$.subscribe(i=>Li("duration",i)),t.availableVideoTracks$.pipe(q(i=>!!i.length),ge()).subscribe(i=>Li("tracks",i)),this.events.fatalError$.subscribe(new Ye("fatalError")),this.events.managedError$.subscribe(new Ye("managedError")),t.position$.subscribe(new Ye("position")),t.currentVideoTrack$.pipe($(i=>i==null?void 0:i.quality)).subscribe(new Ye("quality")),this.info.currentBuffer$.subscribe(new Ye("buffer")),t.isBuffering$.subscribe(new Ye("isBuffering"))].forEach(i=>this.subscription.add(i)),Li("codecs",uv())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>this.events.managedError$.next({id:"WakeLock",category:x.DOM,message:String(r)}))};this.subscription.add(L(N(document,"visibilitychange"),N(document,"fullscreenchange"),this.desiredState.playbackState.transitionEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===m.PLAYING,n=Boolean(e)&&!(e!=null&&e.released);r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}}const Cv=`${zo}@${qo}`;export{Ee as ChromecastState,fi as HttpConnectionType,Bv as Observable,m as PlaybackState,xv as Player,Cv as SDK_VERSION,Mv as Subject,Nv as Subscription,Uv as ValueSubject,y as VideoFormat,ae as VideoQuality};
|