@vkontakte/videoplayer-core 2.0.87 → 2.0.88
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 +6 -6
- package/es2015.esm.js +6 -6
- package/es2018.cjs.js +6 -6
- package/es2018.esm.js +6 -6
- package/esnext.cjs.js +6 -6
- package/esnext.esm.js +6 -6
- package/evergreen.esm.js +6 -6
- package/index.d.ts +8 -25
- package/package.json +2 -2
package/es2018.esm.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
* Mon,
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.88
|
|
3
|
+
* Mon, 03 Jul 2023 18:19:16 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-88/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{ValueSubject as T,Subject as x,Subscription as ae,isNonNullable as k,ErrorCategory as D,isNullable as ee,fromEvent as M,assertNever as U,merge as V,tap as jr,map as _,observableFrom as Re,filterChanged as me,assertNonNullable as R,debounce as Le,timeout as Go,combine as Qe,once as be,mapTo as Ht,filter as te,now as he,Observable as ts,abortable as Fe,getExponentialDelay as Wr,interval as zo,safeStorage as bs,Logger as jo,ACTIVE_LIVE_VALID_DELAY as Wo}from"@vkontakte/videoplayer-shared/es2018.esm.js";import{Observable as Tv,Subject as Ev,Subscription as $v,ValueSubject as Av}from"@vkontakte/videoplayer-shared/es2018.esm.js";import Qo from"lodash/debounce.js";const Jo="2.0.87";var p;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(p||(p={}));var y;(function(s){s.MPEG="MPEG",s.DASH="DASH",s.DASH_SEP="DASH_SEP",s.DASH_SEP_VK="DASH_SEP",s.DASH_WEBM="DASH_WEBM",s.DASH_WEBM_AV1="DASH_WEBM_AV1",s.DASH_WEBM_VK="DASH_WEBM",s.DASH_ONDEMAND="DASH_ONDEMAND",s.DASH_ONDEMAND_VK="DASH_ONDEMAND",s.DASH_LIVE="DASH_LIVE",s.DASH_LIVE_CMAF="DASH_LIVE_CMAF",s.DASH_LIVE_WEBM="DASH_LIVE_WEBM",s.HLS="HLS",s.HLS_ONDEMAND="HLS_ONDEMAND",s.HLS_JS="HLS",s.HLS_LIVE="HLS_LIVE",s.HLS_LIVE_CMAF="HLS_LIVE_CMAF",s.WEB_RTC_LIVE="WEB_RTC_LIVE"})(y||(y={}));var $e;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})($e||($e={}));var Te;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})(Te||(Te={}));var ci;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(ci||(ci={}));var z;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(z||(z={}));var mt;(function(s){s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip"})(mt||(mt={}));var Ko=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 Xo{constructor(e){var t;this.connection$=new T(void 0),this.castState$=new T(Te.NOT_AVAILABLE),this.errorEvent$=new x,this.realCastState$=new T(Te.NOT_AVAILABLE),this.subscription=new ae,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=k((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||Ko("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:D.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(){k(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();ee(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();ee(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 U(r.sessionState)}})).add(V(M(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(jr(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),_(r=>r.castState)),Re([i.getCastState()])).pipe(me(),_(Zo),jr(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===Te.CONNECTED,o=k(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;(ee(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===Te.CONNECTED?k(this.connection$.getValue())?Te.CONNECTED:Te.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:D.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const Zo=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return Te.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return Te.AVAILABLE;case cast.framework.CastState.CONNECTING:return Te.CONNECTING;case cast.framework.CastState.CONNECTED:return Te.CONNECTED;default:return U(s)}};var Qr=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},at=function(s){try{return!!s()}catch(e){return!0}},ed=at,is=!ed(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),bn=is,yn=Function.prototype,nr=yn.call,td=bn&&yn.bind.bind(nr,nr),nt=bn?td:function(s){return function(){return nr.apply(s,arguments)}},Tn=nt,id=Tn({}.toString),sd=Tn("".slice),ss=function(s){return sd(id(s),8,-1)},rd=nt,ad=at,nd=ss,ys=Object,od=rd("".split),dd=ad(function(){return!ys("z").propertyIsEnumerable(0)})?function(s){return nd(s)=="String"?od(s,""):ys(s)}:ys,rs=function(s){return s==null},ud=rs,ld=TypeError,br=function(s){if(ud(s))throw ld("Can't call method on "+s);return s},cd=dd,hd=br,fi=function(s){return cd(hd(s))},fd=function(){},jt={},$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")(),or=typeof document=="object"&&document.all,pd=typeof or=="undefined"&&or!==void 0,En={all:or,IS_HTMLDDA:pd},$n=En,md=$n.all,Ce=$n.IS_HTMLDDA?function(s){return typeof s=="function"||s===md}:function(s){return typeof s=="function"},vd=Je,Sd=Ce,Jr=vd.WeakMap,gd=Sd(Jr)&&/native code/.test(String(Jr)),Kr=Ce,An=En,bd=An.all,kt=An.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:Kr(s)||s===bd}:function(s){return typeof s=="object"?s!==null:Kr(s)},yd=at,St=!yd(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Wt={},Td=Je,Xr=kt,dr=Td.document,Ed=Xr(dr)&&Xr(dr.createElement),wn=function(s){return Ed?dr.createElement(s):{}},$d=St,Ad=at,wd=wn,_n=!$d&&!Ad(function(){return Object.defineProperty(wd("div"),"a",{get:function(){return 7}}).a!=7}),_d=St,kd=at,kn=_d&&kd(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Pd=kt,Rd=String,Id=TypeError,Pt=function(s){if(Pd(s))return s;throw Id(Rd(s)+" is not an object")},Dd=is,Ai=Function.prototype.call,ot=Dd?Ai.bind(Ai):function(){return Ai.apply(Ai,arguments)},yr={},Ts=yr,Es=Je,Ld=Ce,Zr=function(s){return Ld(s)?s:void 0},Tr=function(s,e){return arguments.length<2?Zr(Ts[s])||Zr(Es[s]):Ts[s]&&Ts[s][e]||Es[s]&&Es[s][e]},Cd=nt,Er=Cd({}.isPrototypeOf),xd=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Pn=Je,$s=xd,ea=Pn.process,ta=Pn.Deno,ia=ea&&ea.versions||ta&&ta.version,sa=ia&&ia.v8,Me,Gi;sa&&(Me=sa.split("."),Gi=Me[0]>0&&Me[0]<4?1:+(Me[0]+Me[1]));!Gi&&$s&&(Me=$s.match(/Edge\/(\d+)/),(!Me||Me[1]>=74)&&(Me=$s.match(/Chrome\/(\d+)/),Me&&(Gi=+Me[1])));var Od=Gi,ra=Od,Nd=at,Rn=!!Object.getOwnPropertySymbols&&!Nd(function(){var s=Symbol();return!String(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&ra&&ra<41}),Bd=Rn,In=Bd&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Md=Tr,Fd=Ce,Ud=Er,Vd=In,Hd=Object,Dn=Vd?function(s){return typeof s=="symbol"}:function(s){var e=Md("Symbol");return Fd(e)&&Ud(e.prototype,Hd(s))},Yd=String,$r=function(s){try{return Yd(s)}catch(e){return"Object"}},qd=Ce,Gd=$r,zd=TypeError,Ar=function(s){if(qd(s))return s;throw zd(Gd(s)+" is not a function")},jd=Ar,Wd=rs,as=function(s,e){var t=s[e];return Wd(t)?void 0:jd(t)},As=ot,ws=Ce,_s=kt,Qd=TypeError,Jd=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")},zi={},Kd={get exports(){return zi},set exports(s){zi=s}},Xd=!0,aa=Je,Zd=Object.defineProperty,eu=function(s,e){try{Zd(aa,s,{value:e,configurable:!0,writable:!0})}catch(t){aa[s]=e}return e},tu=Je,iu=eu,na="__core-js_shared__",su=tu[na]||iu(na,{}),Ln=su,oa=Ln;(Kd.exports=function(s,e){return oa[s]||(oa[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 ru=br,au=Object,ns=function(s){return au(ru(s))},nu=nt,ou=ns,du=nu({}.hasOwnProperty),dt=Object.hasOwn||function(e,t){return du(ou(e),t)},uu=nt,lu=0,cu=Math.random(),hu=uu(1 .toString),Cn=function(s){return"Symbol("+(s===void 0?"":s)+")_"+hu(++lu+cu,36)},fu=Je,pu=zi,da=dt,mu=Cn,vu=Rn,Su=In,Ft=fu.Symbol,ks=pu("wks"),gu=Su?Ft.for||Ft:Ft&&Ft.withoutSetter||mu,He=function(s){return da(ks,s)||(ks[s]=vu&&da(Ft,s)?Ft[s]:gu("Symbol."+s)),ks[s]},bu=ot,ua=kt,la=Dn,yu=as,Tu=Jd,Eu=He,$u=TypeError,Au=Eu("toPrimitive"),wu=function(s,e){if(!ua(s)||la(s))return s;var t=yu(s,Au),i;if(t){if(e===void 0&&(e="default"),i=bu(t,s,e),!ua(i)||la(i))return i;throw $u("Can't convert object to primitive value")}return e===void 0&&(e="number"),Tu(s,e)},_u=wu,ku=Dn,wr=function(s){var e=_u(s,"string");return ku(e)?e:e+""},Pu=St,Ru=_n,Iu=kn,wi=Pt,ca=wr,Du=TypeError,Ps=Object.defineProperty,Lu=Object.getOwnPropertyDescriptor,Rs="enumerable",Is="configurable",Ds="writable";Wt.f=Pu?Iu?function(e,t,i){if(wi(e),t=ca(t),wi(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Ds in i&&!i[Ds]){var r=Lu(e,t);r&&r[Ds]&&(e[t]=i.value,i={configurable:Is in i?i[Is]:r[Is],enumerable:Rs in i?i[Rs]:r[Rs],writable:!1})}return Ps(e,t,i)}:Ps:function(e,t,i){if(wi(e),t=ca(t),wi(i),Ru)try{return Ps(e,t,i)}catch(r){}if("get"in i||"set"in i)throw Du("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var os=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},Cu=St,xu=Wt,Ou=os,pi=Cu?function(s,e,t){return xu.f(s,e,Ou(1,t))}:function(s,e,t){return s[e]=t,s},Nu=zi,Bu=Cn,ha=Nu("keys"),_r=function(s){return ha[s]||(ha[s]=Bu(s))},kr={},Mu=gd,xn=Je,Fu=kt,Uu=pi,Ls=dt,Cs=Ln,Vu=_r,Hu=kr,fa="Object already initialized",ur=xn.TypeError,Yu=xn.WeakMap,ji,hi,Wi,qu=function(s){return Wi(s)?hi(s):ji(s,{})},Gu=function(s){return function(e){var t;if(!Fu(e)||(t=hi(e)).type!==s)throw ur("Incompatible receiver, "+s+" required");return t}};if(Mu||Cs.state){var Ge=Cs.state||(Cs.state=new Yu);Ge.get=Ge.get,Ge.has=Ge.has,Ge.set=Ge.set,ji=function(s,e){if(Ge.has(s))throw ur(fa);return e.facade=s,Ge.set(s,e),e},hi=function(s){return Ge.get(s)||{}},Wi=function(s){return Ge.has(s)}}else{var xt=Vu("state");Hu[xt]=!0,ji=function(s,e){if(Ls(s,xt))throw ur(fa);return e.facade=s,Uu(s,xt,e),e},hi=function(s){return Ls(s,xt)?s[xt]:{}},Wi=function(s){return Ls(s,xt)}}var zu={set:ji,get:hi,has:Wi,enforce:qu,getterFor:Gu},ju=is,On=Function.prototype,pa=On.apply,ma=On.call,Wu=typeof Reflect=="object"&&Reflect.apply||(ju?ma.bind(pa):function(){return ma.apply(pa,arguments)}),Qu=ss,Ju=nt,Nn=function(s){if(Qu(s)==="Function")return Ju(s)},Bn={},Mn={},Fn={}.propertyIsEnumerable,Un=Object.getOwnPropertyDescriptor,Ku=Un&&!Fn.call({1:2},1);Mn.f=Ku?function(e){var t=Un(this,e);return!!t&&t.enumerable}:Fn;var Xu=St,Zu=ot,el=Mn,tl=os,il=fi,sl=wr,rl=dt,al=_n,va=Object.getOwnPropertyDescriptor;Bn.f=Xu?va:function(e,t){if(e=il(e),t=sl(t),al)try{return va(e,t)}catch(i){}if(rl(e,t))return tl(!Zu(el.f,e,t),e[t])};var nl=at,ol=Ce,dl=/#|\.prototype\./,mi=function(s,e){var t=ll[ul(s)];return t==hl?!0:t==cl?!1:ol(e)?nl(e):!!e},ul=mi.normalize=function(s){return String(s).replace(dl,".").toLowerCase()},ll=mi.data={},cl=mi.NATIVE="N",hl=mi.POLYFILL="P",fl=mi,Sa=Nn,pl=Ar,ml=is,vl=Sa(Sa.bind),Vn=function(s,e){return pl(s),e===void 0?s:ml?vl(s,e):function(){return s.apply(e,arguments)}},_i=Je,Sl=Wu,gl=Nn,bl=Ce,yl=Bn.f,Tl=fl,Ot=yr,El=Vn,Nt=pi,ga=dt,$l=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 Sl(s,this,arguments)};return e.prototype=s.prototype,e},ds=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?Ot:Ot[t]||Nt(Ot,t,{})[t],u=o.prototype,d,l,c,h,f,v,b,g,m;for(h in e)d=Tl(i?h:t+(r?".":"#")+h,s.forced),l=!d&&n&&ga(n,h),v=o[h],l&&(s.dontCallGetSet?(m=yl(n,h),b=m&&m.value):b=n[h]),f=l&&b?b:e[h],!(l&&typeof v==typeof f)&&(s.bind&&l?g=El(f,_i):s.wrap&&l?g=$l(f):a&&bl(f)?g=gl(f):g=f,(s.sham||f&&f.sham||v&&v.sham)&&Nt(g,"sham",!0),Nt(o,h,g),a&&(c=t+"Prototype",ga(Ot,c)||Nt(Ot,c,{}),Nt(Ot[c],h,f),s.real&&u&&(d||!u[h])&&Nt(u,h,f)))},lr=St,Al=dt,Hn=Function.prototype,wl=lr&&Object.getOwnPropertyDescriptor,Pr=Al(Hn,"name"),_l=Pr&&function(){}.name==="something",kl=Pr&&(!lr||lr&&wl(Hn,"name").configurable),Pl={EXISTS:Pr,PROPER:_l,CONFIGURABLE:kl},Yn={},Rl=Math.ceil,Il=Math.floor,Dl=Math.trunc||function(e){var t=+e;return(t>0?Il:Rl)(t)},Ll=Dl,Rr=function(s){var e=+s;return e!==e||e===0?0:Ll(e)},Cl=Rr,xl=Math.max,Ol=Math.min,Nl=function(s,e){var t=Cl(s);return t<0?xl(t+e,0):Ol(t,e)},Bl=Rr,Ml=Math.min,Fl=function(s){return s>0?Ml(Bl(s),9007199254740991):0},Ul=Fl,Ir=function(s){return Ul(s.length)},Vl=fi,Hl=Nl,Yl=Ir,ba=function(s){return function(e,t,i){var r=Vl(e),a=Yl(r),n=Hl(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}},ql={includes:ba(!0),indexOf:ba(!1)},Gl=nt,xs=dt,zl=fi,jl=ql.indexOf,Wl=kr,ya=Gl([].push),Ql=function(s,e){var t=zl(s),i=0,r=[],a;for(a in t)!xs(Wl,a)&&xs(t,a)&&ya(r,a);for(;e.length>i;)xs(t,a=e[i++])&&(~jl(r,a)||ya(r,a));return r},qn=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Jl=Ql,Kl=qn,Xl=Object.keys||function(e){return Jl(e,Kl)},Zl=St,ec=kn,tc=Wt,ic=Pt,sc=fi,rc=Xl;Yn.f=Zl&&!ec?Object.defineProperties:function(e,t){ic(e);for(var i=sc(t),r=rc(t),a=r.length,n=0,o;a>n;)tc.f(e,o=r[n++],i[o]);return e};var ac=Tr,nc=ac("document","documentElement"),oc=Pt,dc=Yn,Ta=qn,uc=kr,lc=nc,cc=wn,hc=_r,Ea=">",$a="<",cr="prototype",hr="script",Gn=hc("IE_PROTO"),Os=function(){},zn=function(s){return $a+hr+Ea+s+$a+"/"+hr+Ea},Aa=function(s){s.write(zn("")),s.close();var e=s.parentWindow.Object;return s=null,e},fc=function(){var s=cc("iframe"),e="java"+hr+":",t;return s.style.display="none",lc.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(zn("document.F=Object")),t.close(),t.F},ki,Ui=function(){try{ki=new ActiveXObject("htmlfile")}catch(e){}Ui=typeof document!="undefined"?document.domain&&ki?Aa(ki):fc():Aa(ki);for(var s=Ta.length;s--;)delete Ui[cr][Ta[s]];return Ui()};uc[Gn]=!0;var jn=Object.create||function(e,t){var i;return e!==null?(Os[cr]=oc(e),i=new Os,Os[cr]=null,i[Gn]=e):i=Ui(),t===void 0?i:dc.f(i,t)},pc=at,mc=!pc(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),vc=dt,Sc=Ce,gc=ns,bc=_r,yc=mc,wa=bc("IE_PROTO"),fr=Object,Tc=fr.prototype,Wn=yc?fr.getPrototypeOf:function(s){var e=gc(s);if(vc(e,wa))return e[wa];var t=e.constructor;return Sc(t)&&e instanceof t?t.prototype:e instanceof fr?Tc:null},Ec=pi,Qn=function(s,e,t,i){return i&&i.enumerable?s[e]=t:Ec(s,e,t),s},$c=at,Ac=Ce,wc=kt,_c=jn,_a=Wn,kc=Qn,Pc=He,pr=Pc("iterator"),Jn=!1,st,Ns,Bs;[].keys&&(Bs=[].keys(),"next"in Bs?(Ns=_a(_a(Bs)),Ns!==Object.prototype&&(st=Ns)):Jn=!0);var Rc=!wc(st)||$c(function(){var s={};return st[pr].call(s)!==s});Rc?st={}:st=_c(st);Ac(st[pr])||kc(st,pr,function(){return this});var Kn={IteratorPrototype:st,BUGGY_SAFARI_ITERATORS:Jn},Ic=He,Dc=Ic("toStringTag"),Xn={};Xn[Dc]="z";var Dr=String(Xn)==="[object z]",Lc=Dr,Cc=Ce,Vi=ss,xc=He,Oc=xc("toStringTag"),Nc=Object,Bc=Vi(function(){return arguments}())=="Arguments",Mc=function(s,e){try{return s[e]}catch(t){}},us=Lc?Vi:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=Mc(e=Nc(s),Oc))=="string"?t:Bc?Vi(e):(i=Vi(e))=="Object"&&Cc(e.callee)?"Arguments":i},Fc=Dr,Uc=us,Vc=Fc?{}.toString:function(){return"[object "+Uc(this)+"]"},Hc=Dr,Yc=Wt.f,qc=pi,Gc=dt,zc=Vc,jc=He,ka=jc("toStringTag"),Zn=function(s,e,t,i){if(s){var r=t?s:s.prototype;Gc(r,ka)||Yc(r,ka,{configurable:!0,value:e}),i&&!Hc&&qc(r,"toString",zc)}},Wc=Kn.IteratorPrototype,Qc=jn,Jc=os,Kc=Zn,Xc=jt,Zc=function(){return this},eh=function(s,e,t,i){var r=e+" Iterator";return s.prototype=Qc(Wc,{next:Jc(+!i,t)}),Kc(s,r,!1,!0),Xc[r]=Zc,s},th=ds,ih=ot,eo=Pl,sh=eh,rh=Wn,ah=Zn,Pa=Qn,nh=He,Ra=jt,to=Kn,oh=eo.PROPER;eo.CONFIGURABLE;to.IteratorPrototype;var Pi=to.BUGGY_SAFARI_ITERATORS,Ms=nh("iterator"),Ia="keys",Ri="values",Da="entries",dh=function(){return this},uh=function(s,e,t,i,r,a,n){sh(t,e,i);var o=function(m){if(m===r&&h)return h;if(!Pi&&m in l)return l[m];switch(m){case Ia:return function(){return new t(this,m)};case Ri:return function(){return new t(this,m)};case Da:return function(){return new t(this,m)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,l=s.prototype,c=l[Ms]||l["@@iterator"]||r&&l[r],h=!Pi&&c||o(r),f=e=="Array"&&l.entries||c,v,b,g;if(f&&(v=rh(f.call(new s)),v!==Object.prototype&&v.next&&(ah(v,u,!0,!0),Ra[u]=dh)),oh&&r==Ri&&c&&c.name!==Ri&&(d=!0,h=function(){return ih(c,this)}),r)if(b={values:o(Ri),keys:a?h:o(Ia),entries:o(Da)},n)for(g in b)(Pi||d||!(g in l))&&Pa(l,g,b[g]);else th({target:e,proto:!0,forced:Pi||d},b);return n&&l[Ms]!==h&&Pa(l,Ms,h,{name:r}),Ra[e]=h,b},lh=function(s,e){return{value:s,done:e}},ch=fi,Lr=fd,La=jt,io=zu,hh=Wt.f,fh=uh,Ii=lh,ph=Xd,mh=St,so="Array Iterator",vh=io.set,Sh=io.getterFor(so);fh(Array,"Array",function(s,e){vh(this,{type:so,target:ch(s),index:0,kind:e})},function(){var s=Sh(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,Ii(void 0,!0)):t=="keys"?Ii(i,!1):t=="values"?Ii(e[i],!1):Ii([i,e[i]],!1)},"values");var Ca=La.Arguments=La.Array;Lr();Lr();Lr();if(!ph&&mh&&Ca.name!=="values")try{hh(Ca,"name",{value:"values"})}catch(s){}var gh=He,bh=jt,yh=gh("iterator"),Th=Array.prototype,Eh=function(s){return s!==void 0&&(bh.Array===s||Th[yh]===s)},$h=us,xa=as,Ah=rs,wh=jt,_h=He,kh=_h("iterator"),ro=function(s){if(!Ah(s))return xa(s,kh)||xa(s,"@@iterator")||wh[$h(s)]},Ph=ot,Rh=Ar,Ih=Pt,Dh=$r,Lh=ro,Ch=TypeError,xh=function(s,e){var t=arguments.length<2?Lh(s):e;if(Rh(t))return Ih(Ph(t,s));throw Ch(Dh(s)+" is not iterable")},Oh=ot,Oa=Pt,Nh=as,Bh=function(s,e,t){var i,r;Oa(s);try{if(i=Nh(s,"return"),!i){if(e==="throw")throw t;return t}i=Oh(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return Oa(i),t},Mh=Vn,Fh=ot,Uh=Pt,Vh=$r,Hh=Eh,Yh=Ir,Na=Er,qh=xh,Gh=ro,Ba=Bh,zh=TypeError,Hi=function(s,e){this.stopped=s,this.result=e},Ma=Hi.prototype,jh=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=Mh(e,i),d,l,c,h,f,v,b,g=function(S){return d&&Ba(d,"normal",S),new Hi(!0,S)},m=function(S){return r?(Uh(S),o?u(S[0],S[1],g):u(S[0],S[1])):o?u(S,g):u(S)};if(a)d=s.iterator;else if(n)d=s;else{if(l=Gh(s),!l)throw zh(Vh(s)+" is not iterable");if(Hh(l)){for(c=0,h=Yh(s);h>c;c++)if(f=m(s[c]),f&&Na(Ma,f))return f;return new Hi(!1)}d=qh(s,l)}for(v=a?s.next:d.next;!(b=Fh(v,d)).done;){try{f=m(b.value)}catch(S){Ba(d,"throw",S)}if(typeof f=="object"&&f&&Na(Ma,f))return f}return new Hi(!1)},Wh=wr,Qh=Wt,Jh=os,Kh=function(s,e,t){var i=Wh(e);i in s?Qh.f(s,i,Jh(0,t)):s[i]=t},Xh=ds,Zh=jh,ef=Kh;Xh({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Zh(e,function(i,r){ef(t,i,r)},{AS_ENTRIES:!0}),t}});var tf=yr,sf=tf.Object.fromEntries,rf={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},af=rf,nf=Je,of=us,df=pi,Fa=jt,uf=He,Ua=uf("toStringTag");for(var Fs in af){var Va=nf[Fs],Us=Va&&Va.prototype;Us&&of(Us)!==Ua&&df(Us,Ua,Fs),Fa[Fs]=Fa.Array}var lf=sf,cf=lf,hf=cf,ff=hf,vi=ff,Vt;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(Vt||(Vt={}));var Yt=(s,e=0,t=Vt.OFFSET_P)=>{switch(t){case Vt.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Vt.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}default:U(t)}return s},I=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)},re;(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"})(re||(re={}));const Ve={[re.Q_144P]:{width:256,height:144},[re.Q_240P]:{width:428,height:240},[re.Q_360P]:{width:640,height:360},[re.Q_480P]:{width:856,height:480},[re.Q_720P]:{width:1280,height:720},[re.Q_1080P]:{width:1920,height:1080},[re.Q_1440P]:{width:2560,height:1440},[re.Q_2160P]:{width:3840,height:2160},[re.Q_4320P]:{width:7680,height:4320}},Yi=(s,e)=>Ve[s].height>Ve[e].height,pf=(s,e)=>Ve[s].height>=Ve[e].height,di=(s,e)=>Ve[s].height<Ve[e].height,mf=(s,e)=>Ve[s].height<=Ve[e].height,vf=s=>s.sort((e,t)=>e===t?0:e===re.INVARIANT?1:t===re.INVARIANT?-1:di(e,t)?1:-1)[0],Sf=Object.keys(Ve).sort((s,e)=>di(s,e)?-1:1),Rt=({width:s,height:e})=>{const t=Math.min(s,e),i=Math.max(s,e);return Sf.find(r=>{const a=Ve[r];return a.width>=i&&a.height>=t})},gf=s=>Ve[s].height,Qi=s=>s===re.INVARIANT;class ue{constructor(e){this.transitionStarted$=new x,this.transitionEnded$=new x,this.transitionUpdated$=new x,this.forceChanged$=new x,this.stateChangeStarted$=V(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=V(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||k(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 bf=s=>{switch(s){case y.MPEG:case y.DASH:case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.HLS:case y.HLS_ONDEMAND:return!1;case y.DASH_LIVE:case y.DASH_LIVE_CMAF:case y.HLS_LIVE:case y.HLS_LIVE_CMAF:case y.DASH_LIVE_WEBM:case y.WEB_RTC_LIVE:return!0;default:return U(s)}};var Y;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Y||(Y={}));const yf=5,Tf=5,Ef=500,Ha=7e3;class $f{constructor(e){this.subscription=new ae,this.loadMediaTimeoutSubscription=new ae,this.videoState=new ue(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===p.STOPPED){i!==Y.STOPPED&&(this.videoState.startTransitionTo(Y.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==p.PAUSED&&o.state===z.Requested&&i!==Y.STOPPED){this.seek(o.position/1e3);return}switch(a){case p.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:U(i)}break}case p.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:U(i)}break}case p.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:U(i)}break}default:U(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(bf(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new ae;this.subscription.add(e),this.subscription.add(V(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 x;e.add(r.pipe(Le(Ef)).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===z.Applying||Math.abs(o-a)>yf)&&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<Tf&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),I(this.params.desiredState.playbackState,p.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:U(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=V(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Re(["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),I(this.params.desiredState.playbackState,p.PAUSED)):(this.videoState.setState(Y.PLAYING),I(this.params.desiredState.playbackState,p.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:z.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===Y.PAUSED||e===Y.PLAYING)&&(this.videoState.setState(Y.PAUSED),I(this.params.desiredState.playbackState,p.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),I(this.params.desiredState.playbackState,p.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)===p.READY&&I(this.params.desiredState.playbackState,p.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=vf(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:case y.DASH_WEBM_AV1:{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=Yt(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:D.VIDEO_PIPELINE,message:l,thrown:c}),c}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return U(e)}const o=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,a);o.contentUrl=r,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return k(u)&&(o.metadata.title=u),k(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===z.Applying||i.state===z.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(Go(Ha).subscribe(()=>a(`timeout(${Ha})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===z.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{const a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:D.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}class Ya{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 ao extends Ya{constructor(){super(),this.listeners||Ya.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 no=class{constructor(){Object.defineProperty(this,"signal",{value:new ao,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&&(no.prototype[Symbol.toStringTag]="AbortController",ao.prototype[Symbol.toStringTag]="AbortSignal");function oo(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 Af(s){typeof s=="function"&&(s={fetch:s});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!oo({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(d,l){let c;l&&l.signal&&(c=l.signal,delete l.signal);const h=new t(d,l);return c&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),h},a.prototype=t.prototype);const n=e;return{fetch:(u,d)=>{const l=a&&a.prototype.isPrototypeOf(u)?u.signal:d?d.signal:void 0;if(l){let c;try{c=new DOMException("Aborted","AbortError")}catch(f){c=new Error("Aborted"),c.name="AbortError"}if(l.aborted)return Promise.reject(c);const h=new Promise((f,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 ls=oo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),uo=ls?Af({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,qt=ls?uo.fetch:window.fetch;ls?uo.Request:window.Request;const _t=ls?no:window.AbortController,ri=s=>s.range?s.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class ui{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]=ri(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(ri),r=i[0][0];let a=i[0][1];for(let h=1;h<i.length&&a<this.params.minDataSize;h++){const f=i[h][1];f-r<=2*this.params.minDataSize&&(a=Math.max(a,f))}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 f,v;throw(v=(f=this.params).onError)===null||v===void 0||v.call(f,{id:"BigRequestParsing",category:D.PARSER,message:"Error parsing response data",thrown:h}),h};return qt(o,{signal:d}).then(h=>{var f,v,b;if(l.response=h,!h.ok||!h.body){this.onBigRequestError(l);return}const[g,m]=h.body.tee();(v=(f=this.params).onDownloadStream)===null||v===void 0||v.call(f,m);const S=g.getReader(),E=parseInt((b=h.headers.get("Content-Length"))!==null&&b!==void 0?b:"",10)||a-r+1;l.data=new ArrayBuffer(E);const $=new Uint8Array(l.data),A=async({done:L,value:q})=>{L?this.onBigRequestProgress(l):q&&($.set(q,l.loaded),l.loaded+=q.byteLength,this.onBigRequestProgress(l),await(S==null?void 0:S.read().then(A,ui.suppressStreamErrors).catch(c)))};S==null||S.read().then(A,ui.suppressStreamErrors).catch(c)},ui.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,f,v;if(!this.activeRequests.has(e)||!a)return;const b=(o=this.dashJsRequestQueue.get(e))!==null&&o!==void 0?o:[];for(const g of b){const{request:m}=g,[S,E]=ri(m),$=S>=t&&E<=t+r,A=t>=S&&t+r<E,L=a.slice(S-t,Math.min(E-t+1,r));if(($||A)&&(m.requestStartDate=(u=m.requestStartDate)!==null&&u!==void 0?u:new Date,m.firstByteDate=(d=m.firstByteDate)!==null&&d!==void 0?d:new Date,m.bytesLoaded=L.byteLength,m.bytesTotal=i-t),$){m.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[]).filter(N=>N!==g)),(c=g.success)===null||c===void 0||c.call(g,L,"",e);const q=n?Array.from(n.headers.entries()).map(([N,F])=>`${N}: ${F}`).join(`\r
|
|
7
|
-
`):"";(h=this.dashMetrics)===null||h===void 0||h.addHttpRequest(m,e,(f=n==null?void 0:n.status)!==null&&f!==void 0?f:200,q,[])}else A&&((v=g.progress)===null||v===void 0||v.call(g,{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:D.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]=ri(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]=ri(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 Ji{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(Ji.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;Ji.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const wf=(s,e)=>t=>({create:i=>{const r=s(t).create(i);return new Ji(r,e,i)}}),_f=(s,e)=>{const t=new ui(e);return s.extend("SchemeLoaderFactory",function(){const{parent:i}=this,r=i.getLoader;return{getLoader:a=>{const n=r(a);return wf(n,t)}}},!0),()=>t.destroy()};var kf=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)},Pf=s=>{const e=new T(1/0),t=new x,i=new T(void 0),r=new T(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},u=l=>{var c,h,f,v,b;const g=vi(l.getAllResponseHeaders().trim().split(/[\n\r]+/).map(E=>E.split(": ")));if("x-playback-duration"in g||"x-playback-duration-millis"in g){const E=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=(f=$!=null?$:E*1e3)!==null&&f!==void 0?f:NaN;k(A)&&!isNaN(A)&&e.next(A)}const m=(v=g["x-delivery-type"])!==null&&v!==void 0?v:ci.HTTP1,S=(b={1:!0,0:!1}[g["x-reused"]])!==null&&b!==void 0?b:void 0;i.next(m),r.next(S)},d=l=>{l.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return s.extend("XHRLoader",function(){const{parent:l}=this,c=l.load.bind(l);return{load:function(h){if(h.request.type==="MPD"){const f=h.onload,v=h.progress;h.onload=function(...b){return u(this),f(...b)},h.progress=function(...b){return d(this),v(...b)},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()},Rf=s=>s.extend("RequestModifier",()=>({modifyRequestURL:Gt}),!0),If=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 Ue=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=s.getState(),o=e(),u=ee(r),d=new ae;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},It=(s,e,t)=>Ue(e,()=>s.loop,i=>{k(i)&&(s.loop=i)},{onError:t}),ut=(s,e,t,i)=>Ue(e,()=>({muted:s.muted,volume:s.volume}),r=>{k(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}),gt=(s,e,t,i)=>Ue(e,()=>s.playbackRate,r=>{k(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Df=s=>["__",s.language,s.label].join("|"),Lf=(s,e)=>{if(s.id===e)return!0;const[t,i,r]=e.split("|");return s.language===i&&s.label===r};class Ke{constructor(){this.available$=new x,this.current$=new T(void 0),this.error$=new x,this.subscription=new ae,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:D.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(Ue(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{k(a)&&this.setInternal(a)},{equal:(a,n)=>k(a)&&k(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(_(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Ue(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{k(a)&&this.setExternal(a)},{equal:(a,n)=>k(a)&&k(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(Ue(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(Ue(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(M(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();this.select(i)})),this.subscription.add(V(M(e,"addtrack"),M(e,"removetrack"),Re(["init"])).pipe(_(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),me((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(V(M(e,"change"),Re(["init"])).pipe(_(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),_(i=>i&&this.htmlTextTrackToITextTrack(i).id),me()).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 f=(d=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&d!==void 0?d:null;f&&f.length&&(this.applyCueSettings((c=(l=o.target)===null||l===void 0?void 0:l.cues)!==null&&c!==void 0?c:null),(h=o.target)===null||h===void 0||h.removeEventListener("cuechange",n))};(a=i.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(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;k(t.align)&&(r.align=t.align),k(t.position)&&(r.position=t.position),k(t.size)&&(r.size=t.size),k(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){R(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Ke.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,r=e.id!==""?e.id:Df(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,url:this.internalTracks.get(r).url}}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).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){e.filter(({id:t})=>!this.internalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.internalTracks).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))k(e)&&Lf(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),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){R(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const Cr=s=>{s.removeAttribute("src"),s.load()},Cf=s=>{try{s.pause(),s.playbackRate=0,Cr(s),s.remove()}catch(e){console.error(e)}};class xf{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}}const mr=window.WeakMap?new WeakMap:new xf,lt=s=>{let e=s.querySelector("video");const t=Boolean(e);return e?Cr(e):(e=document.createElement("video"),s.appendChild(e)),mr.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},ct=s=>{const e=mr.get(s);mr.delete(s),e?Cr(s):Cf(s)};class xr{constructor(){this.pausedTime=0,this.streamOffset=0,this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}}const lo=s=>{var e;let t=s;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},qa=s=>{const e=lo(s);return Boolean(e&&e.fullscreenElement&&e.fullscreenElement===s)},Of=s=>{const e=lo(s);return Boolean(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};var co=()=>{const{userAgent:s}=window.navigator;return!/chrome/i.test(s)&&/webkit|safari|khtml/i.test(s)};const vr=3;class Nf{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<vr&&(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||vr))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 ho=(s,e,t=vr)=>{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 Bf=1e3,Mf=s=>s.webkitAudioDecodedByteCount!==void 0?!!s.webkitAudioDecodedByteCount:s.mozHasAudio!==void 0?s.mozHasAudio:s.audioTracks?!!s.audioTracks.length:!0,ht=s=>{const e=E=>M(s,E).pipe(Ht(void 0)),i=V(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(E=>M(s,E))).pipe(_(E=>E.type==="ended"?s.readyState<2:s.readyState<3),me()),r=V(M(s,"progress"),M(s,"timeupdate")).pipe(_(()=>ho(s.buffered,s.currentTime))),a=co()?Qe({play:e("play").pipe(be()),playing:e("playing")}).pipe(Ht(void 0)):e("playing"),n=M(s,"playing").pipe(Le(Bf),_(()=>Mf(s))),o=M(s,"volumechange").pipe(_(()=>({muted:s.muted,volume:s.volume}))),u=M(s,"ratechange").pipe(_(()=>s.playbackRate)),d=M(s,"error").pipe(te(()=>Boolean(s.error||s.played.length)),_(()=>{var E;const $=s.error;return{id:$?`MediaError#${$.code}`:"HtmlVideoError",category:D.VIDEO_PIPELINE,message:$?$.message:"Error event from HTML video element",thrown:(E=s.error)!==null&&E!==void 0?E:void 0}})),l=M(s,"timeupdate").pipe(_(()=>s.currentTime)),c=new x,h=.3;let f;l.subscribe(E=>{s.loop&&k(f)&&k(E)&&f>=s.duration-h&&E<=h&&c.next(f),f=E});const v=M(s,"enterpictureinpicture"),b=M(s,"leavepictureinpicture"),g=new T(Of(s));v.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));const m=new T(qa(s));return M(s,"fullscreenchange").pipe(_(()=>qa(s))).subscribe(m),{playing$:a,pause$:e("pause").pipe(te(()=>!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,inPiP$:g,inFullscreen$:m}},Or=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var Ff=ds,Uf=ns,Vf=Ir,Hf=Rr;Ff({target:"Array",proto:!0},{at:function(e){var t=Uf(this),i=Vf(t),r=Hf(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});var Yf=Tr,fo=Yf,qf=fo,Gf=qf("Array","at"),zf=Gf,jf=zf,Wf=jf,Qf=Wf,Ze=Qf;let Nr=!1,tt={};const Jf=s=>{Nr=s},Kf=()=>{tt={}},Xf=s=>{s(tt)},Di=(s,e)=>{var t;Nr&&(tt.meta=(t=tt.meta)!==null&&t!==void 0?t:{},tt.meta[s]=e)};class je{constructor(e){this.name=e}next(e){var t,i;if(!Nr)return;tt.series=(t=tt.series)!==null&&t!==void 0?t:{};const r=(i=tt.series[this.name])!==null&&i!==void 0?i:[];r.push([Date.now(),e]),tt.series[this.name]=r}}const Zf=new je("best_bitrate"),ep=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class tp{constructor(){this.history={}}recordSelection(e){this.history[e.id]=he()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Si=(s,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:d})=>{var l,c,h,f;const v=i.usePixelRatio&&(l=window.devicePixelRatio)!==null&&l!==void 0?l:1,b=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*v*i.containerSizeFactor,height:e.height*v*i.containerSizeFactor},g=b&&Rt(b),m=i.considerPlaybackRate&&k(o)?o:1,S=s.filter(B=>!Qi(B.quality)).sort((B,O)=>Yi(B.quality,O.quality)?-1:1),E=(c=Ze(S,-1))===null||c===void 0?void 0:c.quality,$=(h=Ze(S,0))===null||h===void 0?void 0:h.quality,A=ee(r)||k(r.min)&&k(r.max)&&di(r.max,r.min)||k(r.min)&&$&&Yi(r.min,$)||k(r.max)&&E&&di(r.max,E),L=m*ep(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),N=S.filter(B=>{const O=g?di(B.quality,g):!0,X=k(t)&&isFinite(t)&&k(B.bitrate)?t-a>=B.bitrate*L:!0,de=i.lazyQualitySwitch&&k(i.minBufferToSwitchUp)&&u&&!Qi(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Yi(B.quality,u.quality),fe=A||(ee(r.max)||mf(B.quality,r.max))&&(ee(r.min)||pf(B.quality,r.min));return O&&X&&!de&&fe})[0];N&&N.bitrate&&Zf.next(N.bitrate);const F=(f=N!=null?N:S[Math.ceil((S.length-1)/2)])!==null&&f!==void 0?f:s[0],W=F&&d&&d.history[F.id]&&he()-d.history[F.id]<=i.trackCooldown&&(!d.last||F.id!==d.last.id);if(F!=null&&F.id&&d&&!W&&d.recordSelection(F),W&&(d!=null&&d.last)){const B=d.last;return d==null||d.recordSwitch(B),B}return d==null||d.recordSwitch(F),F};var we=s=>new URL(s).hostname;const ip=300,Ki=(s,e=ip)=>new ts(t=>{const{width:i,height:r}=s.getBoundingClientRect();if(t.next({width:i,height:r}),!window.ResizeObserver)return;const a=new ResizeObserver(Qo(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),k(u)&&k(d)&&t.next({width:u,height:d})},e));return a.observe(s),()=>a.disconnect()}),sp=5e3,ai={};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 ts(t=>{const i=r=>t.next(r);return s.on(e,i),()=>s.off(e,i)});class Ga{constructor(e){this.subscription=new ae,this.videoState=new ue(j.DOWNLOADING_LIB),this.textTracksManager=new Ke,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new T(void 0),this.maxSeekBackTime$=new T(1/0),this.availableFrom$=new T(void 0),this.elementSize$=new T(void 0),this.liveOffset=new xr,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)!==p.PAUSED&&a.state===z.Requested&&t!==j.STOPPED&&i!==p.STOPPED&&(n?this.seek(a.position-this.liveOffset.getTotalPausedTime()):this.seek(a.position)),i){case p.STOPPED:{switch(t){case j.STOPPED:break;case j.PLAYING:case j.PAUSED:case j.READY:this.stop();break;default:U(t)}break}case p.READY:{switch(t){case j.STOPPED:this.prepare();break;case j.PLAYING:case j.PAUSED:case j.READY:break;default:U(t)}break}case p.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:U(t)}break}case p.PAUSED:{switch(t){case j.PLAYING:this.pause(),this.liveOffset.pause();break;case j.PAUSED:break;case j.READY:this.videoState.setState(j.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED);break;case j.STOPPED:this.prepare();break;default:U(t)}break}default:U(i)}},this.video=lt(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=r=>{var a;e||this.params.output.error$.next({id:r==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:D.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"),sp);import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(ai.MediaPlayer=r.MediaPlayer,ai.Debug=r.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){R(ai.MediaPlayer,"dashjs not loaded"),R(ai.Debug,"dashjs not loaded"),this.player=ai.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?Or(t.frameRate+""):void 0),!0)),(this.params.format===y.DASH_WEBM||this.params.format===y.DASH_WEBM_AV1)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=_f(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&&If(this.player),kf(this.player),this.params.tuning.requestQuick&&Rf(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(j.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=m=>{e.error$.next({id:"DashIFProvider",category:D.WTF,message:"DashIFProvider internal logic error",thrown:m})},r=(m,S)=>this.subscription.add(m.subscribe(S,i));r(Ki(this.video),this.elementSize$),r(Se(this.player,"error").pipe(_(m=>{const S=typeof m.error=="object"?m.error.code:m.error,E=typeof m.error=="object"?m.error.message:void 0;return{id:`DashJS#${S}`,message:E}})),e.error$),r(Se(this.player,"playbackError").pipe(_(m=>({id:"DashJSPlayback",message:m.error}))),e.error$);const a=Se(this.player,"qualityChangeRendered").pipe(te(({mediaType:m})=>m==="video"),_(({newQuality:m})=>{var S;return(S=this.videoTracks.find(({bitrateInfo:E})=>E.qualityIndex===m))===null||S===void 0?void 0:S.track}));a.pipe(te(k)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(te(({to:m})=>m===j.STREAM_INITIALIZED),be()).subscribe(()=>{this.subscription.add(Ue(t.videoTrack,()=>{var m,S;const E=this.player.getQualityFor("video");return(S=(m=this.videoTracks.find(({bitrateInfo:$})=>$.qualityIndex===E))===null||m===void 0?void 0:m.track)===null||S===void 0?void 0:S.id},m=>{var S;if(ee(m))return;const E=(S=this.videoTracks.find(({track:$})=>$.id===m))===null||S===void 0?void 0:S.bitrateInfo;E&&this.player.setQualityFor("video",E.qualityIndex)},{changed$:a.pipe(_(m=>m==null?void 0:m.id)),onError:i}))},i)),this.subscription.add(Ue(t.autoVideoTrackSwitching,()=>{var m,S,E;return(E=(S=(m=this.player.getSettings().streaming)===null||m===void 0?void 0:m.abr)===null||S===void 0?void 0:S.autoSwitchBitrate)===null||E===void 0?void 0:E.video},m=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:m}}}}),{onError:i})),r(Se(this.player,"bufferStateChanged").pipe(te(({mediaType:m})=>m==="video"),_(({state:m})=>m==="bufferStalled")),e.isBuffering$),r(Se(this.player,"fragmentLoadingStarted"),({mediaType:m,request:{url:S}})=>{var E,$;const A=this.player.getDashMetrics(),L=A.getLatestFragmentRequestHeaderValueByID(m,"X-Reused"),q=(E=A.getLatestFragmentRequestHeaderValueByID(m,"X-Delivery-Type"))!==null&&E!==void 0?E:ci.HTTP1,N=($={1:!0,0:!1}[L])!==null&&$!==void 0?$:void 0;this.params.output.httpConnectionType$.next(q),this.params.output.httpConnectionReused$.next(N),e.hostname$.next(we(S))}),r(Se(this.player,"streamInitialized"),({streamInfo:{duration:m,manifestInfo:{isDynamic:S,availableFrom:E}}})=>{this.isLive$.next(S),this.availableFrom$.next(E.getTime()),S||e.duration$.next(m),this.videoTracks=[];const $=this.player.getQualityFor("video");let A;for(const L of this.player.getBitrateInfoListFor("video")){const q=L.qualityIndex.toString(10),N=Rt(L),F=L.bitrate/1e3,W={width:L.width,height:L.height},B=this.frameRatesByFrameHeight[L.height];if(N){const O={id:q,quality:N,bitrate:F,size:W,fps:B};this.videoTracks.push({track:O,bitrateInfo:L}),L.qualityIndex===$&&(A=O)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:L})=>L)),A&&e.currentVideoTrack$.next(A),this.videoState.setState(j.STREAM_INITIALIZED),this.videoState.startTransitionTo(j.READY)}),r(Se(this.player,"fragmentLoadingCompleted"),({request:m})=>{if(!m.requestEndDate||!m.firstByteDate||!m.bytesLoaded)return;const S=m.requestEndDate.getTime()-m.firstByteDate.getTime(),E=m.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(E,S)}),r(V(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const m=this.params.dependencies.throughputEstimator.throughput$.getValue(),S=Si(this.videoTracks.map(({track:$})=>$),{container:this.elementSize$.getValue(),throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),E=this.videoTracks.find(({track:$})=>$===S);E!=null&&E.bitrateInfo&&this.player.setQualityFor("video",E==null?void 0:E.bitrateInfo.qualityIndex,!1)}),r(Qe({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(te(k))}).pipe(te(({isLive:m})=>m),_(({maxSeekBackTime:m})=>-m/1e3)),this.params.output.duration$);const n=Se(this.player,"playbackTimeUpdated").pipe(_(({time:m})=>m!=null?m:0));r(Qe({availableFrom:this.availableFrom$.pipe(te(k)),currentTime:n}),({availableFrom:m,currentTime:S})=>this.params.output.liveTime$.next(m+S*1e3)),r(n.pipe(te(()=>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(_(()=>ho(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(Se(this.player,"playbackPlaying"),()=>{this.videoState.setState(j.PLAYING),I(t.playbackState,p.PLAYING)}),r(Se(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(j.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(Se(this.player,"playbackPaused"),()=>{this.videoState.setState(j.PAUSED),I(t.playbackState,p.PAUSED)}),r(Se(this.player,"canPlay"),()=>{var m;((m=this.videoState.getTransition())===null||m===void 0?void 0:m.to)===j.READY&&this.videoState.setState(j.READY)}),r(this.isLive$,e.isLive$),r(Ki(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=V(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Re(["init"])).pipe(Le(0));r(o,this.syncPlayback);const{playbackDuration$:u,ping$:d,connectionType$:l,connectionReused$:c}=Pf(this.player);r(l,this.params.output.httpConnectionType$),r(c,this.params.output.httpConnectionReused$),r(u,this.maxSeekBackTime$),r(d.pipe(be()),e.firstBytesEvent$),r(Se(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(Qe({isLive:this.isLive$,isShort:e.duration$.pipe(_(m=>m<60))}),({isLive:m,isShort:S})=>{const E=!m&&S;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:E}}})}),r(n.pipe(te(m=>m>this.params.tuning.insufficientBufferRuleMargin),be()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(Se(this.player,"manifestLoaded").pipe(be()).subscribe(()=>{this.subscription.add(Se(this.player,"playbackPlaying").pipe(be(),Ht(void 0)).subscribe(e.firstFrameEvent$,i))},i)),r(Se(this.player,"manifestLoaded"),m=>{var S,E,$,A,L,q,N;if(!((E=(S=m.data)===null||S===void 0?void 0:S.Period)===null||E===void 0)&&E.AdaptationSet){const F=[];for(const W of(A=($=m.data)===null||$===void 0?void 0:$.Period)===null||A===void 0?void 0:A.AdaptationSet)if(W.contentType==="text"){const B=(L=W.Representation)===null||L===void 0?void 0:L.id,O=new URL((q=W.Representation)===null||q===void 0?void 0:q.BaseURL,(N=m.data)===null||N===void 0?void 0:N.baseUri).toString(),X="internal",de=W.lang,fe=Boolean(B.includes("auto"));F.push({id:B,url:O,type:X,language:de,isAuto:fe})}t.internalTextTracks.startTransitionTo(F)}}),this.subscription.add(It(this.video,t.isLooped,i));const{volumeState$:h,looped$:f,playbackRateState$:v,inPiP$:b,inFullscreen$:g}=ht(this.video);this.subscription.add(ut(this.video,t.volume,h,i)),this.subscription.add(h.subscribe(e.volume$,i)),this.subscription.add(f.subscribe(e.loopedEvent$)),this.subscription.add(gt(this.video,t.playbackRate,v,i)),this.subscription.add(b.subscribe(e.inPiP$)),this.subscription.add(g.subscribe(e.inFullscreen$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(j.STOPPED),I(this.params.desiredState.playbackState,p.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=Yt(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Vt.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){}ct(this.video),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var gi=s=>{switch(s){case"mobile":return re.Q_144P;case"lowest":return re.Q_240P;case"low":return re.Q_360P;case"sd":case"medium":return re.Q_480P;case"hd":case"high":return re.Q_720P;case"fullhd":case"full":return re.Q_1080P;case"quadhd":case"quad":return re.Q_1440P;case"ultrahd":case"ultra":return re.Q_2160P}};const za=s=>{if(s instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(s.message))throw s;return!(s instanceof DOMException&&(s.code===20||s.name==="AbortError"))};var bt=async s=>{const e=s.muted;try{await s.play()}catch(t){if(!za(t))return!1;if(e)return console.warn(t),!1;s.muted=!0;try{await s.play()}catch(i){return za(i)&&(s.muted=!1,console.warn(i)),!1}}return!0};function Ae(){return he()}function po(s){return Ae()-s}function ja(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 rp(s,e,t){const i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function qi(s,e,t,i){const r=window.XMLHttpRequest;let a,n,o,u=!1,d=0,l,c,h=!1,f="arraybuffer",v=7e3,b=2e3,g=()=>{if(u)return;R(l);const O=po(l);let X;if(O<b){X=b-O,setTimeout(g,X);return}b*=2,b>v&&(b=v),n&&n.abort(),n=new r,L()};const m=O=>(a=O,B),S=O=>(c=O,B),E=()=>(f="json",B),$=()=>{if(!u){if(--d>=0){g(),i&&i();return}u=!0,c&&c(),t&&t()}},A=O=>(h=O,B),L=()=>{l=Ae(),n=new r,n.open("get",s);let O=0,X,de=0;const fe=()=>(R(l),Math.max(l,Math.max(X||0,de||0)));if(a&&n.addEventListener("progress",P=>{const H=Ae();a.updateChunk&&P.loaded>O&&(a.updateChunk(fe(),P.loaded-O),O=P.loaded,X=H)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>$())),n.addEventListener("load",()=>{if(u)return;R(n);const P=n.status;if(P>=200&&P<300){if(n.response.byteLength&&a){const H=n.response.byteLength-O;H&&a.updateChunk&&a.updateChunk(fe(),H)}c&&c(),n&&e(n.response)}else $()}),n.addEventListener("error",()=>{$()}),h){const P=()=>{R(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(de=Ae(),n.removeEventListener("readystatechange",P))};n.addEventListener("readystatechange",P)}return n.responseType=f,n.send(),B},B={withBitrateReporting:m,withParallel:A,withJSONResponse:E,withRetryCount:O=>(d=O,B),withRetryInterval:(O,X)=>(k(O)&&(b=O),k(X)&&(v=X),B),withTimeout:O=>(o=O,B),withFinally:S,send:L,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return B}const ap=100,np=2e3,op=500;let dp=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-op;if(t-e>np){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>ap&&(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 up{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=Ae(),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=Ae()-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=qi(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=Ae()}_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=Ae();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 Li=1e4,Ci=3,lp=300,cp=2e3,hp=6e4,fp=10,pp=1,mp=500;class vp{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 dp(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ja(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=ja(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||k(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=()=>{rp(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 up(Ci,Li,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,L)=>{u&&u.abort(),u=qi(this.urlResolver.resolve($,!1),A,L,()=>this._retryCallback()).withTimeout(Li).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ci).withFinally(()=>{u=null}).send()},f=($,A,L)=>{R(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve($,!1),A,L,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},v=$=>{const A=i.playbackRate;i.playbackRate!==$&&(t(`Playback rate switch: ${A}=>${$}`),i.playbackRate=$)},b=$=>{this.lowLatency=$,t(`lowLatency changed to ${$}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)v(1);else{let $=this._getBufferSizeSec();if(this.bufferStates.length<5){v(1);return}const L=Ae()-1e4;let q=0;for(let F=0;F<this.bufferStates.length;F++){const W=this.bufferStates[F];$=Math.min($,W.buf),W.ts<L&&q++}this.bufferStates.splice(0,q),t(`update playback rate; minBuffer=${$} drop=${q} jitter=${this.sourceJitter}`);let N=$-pp;this.sourceJitter>=0?N-=this.sourceJitter/2:this.sourceJitter-=1,N>3?v(1.15):N>1?v(1.1):N>.3?v(1.05):v(1)}},m=$=>{let A;const L=()=>A&&A.start?A.start.length:0,q=P=>A.start[P]/1e3,N=P=>A.dur[P]/1e3,F=P=>A.fragIndex+P,W=(P,H)=>({chunkIdx:F(P),startTS:q(P),dur:N(P),discontinuity:H}),B=()=>{let P=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,pe=H;this.sourceJitter>1&&(pe+=this.sourceJitter-1);let ge=A.dur.length-1;for(;ge>=0&&(pe-=A.dur[ge],!(pe<=0));--ge);P=Math.min(ge,A.dur.length-1-ne),P=Math.max(P,0)}return W(P,!0)},O=P=>{const H=L();if(!(H<=0)){if(k(P)){for(let ne=0;ne<H;ne++)if(q(ne)>P)return W(ne)}return B()}},X=P=>{const H=L(),ne=P?P.chunkIdx+1:0,pe=ne-A.fragIndex;if(!(H<=0)){if(!P||pe<0||pe-H>fp)return t(`Resync: offset=${pe} bChunks=${H} chunk=`+JSON.stringify(P)),B();if(!(pe>=H))return W(ne-A.fragIndex,!1)}},de=(P,H,ne)=>{d&&d.abort(),d=qi(this.urlResolver.resolve(P,!0,this.lowLatency),H,ne,()=>this._retryCallback()).withTimeout(Li).withRetryCount(Ci).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(P,H)=>{de($,ne=>{if(!c())return;A=ne;const pe=Boolean(A.lowLatency);pe!==this.lowLatency&&b(pe);let ge=0;for(let _e=0;_e<A.dur.length;++_e)ge+=A.dur[_e];ge>0&&(R(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ge/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,P(O(H))},()=>this._handleNetworkError())},nextChunk:X}},S=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),R(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:$=>{const{videoElement:A,logger:L}=this.params;let q=m(e.jidxUrl),N,F,W,B,O=0,X,de,fe;const P=()=>{X&&(clearTimeout(X),X=void 0);const J=Math.max(mp,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ye=O+J,ke=Ae(),Oe=Math.min(1e4,ye-ke);O=ke;const Xe=()=>{d||c()&&q.seek(()=>{c()&&(O=Ae(),H(),P())})};Oe>0?X=window.setTimeout(()=>{this.paused?P():Xe()},Oe):Xe()},H=()=>{let J;for(;J=q.nextChunk(B);)B=J,Ye(J);const ye=q.nextChunk(W);if(ye){if(W&&ye.discontinuity){L("Detected discontinuity; restarting playback"),this.paused?P():(S(),this._initPlayerWith(e));return}_e(ye)}else P()},ne=(J,ye)=>{if(!c()||!this.sourceBuffer)return;let ke,Oe,Xe;const yt=ft=>{window.setTimeout(()=>{c()&&ne(J,ye)},ft)};if(this.sourceBuffer.updating)L("Source buffer is updating; delaying appendBuffer"),yt(100);else{const ft=Ae(),Dt=A.currentTime;!this.paused&&A.buffered.length>1&&de===Dt&&ft-fe>500&&(L("Stall suspected; trying to fix"),this._fixupStall()),de!==Dt&&(de=Dt,fe=ft);const qe=this._getBufferSizeSec();if(qe>30)L(`Buffered ${qe} seconds; delaying appendBuffer`),yt(2e3);else try{this.sourceBuffer.appendBuffer(J),this.videoPlayStarted?(this.bufferStates.push({ts:ft,buf:qe}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ye&&ye()}catch(Qt){if(Qt.name==="QuotaExceededError")L("QuotaExceededError; delaying appendBuffer"),Xe=this.sourceBuffer.buffered.length,Xe!==0&&(ke=this.sourceBuffer.buffered.start(0),Oe=Dt,Oe-ke>4&&this.sourceBuffer.remove(ke,Oe-3)),yt(1e3);else throw Qt}}},pe=()=>{F&&N&&(L([`Appending chunk, sz=${F.byteLength}:`,JSON.stringify(W)]),ne(F,function(){F=null,H()}))},ge=J=>e.fragUrlTemplate.replace("%%id%%",J.chunkIdx),_e=J=>{c()&&f(ge(J),(ye,ke)=>{if(c()){if(ke/=1e3,F=ye,W=J,n=J.startTS,ke){const Oe=Math.min(10,J.dur/ke);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Oe:Oe}pe()}},()=>this._handleNetworkError())},Ye=J=>{c()&&(R(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ge(J),!1)))},xe=J=>{c()&&(e.cachedHeader=J,ne(J,()=>{N=!0,pe()}))};a=!0,q.seek(J=>{if(c()){if(O=Ae(),!J){P();return}B=J,!ee($)||J.startTS>$?_e(J):(W=J,H())}},$),e.cachedHeader?xe(e.cachedHeader):h(e.headerUrl,xe,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>n},l}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),k(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 k(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let h,f,v;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(f=this._getBufferSizeSec(),v=c/this.bitrate,f>10&&v>.8||f>15&&v>.5||f>20&&v>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},a=(()=>({updateChunk:(h,f)=>{const v=Ae();if(this.chunkRateEstimator.addInterval(h,v,f)){const g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:v-h,speed:g}),!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&&po(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,h)=>{const f=a.updateChunk(c,h);return f&&d(),f},notifySwitch:c=>{const h=Ae();c<o&&(n=h),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=qi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Li).withRetryCount(Ci).withRetryInterval(lp,cp).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;bt(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))},hp))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var G;(function(s){s.STOPPED="stopped",s.MANIFEST_READY="manifest_ready",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(G||(G={}));const Sp=[G.PAUSED,G.PLAYING,G.READY],gp=[G.PAUSED,G.PLAYING,G.READY];class bp{constructor(e){this.subscription=new ae,this.videoState=new ue(G.STOPPED),this.representations$=new T([]),this.textTracksManager=new Ke,this.maxSeekBackTime$=new T(1/0),this.zeroTime$=new T(void 0),this.liveOffset=new xr,this._dashCb=r=>{var a,n,o,u;switch(r.name){case"buffering":{const d=r.isBuffering;this.params.output.isBuffering$.next(d);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:D.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const d=r.manifest,l=[];for(const c of d){const h=(a=c.name)!==null&&a!==void 0?a:c.index.toString(10),f=(n=gi(c.name))!==null&&n!==void 0?n:Rt(c.video),v=c.bitrate/1e3,b={...c.video};if(!f)continue;const g={id:h,quality:f,bitrate:v,size:b};l.push({track:g,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)===G.MANIFEST_READY&&this.videoState.setState(G.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),k(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===p.STOPPED){a!==G.STOPPED&&(this.videoState.startTransitionTo(G.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(G.STOPPED));return}if(!n){if(gp.includes(a)){const l=(r=this.params.desiredState.videoTrack.getTransition())===null||r===void 0?void 0:r.to;k(l)&&this.setVideoTrack(l);const c=this.params.desiredState.autoVideoTrackSwitching.getTransition();c&&this.setAutoQuality(c.to)}if((u==null?void 0:u.to)!==p.PAUSED&&d.state===z.Requested&&Sp.includes(a)){this.seek(d.position-this.liveOffset.getTotalPausedTime());return}switch(a){case G.STOPPED:this.videoState.startTransitionTo(G.MANIFEST_READY),this.dash.attachSource(Yt(this.params.source.url));return;case G.MANIFEST_READY:this.videoState.startTransitionTo(G.READY),this.prepare();break;case G.READY:if(o===p.PAUSED)this.videoState.setState(G.PAUSED);else if(o===p.PLAYING){this.videoState.startTransitionTo(G.PLAYING);const l=u==null?void 0:u.from;l&&l===p.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(G.PAUSED)})}return;case G.PLAYING:o===p.PAUSED&&(this.videoState.startTransitionTo(G.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case G.PAUSED:o===p.PLAYING&&(this.videoState.startTransitionTo(G.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(G.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return U(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:D.WTF,message:"DashLiveProvider internal logic error",thrown:r})};V(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=lt(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(we(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=ht(this.video);this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===G.READY&&this.videoState.setState(G.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(G.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===z.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(G.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(me(),_(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(Qe({zeroTime:this.zeroTime$.pipe(te(k)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(It(this.video,this.params.desiredState.isLooped,t)).add(ut(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(gt(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:r}})=>{const a=r&&gf(r);this.dash.setMaxAutoQuality(a)})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case G.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(p.STOPPED);break;case G.MANIFEST_READY:case G.READY:((a=this.params.desiredState.playbackState.getTransition())===null||a===void 0?void 0:a.to)===p.READY&&this.params.desiredState.playbackState.setState(p.READY);break;case G.PAUSED:this.params.desiredState.playbackState.setState(p.PAUSED);break;case G.PLAYING:this.params.desiredState.playbackState.setState(p.PLAYING);break;default:return U(r.to)}},t)).add(V(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,Re(["init"])).pipe(Le(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),ct(this.video)}createLiveDashPlayer(){const e=new vp({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&&k(u)?u:(a=Si(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=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t===p.PAUSED&&i===G.PAUSED,a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Yt(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}}var mo=s=>{var e,t;const i=s.get("X-Delivery-Type"),r=s.get("X-Reused"),a=i===null?ci.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}},wt=(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 yp=s=>{const e=document.createElement("a");return e.href=s,e.origin},Tp=s=>{const e=document.createElement("a");return e.href=s,e.host};class vo{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=vi(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(Tp(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 Xi{constructor(e){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t==null||t()}catch(i){if(i.name==="QuotaExceededError"){this._isFull=!0;const r=this._sourceBuffer.buffered;let a=0;for(let n=0,o=r.length;n<o;n++)a+=r.end(n)-r.start(n);a&&(this._maxBufferDuration=Math.round(a))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",i),i}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,i,r,a,n,o){this.abort(()=>{let u=0;const d=Date.now();let l=0,c=0,h=0;const f=b=>{r(Xi._str2ua(b.substr(u))),u=b.length};let v=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(v=Gt(v)),this._lastXhr=new vo(v,e.failoverHosts,b=>{this._lastXhr=void 0,f(b);const g=Date.now()-d;this._params.onBandwidthChange({size:b.length,duration:g,speed:8*b.length/(g/1e3)}),this._onDashCallback("loading",{size:b.length,done:!0}),a==null||a()},b=>{if(b.length-u>o&&f(b),c===0){c=Date.now();return}h=b.length-l;const g=Date.now()-c;h>=100*1024&&g>=1e3&&(this._params.onBandwidthChange({size:h,duration:g,speed:8*h/(g/1e3)}),h=0,l=b.length,c=Date.now()),this._onDashCallback("loading",{size:b.length,done:!1})},n,(b,g,m)=>this._params.onError(b,g,m))})}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=Xi._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 Ep{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 vo(i,t,r=>{this.attachManifest(r,t,yp(i))},void 0,r=>{this._params.onResponseHeaders(r)},(r,a,n)=>this._params.onError(r,a,n))}attachManifest(e,t,i){const a=new DOMParser().parseFromString(e,"text/xml").documentElement,n=(d,l)=>{const c=d.attributes.getNamedItem(l);return c?c.value:null};this._duration=this._parseDurationFromISO8601(String(n(a,"mediaPresentationDuration")));const o=[],u=[];if(Array.prototype.forEach.call(a.getElementsByTagName("Representation"),d=>{var l,c,h,f,v,b,g,m,S,E,$,A,L,q,N,F,W,B,O;const X=d.getElementsByTagName("SegmentBase")[0],de=X&&n(X,"indexRange").split("-"),fe=X&&X.getElementsByTagName("Initialization")[0],P=fe&&n(fe,"range").split("-");if(!P||!de){const Ye=d.parentElement;if((Ye==null?void 0:Ye.getAttribute("contentType"))==="text"){const xe=(l=d.getAttribute("id"))!==null&&l!==void 0?l:void 0,J=(i?i+"/":"")+((v=(f=(h=(c=d.getElementsByTagName("BaseURL"))===null||c===void 0?void 0:c[0])===null||h===void 0?void 0:h.childNodes)===null||f===void 0?void 0:f[0])===null||v===void 0?void 0:v.data),ye=(b=Ye.getAttribute("lang"))!==null&&b!==void 0?b:void 0,ke=xe==null?void 0:xe.includes("auto");J&&u.push({id:xe,url:J,language:ye,isAuto:ke})}return}const H=.1,ne=Number((g=d.attributes.getNamedItem("bandwidth"))===null||g===void 0?void 0:g.value),pe=(i?i+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ge;const _e=(S=(m=d.attributes.getNamedItem("frameRate"))===null||m===void 0?void 0:m.value)!==null&&S!==void 0?S:void 0;ge=_e?Or(_e):void 0,o.push({width:Number((E=d.attributes.getNamedItem("width"))===null||E===void 0?void 0:E.value),height:Number(($=d.attributes.getNamedItem("height"))===null||$===void 0?void 0:$.value),bandwidth:ne,baseURL:pe,failoverHosts:t,indexFrom:Number(de[0]),indexTo:Number(de[1]),initFrom:Number(P[0]),initTo:Number(P[1]),codecs:(L=(A=d.attributes.getNamedItem("codecs"))===null||A===void 0?void 0:A.value)!==null&&L!==void 0?L:void 0,mimeType:(N=(q=d.attributes.getNamedItem("mimeType"))===null||q===void 0?void 0:q.value)!==null&&N!==void 0?N:void 0,fps:ge,bufferSize:H*ne/8,bufferLength:H,name:(W=(F=d.attributes.getNamedItem("okQuality"))===null||F===void 0?void 0:F.value)!==null&&W!==void 0?W:void 0,id:(O=(B=d.attributes.getNamedItem("id"))===null||B===void 0?void 0:B.value)!==null&&O!==void 0?O:void 0})}),o.length)this._representations=o;else{this._onDashCallback("error");return}u.forEach(({id:d,language:l,url:c})=>{const h=document.createElement("track");c&&h.setAttribute("src",c),d&&h.setAttribute("id",d),l&&h.setAttribute("srclang",l),this._video.appendChild(h)}),this._representations.sort((d,l)=>l.bandwidth-d.bandwidth),this._params.onManifestReady({representations:this._representations,textRepresentations:u})}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const i=Date.now();this._stream.load(e,e.initFrom,e.indexTo,r=>{let a=e.initTo-e.initFrom+1;if(!r.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(r.buffer,0,a);const n=new DataView(r.buffer);a+=12;const o=n.getUint32(a+4,!1);a+=8;let u=n.getUint32(a,!1),d=n.getUint32(a+4,!1)+(e.indexTo+1);a+=8;const l=n.getUint16(a+2,!1);a+=4,e.refs=[];for(let h=0;h<l;h+=1){const f=d+(n.getUint32(a,!1)&2147483647),v=u+n.getUint32(a+4,!1);a+=12,e.refs.push({fromTime:u/o,toTime:v/o,fromOffset:d,toOffset:f-1}),d=f,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 f=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),f)}const l=this._appendVector[String(d.fromTime)];l!==r&&(r=l,this._params.onRepresentationPlay(l));let c;if(this._findRef(d.toTime)){const f=this._buffer.getByTime(this._video.currentTime);if(!f){this._onDashCallback("buffering");return}c=f.to-this._video.currentTime,c<e.bufferLength&&(this._onDashCallback("buffering"),a!==f.to&&(a=f.to,window.setTimeout(()=>{try{const v=this._buffer.getNextWithGap(f);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 Xi({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||ee(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 Q;(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"})(Q||(Q={}));const $p=[Q.PAUSED,Q.PLAYING];class Ap{constructor(e){this.videoState=new ue(Q.STOPPED),this.subscription=new ae,this.representations$=new T([]),this.currentRepresentation$=new T(void 0),this.textTracksManager=new Ke,this.elementSize$=new T(void 0),this.dashLiteEvents={idxRequestPing$:new x,responseHeaders$:new x,manifestReady$:new x,representationPlay$:new x,error$:new x},this.handleManifestReady=({representations:t,textRepresentations:i})=>{var r,a,n;const o=[];for(const u of t){const d=(a=(r=u.name)!==null&&r!==void 0?r:u.id)!==null&&a!==void 0?a:u.height.toString(10),l=(n=u.name&&gi(u.name))!==null&&n!==void 0?n:Rt(u),c=u.bandwidth/1e3,h={width:u.width,height:u.height},f=u.fps;if(!l)continue;const v={id:d,quality:l,bitrate:c,size:h,fps:f};o.push({track:v,representation:u})}if(this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),(i==null?void 0:i.length)>0){const u=[];for(const d of i){const l=d.id||`${d.language}_${Date.now()}`;u.push({id:l,type:"internal",url:d.url||"",language:d.language,isAuto:d.isAuto})}this.params.desiredState.internalTextTracks.startTransitionTo(u)}this.videoState.setState(Q.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===p.STOPPED){t!==Q.STOPPED&&(this.videoState.startTransitionTo(Q.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Q.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(!i)switch((a==null?void 0:a.to)!==p.PAUSED&&n.state===z.Requested&&$p.includes(t)&&this.seek(n.position,n.forcePrecise),t){case Q.STOPPED:this.videoState.startTransitionTo(Q.MANIFEST_LOADED),this.prepare();return;case Q.MANIFEST_LOADED:this.videoState.startTransitionTo(Q.INITIAL_REPRESENTATION_SELECTED);return;case Q.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(Q.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case Q.METADATA_LOADED:this.videoState.startTransitionTo(Q.READY),this.dash.updateRefsForCurrentTime();return;case Q.READY:r===p.READY?I(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(Q.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(Q.PLAYING),this.playIfAllowed());return;case Q.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(Q.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case Q.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(Q.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return U(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),V(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=lt(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Nf(this.video),this.dash=new Ep({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:({representations:t,textRepresentations:i})=>this.dashLiteEvents.manifestReady$.next({representations:t,textRepresentations:i}),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,i,r)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:i,thrown:r,category:D.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:D.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=ht(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$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(a.seeking$.subscribe(()=>{ee(this.params.desiredState.seekState.getState().state!==z.Applying)&&(this.videoState.getState()===Q.PLAYING||this.videoState.getState()===Q.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(It(this.video,t.isLooped,i)),this.subscription.add(ut(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(gt(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),n(Ki(this.video),this.elementSize$),this.subscription.add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===Q.READY&&this.videoState.setState(Q.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(Q.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)})).add(a.playing$.subscribe(()=>{this.videoState.setState(Q.PLAYING),I(this.params.desiredState.playbackState,p.PLAYING)},i)).add(a.loadedMetadata$.subscribe(()=>{this.videoState.setState(Q.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:D.WTF,message:u,thrown:d}))).subscribe(this.params.output.error$)).add(V(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(),f=this.params.desiredState.videoTrack.getState(),v=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),b=this.elementSize$.getValue(),g=r();h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to);let m;if(!g&&k(f))m=f;else{const S=wt(this.video.buffered,this.video.currentTime*1e3),E=g?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,$=Math.min(S/E,1);m=(u=Si(c.map(({track:A})=>A),{container:b,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 k(m)?(d=c.find(({track:S})=>S.id===m))===null||d===void 0?void 0:d.representation:void 0}),me()).subscribe(this.currentRepresentation$,i)).add(Qe({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(te(o=>o.to===Q.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(te(k))}).pipe(be()).subscribe(()=>this.videoState.setState(Q.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(te(k),me((o,u)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?o.height<=u.height:o===u)).subscribe(o=>{const u=wt(this.video.buffered,this.video.currentTime*1e3),d=Math.min(u/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||d<=.5||!r())&&(this.dash.setQualityByRepresentation(o,!0),this.params.output.hostname$.next(we(o.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:u,reused:d}=mo(o);this.params.output.httpConnectionType$.next(u),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(be(),Ht(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(te(k)).subscribe(this.handleRepresentationPlay,i)).add(V(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Re(["init"])).pipe(Le(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),ct(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return U(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){bt(this.video).then(e=>{e||(this.videoState.setState(Q.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}}var Ee;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(Ee||(Ee={}));var Zi;(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"})(Zi||(Zi={}));var De;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(De||(De={}));var Z;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(Z||(Z={}));var zt;(function(s){s.MP4="mp4",s.WEBM="webm"})(zt||(zt={}));var Sr=(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 wp=(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)},_p=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Wa=_p?wp:window.requestIdleCallback;var Vs,Hs;let So=!1;try{So=co()&&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 kp{constructor(e){this.bufferFull$=new x,this.error$=new x,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:D.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);try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:i}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&i==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${i}`,category:D.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:U(t)}}}var Qa=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};const go=new TextDecoder("ascii"),bo=s=>{let e=0,t=s.getUint32(e);e+=4;const i=new DataView(s.buffer,s.byteOffset+e,4),r=go.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}},Pp=s=>go.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",Rp=(s,e,t)=>{const i=bo(s),r=[];let a=0;const n=()=>{const b=i.contents.getUint32(a);return a+=4,b};if((n()&4278190080)!==0)throw new SyntaxError("Unsupported sidx version");n();const d=n(),l=n(),c=n(),h=n()&4294967295;let f=l/d*1e3,v=(t?t.to+1:s.byteOffset+s.byteLength)+c;for(let b=0;b<h;b++){const g=n(),m=g>>>31,S=g<<1>>>1,E=n();if(n(),m!==0)throw new Error("Unsupported multilevel sidx");const $=E/d*1e3;r.push({status:Z.NONE,time:{from:f,to:f+$},byte:{from:v,to:v+S-1}}),f+=$,v+=S}return r},Ip=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=bo(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},Dp={validateData:Pp,parseInit:()=>null,getIndexRange:()=>{},parseSegments:Rp,parseFeedableSegmentChunk:Ip};var w;(function(s){s[s.EBML=440786851]="EBML",s[s.EBMLVersion=17030]="EBMLVersion",s[s.EBMLReadVersion=17143]="EBMLReadVersion",s[s.EBMLMaxIDLength=17138]="EBMLMaxIDLength",s[s.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",s[s.DocType=17026]="DocType",s[s.DocTypeVersion=17031]="DocTypeVersion",s[s.DocTypeReadVersion=17029]="DocTypeReadVersion",s[s.Void=236]="Void",s[s.Segment=408125543]="Segment",s[s.SeekHead=290298740]="SeekHead",s[s.Seek=19899]="Seek",s[s.SeekID=21419]="SeekID",s[s.SeekPosition=21420]="SeekPosition",s[s.Info=357149030]="Info",s[s.TimestampScale=2807729]="TimestampScale",s[s.Duration=17545]="Duration",s[s.Tracks=374648427]="Tracks",s[s.Chapters=272869232]="Chapters",s[s.Cluster=524531317]="Cluster",s[s.Timestamp=231]="Timestamp",s[s.SilentTracks=22612]="SilentTracks",s[s.SilentTrackNumber=22743]="SilentTrackNumber",s[s.Position=167]="Position",s[s.PrevSize=171]="PrevSize",s[s.SimpleBlock=163]="SimpleBlock",s[s.BlockGroup=160]="BlockGroup",s[s.EncryptedBlock=175]="EncryptedBlock",s[s.Attachments=423732329]="Attachments",s[s.Tags=307544935]="Tags",s[s.Cues=475249515]="Cues",s[s.CuePoint=187]="CuePoint",s[s.CueTime=179]="CueTime",s[s.CueTrackPositions=183]="CueTrackPositions",s[s.CueTrack=247]="CueTrack",s[s.CueClusterPosition=241]="CueClusterPosition",s[s.CueRelativePosition=240]="CueRelativePosition",s[s.CueDuration=178]="CueDuration",s[s.CueBlockNumber=21368]="CueBlockNumber",s[s.CueCodecState=234]="CueCodecState",s[s.CueReference=219]="CueReference",s[s.CueRefTime=150]="CueRefTime"})(w||(w={}));var C;(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"})(C||(C={}));const Ja={[w.EBML]:{type:C.Master},[w.EBMLVersion]:{type:C.UnsignedInteger},[w.EBMLReadVersion]:{type:C.UnsignedInteger},[w.EBMLMaxIDLength]:{type:C.UnsignedInteger},[w.EBMLMaxSizeLength]:{type:C.UnsignedInteger},[w.DocType]:{type:C.String},[w.DocTypeVersion]:{type:C.UnsignedInteger},[w.DocTypeReadVersion]:{type:C.UnsignedInteger},[w.Void]:{type:C.Binary},[w.Segment]:{type:C.Master},[w.SeekHead]:{type:C.Master},[w.Seek]:{type:C.Master},[w.SeekID]:{type:C.Binary},[w.SeekPosition]:{type:C.UnsignedInteger},[w.Info]:{type:C.Master},[w.TimestampScale]:{type:C.UnsignedInteger},[w.Duration]:{type:C.Float},[w.Tracks]:{type:C.Master},[w.Chapters]:{type:C.Master},[w.Cluster]:{type:C.Master},[w.Timestamp]:{type:C.UnsignedInteger},[w.SilentTracks]:{type:C.Master},[w.SilentTrackNumber]:{type:C.UnsignedInteger},[w.Position]:{type:C.UnsignedInteger},[w.PrevSize]:{type:C.UnsignedInteger},[w.SimpleBlock]:{type:C.Binary},[w.BlockGroup]:{type:C.Master},[w.EncryptedBlock]:{type:C.Binary},[w.Attachments]:{type:C.Master},[w.Tags]:{type:C.Master},[w.Cues]:{type:C.Master},[w.CuePoint]:{type:C.Master},[w.CueTime]:{type:C.UnsignedInteger},[w.CueTrackPositions]:{type:C.Master},[w.CueTrack]:{type:C.UnsignedInteger},[w.CueClusterPosition]:{type:C.UnsignedInteger},[w.CueRelativePosition]:{type:C.UnsignedInteger},[w.CueDuration]:{type:C.UnsignedInteger},[w.CueBlockNumber]:{type:C.UnsignedInteger},[w.CueCodecState]:{type:C.UnsignedInteger},[w.CueReference]:{type:C.Master},[w.CueRefTime]:{type:C.UnsignedInteger}},yo=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=es(s,t),r=i in Ja,a=r?Ja[i].type:C.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=es(u),c=d*2**((o-1)*8)+l,h=t+o;let f;return h+c>s.byteLength?f=new DataView(s.buffer,s.byteOffset+h):f=new DataView(s.buffer,s.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:f,valueSize:c}},es=(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},it=(s,e)=>{switch(e){case C.SignedInteger:return s.getInt8(0);case C.UnsignedInteger:return es(s);case C.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case C.String:return new TextDecoder("ascii").decode(s);case C.UTF8:return new TextDecoder("utf-8").decode(s);case C.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case C.Master:return s;case C.Binary:return s;default:U(e)}},bi=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=yo(i);if(!e(r))return;r.type===C.Master&&bi(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},Lp=s=>{if(s.getUint32(0)!==w.EBML)return!1;let e,t,i;const r=yo(s);return bi(r.value,({tag:a,type:n,value:o})=>(a===w.EBMLReadVersion?e=it(o,n):a===w.DocType?t=it(o,n):a===w.DocTypeReadVersion&&(i=it(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},To=[w.Info,w.SeekHead,w.Tracks,w.Chapters,w.Cluster,w.Cues,w.Attachments,w.Tags],Cp=[w.Timestamp,w.SilentTracks,w.SilentTrackNumber,w.Position,w.PrevSize,w.SimpleBlock,w.BlockGroup,w.EncryptedBlock],xp=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,d;return bi(s,({tag:l,type:c,value:h,valueSize:f})=>{if(l===w.SeekID){const v=it(h,c);d=es(v)}else l!==w.SeekPosition&&(d=void 0);return l===w.Segment?(e=h.byteOffset,t=h.byteOffset+f):l===w.Info?a=!0:l===w.SeekHead?n=!0:l===w.TimestampScale?i=it(h,c):l===w.Duration?r=it(h,c):l===w.SeekPosition&&d===w.Cues?u=it(h,c):a&&n&&To.includes(l)&&(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}},Op=s=>{if(ee(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Np=(s,e)=>{let t=!1,i=!1;const r=o=>k(o.time)&&k(o.position),a=[];let n;return bi(s,({tag:o,type:u,value:d})=>{switch(o){case w.Cues:t=!0;break;case w.CuePoint:n&&r(n)&&a.push(n),n={};break;case w.CueTime:n&&(n.time=it(d,u));break;case w.CueTrackPositions:break;case w.CueClusterPosition:n&&(n.position=it(d,u));break;default:t&&To.includes(o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{const{time:d,position:l}=o,c=a[u+1];return{status:Z.NONE,time:{from:d,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},Bp=s=>{let e=0,t=!1;try{bi(s,i=>i.tag===w.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Cp.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[w.SimpleBlock,w.BlockGroup,w.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},Mp={validateData:Lp,parseInit:xp,getIndexRange:Op,parseSegments:Np,parseFeedableSegmentChunk:Bp};class Ka{constructor(e,t,i,r,{fetcher:a,tuning:n,getCurrentPosition:o,compatibilityMode:u=!1}){switch(this.onLastSegment$=new T(!1),this.fullyBuffered$=new T(!1),this.playingRepresentation$=new T(void 0),this.error$=new x,this.gaps=[],this.subscription=new ae,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new _t,this.destroyAbortController=new _t,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=Fe(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 kp(this.sourceBuffer),this.subscription.add(M(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},v=>this.error$.next({id:"SegmentEjection",category:D.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:D.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(v=>{if(!this.sourceBuffer)return;const b=Math.min(this.bufferLimit,Qa(this.sourceBuffer.buffered)*.8);this.bufferLimit=b,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(R(c,"No init buffer for starting representation"),R(h,"No segments for starting representation"),!(c instanceof ArrayBuffer))return;let f=0;for(const v of h)v.time.from-f>0&&this.gaps.push({representation:l.id,from:f,to:v.time.from}),f=v.time.to;k(l.duration)&&l.duration-f>0&&this.gaps.push({representation:l.id,from:f,to:l.duration}),yield this.sourceBufferTaskQueue.append(c,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId)}.bind(this)),this.switchTo=Fe(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(ee(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();k(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 zt.MP4:this.containerParser=Dp;break;case zt.WEBM:this.containerParser=Mp;break;default:U(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 _t,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ee(e)||ee(this.downloadingRepresentationId)||ee(this.playingRepresentationId)||ee(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=wt(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)&&Qa(this.sourceBuffer.buffered)>=this.bufferLimit){const d=wt(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=Ze(o,0);l&&l.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===Z.FED&&!o.length&&wt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const u=Ze(i,-1);u&&u.status===Z.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;if(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();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){const r=e.findIndex(({status:c,time:{from:h,to:f}},v)=>{const b=h<=i&&f>=i,g=h>i||b||v===0&&i===0,m=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&h<=i+m||f<=i+m;return(c===Z.NONE||c===Z.PARTIALLY_EJECTED&&g&&S&&this.sourceBuffer&&!Sr(this.sourceBuffer.buffered,i))&&g&&S});if(r===-1)return[];if(t!==De.BYTE_RANGE)return e.slice(r,r+1);const a=e;let n=0,o=0;const u=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=d||o<=l);c++){const h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status===Z.NONE||h.status===Z.PARTIALLY_EJECTED)u.push(h);else break}return u}async loadSegments(e,t,i="auto"){if(!e.length)return;let r,a,n=e;const{type:o}=t.segmentReference;switch(o){case De.BYTE_RANGE:{r=t.segmentReference.url,a={from:Ze(e,0).byte.from,to:Ze(e,-1).byte.to};break}case De.TEMPLATE:{const d=Ze(e,0);r=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:U(o)}for(const d of n)d.status=Z.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:u}=this.downloadAbortController;if(this.failedDownloads&&(await Fe(u,async function*(){const d=Wr(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:D.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&&k(r)&&(i=wt((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:D.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=Z.FED,"size"in c.segment&&(c.segment.size=c.fedBytes);for(const f of this.representations.values())if(f.id!==t)for(const v of(h=this.segments.get(f.id))!==null&&h!==void 0?h:[])v.status===Z.FED&&v.time.from===c.segment.time.from&&v.time.to===c.segment.time.to&&(v.status=Z.NONE);this.activeSegments.delete(c),this.detectGapsWhenIdle(t,[c.segment])},u=this.representations.get(t);if(!u)return;const d=u.segmentReference.type,l=e.byteLength;for(const c of this.activeSegments){const{segment:h}=c,f=d===De.BYTE_RANGE,v=f?h.byte.to-h.byte.from+1:l;if(c.representationId!==t||!(!f||h.byte.from>=i&&h.byte.to<i+e.byteLength))continue;if(a.aborted){n();continue}const g=f?h.byte.from-i:0,m=f?h.byte.to-i:e.byteLength,S=g<r,E=m<=r;if(h.status===Z.DOWNLOADING&&S&&E){h.status=Z.DOWNLOADED,this.activeSegments.delete(c);const $=new DataView(e.buffer,e.byteOffset+g,v);this.sourceBufferTaskQueue.append($,a).then(A=>A&&!a.aborted?o(c):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&(c.loadedBytes=Math.min(v,r-g),c.loadedBytes>c.feedingBytes)){const $=new DataView(e.buffer,e.byteOffset+g+c.feedingBytes,c.loadedBytes-c.feedingBytes),A=c.loadedBytes===v?$:this.containerParser.parseFeedableSegmentChunk($);A!=null&&A.byteLength&&(h.status=Z.PARTIALLY_FED,c.feedingBytes+=A.byteLength,this.sourceBufferTaskQueue.append(A,a).then(L=>{if(a.aborted)n();else if(L)c.fedBytes+=A.byteLength,c.fedBytes===v&&o(c);else{if(c.feedingBytes<v)return;n()}}))}}}abortSegment(e){e.status===Z.PARTIALLY_FED||e.status===Z.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=Z.NONE),e.status=Z.PARTIALLY_EJECTED):e.status=Z.NONE;for(const 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=Wa(()=>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?Fe(this.destroyAbortController.signal,async function*(){const o=Wr(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:D.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||ee(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===Z.FED&&u(l)}if(o=isFinite(a)&&isFinite(n),!o){r=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const l of d){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;l.status===Z.FED&&u(l)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const l=this.sourceBuffer.buffered.start(d)*1e3,c=this.sourceBuffer.buffered.end(d)*1e3;for(const h of this.segments.values())for(const f of h)if(f.status===Z.NONE&&Math.round(f.time.from)<=Math.round(l)&&Math.round(f.time.to)>=Math.round(c)){a=l,n=c;break}}if(o=isFinite(a)&&isFinite(n),!o&&i){r=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const l of this.segments.values())for(const c of l)c.time.from>e+d&&c.status===Z.FED&&u(c)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}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=Wa(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:D.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(ee(this.sourceBuffer)||ee(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}const t=1;for(const i of this.segments.values())for(const r of i){const{status:a}=r;if(a!==Z.FED&&a!==Z.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(l=>l.from-t<=n&&l.to+t>=o),d=e.filter(l=>n>=l.from-t&&n<=l.to+t||o>=l.from-t&&o<=l.to+t);u||(d.length===1?r.status=Z.PARTIALLY_EJECTED:r.status=Z.NONE)}}}var Ut;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(Ut||(Ut={}));class Fp{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new T(void 0),this.lastConnectionReused$=new T(void 0),this.lastRequestFirstBytes$=new T(void 0),this.abortAllController=new _t,this.subscription=new ae,this.fetchManifest=Fe(this.abortAllController.signal,async function*(r){let a=r;this.requestQuic&&(a=Gt(a));const n=yield qt(a,{signal:this.abortAllController.signal}).catch(ni);return n?(this.onHeadersReceived(n.headers),n.text()):null}.bind(this)),this.fetch=Fe(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,f,v;let b=r;const g=new Headers;if(n)switch(a){case Ut.HEADER:{g.append("Range",`bytes=${n.from}-${n.to}`);break}case Ut.PARAM:{const P=new URL(b,location.href);P.searchParams.append("bytes",`${n.from}-${n.to}`),b=P.toString();break}default:U(a)}this.requestQuic&&(b=Gt(b));let m=this.abortAllController.signal;if(d){const P=new _t;if(this.subscription.add(V(M(this.abortAllController.signal,"abort"),M(d,"abort")).subscribe(()=>{try{P.abort()}catch(H){ni(H)}})),this.abortAllController.signal.aborted||d.aborted)try{P.abort()}catch(H){ni(H)}m=P.signal}const S=he(),E=yield qt(b,{priority:u,headers:g,signal:m}).catch(ni),$=he();if((c=this.throughputEstimator)===null||c===void 0||c.addRawRtt($-S),!E)return null;if(!E.ok||!E.body)return Promise.reject(new Error(`Fetch error ${E.status}: ${E.statusText}`));this.onHeadersReceived(E.headers);const A=parseInt((h=E.headers.get("Content-Length"))!==null&&h!==void 0?h:"",10)||n&&n.to-n.from+1||NaN;if(!A){const P=yield E.arrayBuffer();return(f=this.throughputEstimator)===null||f===void 0||f.addRawSpeed(P.byteLength,he()-$),o==null||o(new DataView(P),P.byteLength),P}if(!o&&!l)return E.arrayBuffer();const[L,q]=E.body.tee(),N=L.getReader();l&&((v=this.throughputEstimator)===null||v===void 0||v.trackStream(q));let F=0;const W=new ArrayBuffer(A),B=new Uint8Array(W),O=new DataView(W);let X=!1;const de=P=>{X=!0,ni(P)},fe=Fe(m,async function*({done:P,value:H}){F===0&&this.lastRequestFirstBytes$.next(he()-S),!m.aborted&&!P&&H&&(B.set(H,F),F+=H.byteLength,o==null||o(O,F),yield N==null?void 0:N.read().then(fe,de))}.bind(this));return yield N==null?void 0:N.read().then(fe,de),X?null:W}.bind(this)),this.fetchByteRangeRepresentation=Fe(this.abortAllController.signal,async function*(r,a,n){var o;if(r.type!==De.BYTE_RANGE)return null;const{from:u,to:d}=r.initRange;let l=u,c=d,h=!1,f,v;r.indexRange&&(f=r.indexRange.from,v=r.indexRange.to,h=d+1===f,h&&(l=Math.min(f,u),c=Math.max(v,d))),l=Math.min(l,0);const b=yield this.fetch(r.url,{range:{from:l,to:c},priority:n,measureThroughput:!1});if(!b)return null;const g=new DataView(b,u-l,d-l+1);if(!a.validateData(g))throw new Error("Invalid media file");const m=a.parseInit(g),S=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(m);if(!S)throw new ReferenceError("No way to load representation index");let E;if(h)E=new DataView(b,S.from-l,S.to-S.from+1);else{const A=yield this.fetch(r.url,{range:S,priority:n,measureThroughput:!1});if(!A)return null;E=new DataView(A)}const $=a.parseSegments(E,m,S);return{dataView:new DataView(b),segments:$}}.bind(this)),this.fetchTemplateRepresentation=Fe(this.abortAllController.signal,async function*(r,a){if(r.type!==De.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:Z.NONE,size:void 0})),dataView:new DataView(o)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=mo(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 De.BYTE_RANGE:return(r=await this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case De.TEMPLATE:return(a=await this.fetchTemplateRepresentation(e,i))!==null&&a!==void 0?a:null;default:U(n)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const ni=s=>{if(!(s instanceof DOMException)||!(s.name==="AbortError"||s.code===20))throw s};var Up=kt,Vp=ss,Hp=He,Yp=Hp("match"),qp=function(s){var e;return Up(s)&&((e=s[Yp])!==void 0?!!e:Vp(s)=="RegExp")},Gp=us,zp=String,jp=function(s){if(Gp(s)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return zp(s)},Wp=Pt,Qp=function(){var s=Wp(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},Jp=ot,Kp=dt,Xp=Er,Zp=Qp,Xa=RegExp.prototype,em=function(s){var e=s.flags;return e===void 0&&!("flags"in Xa)&&!Kp(s,"flags")&&Xp(Xa,s)?Jp(Zp,s):e},Br=nt,tm=ns,im=Math.floor,Ys=Br("".charAt),sm=Br("".replace),qs=Br("".slice),rm=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,am=/\$([$&'`]|\d{1,2})/g,nm=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=am;return r!==void 0&&(r=tm(r),u=rm),sm(a,u,function(d,l){var c;switch(Ys(l,0)){case"$":return"$";case"&":return s;case"`":return qs(e,0,t);case"'":return qs(e,n);case"<":c=r[qs(l,1,-1)];break;default:var h=+l;if(h===0)return d;if(h>o){var f=im(h/10);return f===0?d:f<=o?i[f-1]===void 0?Ys(l,1):i[f-1]+Ys(l,1):d}c=i[h-1]}return c===void 0?"":c})},om=ds,dm=ot,Mr=nt,Za=br,um=Ce,lm=rs,cm=qp,Bt=jp,hm=as,fm=em,pm=nm,mm=He,vm=mm("replace"),Sm=TypeError,Eo=Mr("".indexOf),gm=Mr("".replace),en=Mr("".slice),bm=Math.max,tn=function(s,e,t){return t>s.length?-1:e===""?t:Eo(s,e,t)};om({target:"String",proto:!0},{replaceAll:function(e,t){var i=Za(this),r,a,n,o,u,d,l,c,h,f=0,v=0,b="";if(!lm(e)){if(r=cm(e),r&&(a=Bt(Za(fm(e))),!~Eo(a,"g")))throw Sm("`.replaceAll` does not allow non-global regexes");if(n=hm(e,vm),n)return dm(n,e,i,t);if(r)return gm(Bt(i),e,t)}for(o=Bt(i),u=Bt(e),d=um(t),d||(t=Bt(t)),l=u.length,c=bm(1,l),f=tn(o,u,0);f!==-1;)h=d?Bt(t(u,f,o)):pm(u,o,f,[],void 0,t),b+=en(o,v,f)+h,v=f+l,f=tn(o,u,f+c);return v<o.length&&(b+=en(o,v)),b}});var ym=fo,Tm=ym("String","replaceAll"),Em=Tm,$m=Em,Am=$m,wm=Am,sn=wm;const rn=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},Gs=(s,e)=>{let t=s;t=sn(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=sn(t,n,(o,u)=>ee(a)?o:ee(u)?a:a.padStart(parseInt(u,10),"0"))}return t},_m=(s,e)=>{var t,i,r,a,n,o,u,d,l,c,h,f,v,b,g,m,S,E,$,A,L,q,N,F,W,B,O,X,de,fe,P,H,ne,pe,ge,_e,Ye,xe,J,ye;const Oe=new DOMParser().parseFromString(s,"application/xml"),Xe={video:[],audio:[],text:[]},yt=Oe.children[0],ft=yt.getElementsByTagName("Period")[0],Dt=ft.children;let qe;const Qt=yt.getAttribute("mediaPresentationDuration"),Fr=ft.getAttribute("duration");if(Qt)qe=rn(Qt);else if(Fr){const Ne=rn(Fr);k(Ne)&&(qe=Ne)}let Ro=0;const hs=(i=(t=yt.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],Io=hs.includes(Zi.WEBM_AS_IN_FFMPEG)||hs.includes(Zi.WEBM_AS_IN_SPEC)?zt.WEBM:zt.MP4;for(const Ne of Dt){const yi=Ne.getAttribute("mimeType"),Do=Ne.getAttribute("codecs"),Ur=(r=Ne.getAttribute("contentType"))!==null&&r!==void 0?r:yi==null?void 0:yi.split("/")[0],Lo=(n=(a=Ne.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],Vr=Ne.querySelectorAll("Representation"),Co=Ne.querySelector("SegmentTemplate");if(Ur===Ee.TEXT){for(const ve of Vr){const pt=ve.getAttribute("id")||"",Ti=Ne.getAttribute("lang"),Lt=(d=(u=(o=ve.querySelector("BaseURL"))===null||o===void 0?void 0:o.textContent)===null||u===void 0?void 0:u.trim())!==null&&d!==void 0?d:"",fs=pt.includes("auto"),ps=new URL(Lt,e).toString();Xe[Ee.TEXT].push({id:pt,lang:Ti,kind:Ee.TEXT,url:ps,isAuto:fs})}continue}for(const ve of Vr){const pt=(l=ve.getAttribute("mimeType"))!==null&&l!==void 0?l:yi,Ti=(h=(c=ve.getAttribute("codecs"))!==null&&c!==void 0?c:Do)!==null&&h!==void 0?h:"",Lt=(v=(f=ve.getAttribute("contentType"))!==null&&f!==void 0?f:pt==null?void 0:pt.split("/")[0])!==null&&v!==void 0?v:Ur,fs=(g=(b=Ne.getAttribute("profiles"))===null||b===void 0?void 0:b.split(","))!==null&&g!==void 0?g:[],ps=parseInt((m=ve.getAttribute("width"))!==null&&m!==void 0?m:"",10),Hr=parseInt((S=ve.getAttribute("height"))!==null&&S!==void 0?S:"",10),Yr=parseInt((E=ve.getAttribute("bandwidth"))!==null&&E!==void 0?E:"",10)/1e3,qr=($=ve.getAttribute("frameRate"))!==null&&$!==void 0?$:"",xo=(A=ve.getAttribute("quality"))!==null&&A!==void 0?A:void 0,Oo=qr?Or(qr):void 0,No=(L=ve.getAttribute("id"))!==null&&L!==void 0?L:(Ro++).toString(10),Bo=Lt==="video"?`${Hr}p`:Lt==="audio"?`${Yr}Kbps`:Ti,Mo=`${No}@${Bo}`,Fo=(F=(N=(q=ve.querySelector("BaseURL"))===null||q===void 0?void 0:q.textContent)===null||N===void 0?void 0:N.trim())!==null&&F!==void 0?F:"",Gr=new URL(Fo,e).toString(),Uo=[...hs,...Lo,...fs];let ms;const Vo=ve.querySelector("SegmentBase"),Tt=(W=ve.querySelector("SegmentTemplate"))!==null&&W!==void 0?W:Co;if(Vo){const Jt=(O=(B=ve.querySelector("SegmentBase Initialization"))===null||B===void 0?void 0:B.getAttribute("range"))!==null&&O!==void 0?O:"",[Kt,Ss]=Jt.split("-").map(Et=>parseInt(Et,10)),Xt={from:Kt,to:Ss},Zt=(X=ve.querySelector("SegmentBase"))===null||X===void 0?void 0:X.getAttribute("indexRange"),[gs,Ei]=Zt?Zt.split("-").map(Et=>parseInt(Et,10)):[],ei=Zt?{from:gs,to:Ei}:void 0;ms={type:De.BYTE_RANGE,url:Gr,initRange:Xt,indexRange:ei}}else if(Tt){const Jt={representationId:(de=ve.getAttribute("id"))!==null&&de!==void 0?de:void 0,bandwidth:(fe=ve.getAttribute("bandwidth"))!==null&&fe!==void 0?fe:void 0},Kt=parseInt((P=Tt.getAttribute("timescale"))!==null&&P!==void 0?P:"",10),Ss=(H=Tt.getAttribute("initialization"))!==null&&H!==void 0?H:"",Xt=Tt.getAttribute("media"),Zt=(pe=parseInt((ne=Tt.getAttribute("startNumber"))!==null&&ne!==void 0?ne:"",10))!==null&&pe!==void 0?pe:1,gs=Gs(Ss,Jt);if(!Xt)throw new ReferenceError("No media attribute in SegmentTemplate");const Ei=(ge=Tt.querySelectorAll("SegmentTimeline S"))!==null&&ge!==void 0?ge:[],ei=[];if(Ei.length){let Et=Zt,$t=0;for(const ti of Ei){const Ct=parseInt((_e=ti.getAttribute("d"))!==null&&_e!==void 0?_e:"",10)*1e3,ii=parseInt((Ye=ti.getAttribute("r"))!==null&&Ye!==void 0?Ye:"",10)||0,si=(J=parseInt((xe=ti.getAttribute("t"))!==null&&xe!==void 0?xe:"",10))!==null&&J!==void 0?J:void 0;for(let zr=0;zr<ii+1;zr++){const Ho=Gs(Xt,{...Jt,segmentNumber:Et.toString(10),segmentTime:si.toString(10)}),Yo=si?si/Kt:$t;$t+=Ct/Kt;const qo=$t;Et++,ei.push({time:{from:Yo,to:qo},url:Ho})}}}else if(k(qe)){const $t=parseInt((ye=Tt.getAttribute("duration"))!==null&&ye!==void 0?ye:"",10)/Kt*1e3,ti=Math.ceil(qe/$t);let Ct=0;for(let ii=1;ii<ti;ii++){const si=Gs(Xt,{...Jt,segmentNumber:ii.toString(10),segmentTime:Ct.toString(10)});ei.push({time:{from:Ct,to:Ct+$t},url:si}),Ct+=$t}}ms={type:De.TEMPLATE,baseUrl:Gr,initUrl:gs,segments:ei}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Lt||!pt)continue;const vs={video:Ee.VIDEO,audio:Ee.AUDIO,text:Ee.TEXT}[Lt];vs&&Xe[vs].push({id:Mo,kind:vs,segmentReference:ms,profiles:Uo,duration:qe,bitrate:Yr,mime:pt,codecs:Ti,width:ps,height:Hr,fps:Oo,quality:xo})}}return{duration:qe,container:Io,representations:Xe}},km=["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 Pm=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new ae,this.state$=new ue(Ie.NONE),this.currentVideoRepresentation$=new T(void 0),this.error$=new x,this.lastConnectionType$=new T(void 0),this.lastConnectionReused$=new T(void 0),this.lastRequestFirstBytes$=new T(void 0),this.forceEnded$=new x,this.gapWatchdogStarted=!1,this.destroyController=new _t,this.initManifest=Fe(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:D.NETWORK,message:"Failed to load manifest",thrown:o}));if(!r)return;let a;try{a=_m(r!=null?r:"",i)}catch(o){this.error$.next({id:"ManifestParsing",category:D.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!a)return;const n=({kind:o,mime:u,codecs:d})=>{var l,c,h;return Boolean(((l=t.canPlayType)===null||l===void 0?void 0:l.call(t,u))&&((h=(c=window.MediaSource)===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0?void 0:h.call(c,`${u}; codecs="${d}"`))||o===Ee.TEXT)};this.manifest={...a,representations:vi(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:D.PARSER,message:"No playable video representations"})}.bind(this)),this.initRepresentations=Fe(this.destroyController.signal,async function*(t,i){R(this.manifest),R(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 Ka(Ee.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],k(i)&&(this.audioBufferManager=new Ka(Ee.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=V(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(_(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=V(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(_(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.subscription.add(V(this.forceEnded$,Qe({allBuffersFull:a,someBufferEnded:n}).pipe(te(({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:D.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:u})}})),this.subscription.add(V(...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)})),k(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&k(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=zo(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),a=>{this.error$.next({id:"GapWatchdog",category:D.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Fp({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initBuffer(){R(this.element),this.state$.setState(Ie.RUNNING),this.subscription.add(V(...km.map(e=>M(this.element,e)),M(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:D.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&&Sr(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){const i={[Ee.VIDEO]:this.videoBufferManager,[Ee.AUDIO]:this.audioBufferManager,[Ee.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),Sr(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(){var e;this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)===null||e===void 0?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}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 Rm=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a})=>{var n;const o=(n=a?gi(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}},Im=({id:s,bitrate:e})=>({id:s,bitrate:e}),Dm=({id:s,lang:e,url:t,isAuto:i})=>({id:s,url:t,isAuto:i,type:"internal",language:e}),Lm=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=Ze(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:Ze(s,-1)};class Cm{constructor(e){this.subscription=new ae,this.videoState=new ue(le.STOPPED),this.elementSize$=new T(void 0),this.textTracksManager=new Ke,this.videoTracks=[],this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new tp,this.textTracks=[],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===z.Requested&&(r==null?void 0:r.to)!==p.PAUSED&&t!==le.STOPPED&&i!==p.STOPPED&&this.seek(a.position,a.forcePrecise),i===p.STOPPED){t!==le.STOPPED&&(this.videoState.startTransitionTo(le.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(le.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}switch(t){case le.STOPPED:this.videoState.startTransitionTo(le.READY),this.prepare();return;case le.READY:i===p.PAUSED?(this.videoState.setState(le.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):i===p.PLAYING?(this.videoState.startTransitionTo(le.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.READY&&I(this.params.desiredState.playbackState,p.READY);return;case le.PLAYING:i===p.PAUSED?(this.videoState.startTransitionTo(le.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case le.PAUSED:i===p.PLAYING?(this.videoState.startTransitionTo(le.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return U(t)}}},this.params=e,this.video=lt(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Pm({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=ht(this.video),r=d=>{e.error$.next({id:"DashVKProvider",category:D.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(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.lastRequestFirstBytes$.pipe(te(k),be()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(It(this.video,t.isLooped,r)),this.subscription.add(ut(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(gt(this.video,t.playbackRate,i.playbackRateState$,r)),a(Ki(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(le.PLAYING),I(t.playbackState,p.PLAYING)},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(le.PAUSED),I(t.playbackState,p.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=[],this.textTracks=[];const c=this.player.getRepresentations();R(c,"Manifest not loaded or empty");const h=Array.from(c.audio).sort((g,m)=>m.bitrate-g.bitrate),f=Array.from(c.video).sort((g,m)=>m.bitrate-g.bitrate),v=Array.from(c.text);if(!this.params.tuning.isAudioDisabled)for(const g of h){const m=Im(g);m&&this.audioTracks.push({track:m,representation:g})}for(const g of f){const m=Rm(g);if(m){this.videoTracks.push({track:m,representation:g});const S=!this.params.tuning.isAudioDisabled&&Lm(h,f,g);S&&this.audioRepresentations.set(g.id,S)}}for(const g of v){const m=Dm(g);m&&this.textTracks.push({track:m,representation:g})}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:g})=>g)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:g})=>g)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:g})=>g));const b=this.selectVideoRepresentation();R(b),this.player.initRepresentations(b.id,(l=this.audioRepresentations.get(b.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:D.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(V(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(Ee.VIDEO,c.id).catch(n);const h=this.audioRepresentations.get(c.id);h&&this.player.switchRepresentation(Ee.AUDIO,h.id).catch(n)}},r)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(me(),_(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===p.READY),me());this.subscription.add(V(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===p.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(V(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===p.READY)));const u=V(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Re(["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:m}})=>m===u))===null||e===void 0?void 0:e.track,l=this.params.output.currentVideoTrack$.getValue(),c=wt(this.video.buffered,this.video.currentTime*1e3),h=o?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,f=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),b=Si(this.videoTracks.map(({track:m})=>m),{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:f,current:l,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),g=o?b!=null?b:d:d!=null?d:b;return g&&((n=this.videoTracks.find(({track:m})=>m===g))===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.player.destroy(),this.params.output.element$.next(void 0),ct(this.video)}playIfAllowed(){bt(this.video).then(e=>{e||(this.videoState.setState(le.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}}const xm=5e3,ze={};var K;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(K||(K={}));const oi=(s,e)=>new ts(t=>{const i=(r,a)=>t.next(a);return s.on(e,i),()=>s.off(e,i)});class Om{constructor(e){this.subscription=new ae,this.videoState=new ue(K.INITIALIZING),this.textTracksManager=new Ke,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!==K.INITIALIZING)switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===z.Requested&&this.seek(a.position),i){case p.STOPPED:switch(t){case K.STOPPED:break;case K.READY:case K.PLAYING:case K.PAUSED:this.stop();break;default:U(t)}break;case p.READY:switch(t){case K.STOPPED:this.prepare();break;case K.READY:case K.PLAYING:case K.PAUSED:break;default:U(t)}break;case p.PLAYING:switch(t){case K.PLAYING:break;case K.STOPPED:this.prepare();break;case K.READY:case K.PAUSED:this.playIfAllowed();break;default:U(t)}break;case p.PAUSED:switch(t){case K.PAUSED:break;case K.STOPPED:this.prepare();break;case K.READY:this.videoState.setState(K.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED);break;case K.PLAYING:this.pause();break;default:U(t)}break;default:U(i)}},this.video=lt(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(we(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)===null||e===void 0||e.detachMedia(),(t=this.hls)===null||t===void 0||t.destroy(),this.params.output.element$.next(void 0),ct(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:D.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),xm);import("hls.js").then(r=>{e||(ze.Hls=r.default,ze.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){R(ze.Hls,"hls.js not loaded"),this.hls=new ze.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(K.STOPPED)}subscribe(){R(ze.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:D.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=ht(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$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(It(this.video,e.isLooped,i)),this.subscription.add(ut(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(gt(this.video,e.playbackRate,r.playbackRateState$,i)),this.subscription.add(oi(this.hls,ze.Events.ERROR).subscribe(d=>{var l;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:D.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(K.PLAYING),I(e.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(K.PAUSED),I(e.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())===null||d===void 0?void 0:d.to)===K.READY&&this.videoState.setState(K.READY),this.videoState.getState()===K.PLAYING&&this.playIfAllowed()},i)),a(oi(this.hls,ze.Events.MANIFEST_PARSED).pipe(_(({levels:d})=>d.reduce((l,c)=>{var h,f;const v=c.name||c.height.toString(10),{width:b,height:g}=c,m=(f=gi((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:Rt({width:b,height:g});if(!m)return l;const S=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,E={id:v.toString(),quality:m,bitrate:c.bitrate/1e3,size:{width:b,height:g},fps:S};return this.trackLevels.set(v,{track:E,level:c}),l.push(E),l},[]))),t.availableVideoTracks$),a(oi(this.hls,ze.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){const l=[];for(const c of d.subtitleTracks){const h=c.name,f=c.attrs.URI||"",v=c.lang,b="internal",g=h.includes("auto");l.push({id:h,url:f,language:v,type:b,isAuto:g})}e.internalTextTracks.startTransitionTo(l)}}),a(oi(this.hls,ze.Events.LEVEL_LOADING).pipe(_(({url:d})=>we(d))),t.hostname$),this.subscription.add(Ue(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=oi(this.hls,ze.Events.LEVEL_SWITCHED).pipe(_(({level:d})=>n(this.hls.levels[d])));o.pipe(te(k)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Ue(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(ee(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),f=this.hls.currentLevel,v=this.hls.levels[f];!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=V(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Re(["init"])).pipe(Le(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(K.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(K.PLAYING),await bt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:t}))||(this.videoState.setState(K.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))}pause(){this.videoState.startTransitionTo(K.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(K.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0)}}const an="X-Playback-Duration";var nn=async s=>{const e=await qt(s,{method:"HEAD"});return e.headers.has(an)?parseInt(e.headers.get(an),10):void 0};const Nm=s=>{let e=null;if(s.QUALITY&&(e=gi(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},$o=async(s,e=s)=>{var t;const a=(await(await qt(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=vi(d[1].split(",").map(m=>m.split("="))),c=(t=l.QUALITY)!==null&&t!==void 0?t:`stream-${l.BANDWIDTH}`,h=Nm(l);let f;l.BANDWIDTH&&(f=parseInt(l.BANDWIDTH,10)/1e3||void 0),!f&&l["AVERAGE-BANDWIDTH"]&&(f=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const v=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0;let b;if(l.RESOLUTION){const[m,S]=l.RESOLUTION.split("x").map(E=>parseInt(E,10));m&&S&&(b={width:m,height:S})}const g=new URL(a[++o],e).toString();h&&n.push({id:c,quality:h,url:g,bandwidth:f,size:b,fps:v})}return n};var ie;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(ie||(ie={}));class Bm{constructor(e){var t;this.subscription=new ae,this.videoState=new ue(ie.STOPPED),this.textTracksManager=new Ke,this.manifests$=new T([]),this.liveOffset=new xr,this.manifestStartTime$=new T(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===p.STOPPED){r!==ie.STOPPED&&(this.videoState.startTransitionTo(ie.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ie.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(r===ie.STOPPED){this.videoState.startTransitionTo(ie.READY),this.prepare();return}if(o||u){const c=this.videoState.getState();this.videoState.setState(ie.CHANGING_MANIFEST),this.videoState.startTransitionTo(c),this.prepare(),l.state===z.None&&this.params.desiredState.seekState.setState({state:z.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==p.PAUSED&&l.state===z.Requested){this.videoState.startTransitionTo(ie.READY),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case ie.READY:a===p.READY?I(this.params.desiredState.playbackState,p.READY):a===p.PAUSED?(this.videoState.setState(ie.PAUSED),this.liveOffset.pause(),I(this.params.desiredState.playbackState,p.PAUSED)):a===p.PLAYING&&(this.videoState.startTransitionTo(ie.PLAYING),this.playIfAllowed());return;case ie.PLAYING:a===p.PAUSED?(this.videoState.startTransitionTo(ie.PAUSED),this.liveOffset.pause(),this.video.pause()):(n==null?void 0:n.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case ie.PAUSED:a===p.PLAYING?(this.videoState.startTransitionTo(ie.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)===p.PAUSED&&(I(this.params.desiredState.playbackState,p.PAUSED),this.liveOffset.pause());return;case ie.CHANGING_MANIFEST:break;default:return U(r)}},this.params=e,this.video=lt(e.container),this.params.output.element$.next(this.video);const i={id:"master",quality:re.INVARIANT,url:this.params.source.url};this.manifests$.next([i]),$o(Yt(this.params.source.url),this.params.source.url).then(r=>{this.manifests$.next([i,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:D.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(we(this.params.source.url)),this.maxSeekBackTime$=new T((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:r}=this.params.desiredState,a=i.getState(),n=r.getTransition(),o=(t=(e=n==null?void 0:n.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",u=this.manifests$.getValue();if(!u)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:D.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=ht(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$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(ut(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(gt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ie.PLAYING),I(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ie.PAUSED),I(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ie.READY&&this.videoState.setState(ie.READY),this.videoState.getState()===ie.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(me(),_(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&&k(d.to)){const c=d.to;this.params.desiredState.videoTrack.setState(c);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(we(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===ie.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===z.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(Qe({startTime:this.manifestStartTime$.pipe(te(k)),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=V(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,Re(["init"])).pipe(Le(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ct(this.video)}prepare(){const e=this.selectManifest();if(ee(e))return;const t=Yt(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),nn(t).then(i=>{var r;if(!ee(i))this.maxSeekBackTime$.next(i);else{const a=(r=this.params.source.maxSeekBackTime)!==null&&r!==void 0?r:this.maxSeekBackTime$.getValue();if(ee(a)||!isFinite(a))try{qt(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();nn(d).then(l=>{ee(l)||this.maxSeekBackTime$.next(l)})}})}catch(n){}}})}playIfAllowed(){bt(this.video).then(e=>{e||(this.videoState.setState(ie.PAUSED),this.liveOffset.pause(),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}var oe;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(oe||(oe={}));class Mm{constructor(e){this.subscription=new ae,this.videoState=new ue(oe.STOPPED),this.textTracksManager=new Ke,this.manifests$=new T([]),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===p.STOPPED){i!==oe.STOPPED&&(this.videoState.startTransitionTo(oe.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(oe.STOPPED),I(this.params.desiredState.playbackState,p.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===z.None&&this.params.desiredState.seekState.setState({state:z.Requested,position:c*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==p.PAUSED&&d.state===z.Requested&&this.seek(d.position),i){case oe.READY:r===p.READY?I(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(oe.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed());return;case oe.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(oe.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case oe.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;case oe.CHANGING_MANIFEST:break;default:return U(i)}},this.params=e,this.video=lt(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:re.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(we(this.params.source.url)),$o(this.params.source.url).then(i=>{this.manifests$.next([t,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:D.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:D.WTF,message:"HlsProvider internal logic error",thrown:o})},r=ht(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$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(It(this.video,t.isLooped,i)),this.subscription.add(ut(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(gt(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),I(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(oe.PAUSED),I(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===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&&k(d.to)){const c=d.to;this.params.desiredState.videoTrack.setState(c);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(we(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===oe.CHANGING_MANIFEST&&this.videoState.setState(u.to),o.state===z.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=V(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,Re(["init"])).pipe(Le(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ct(this.video)}prepare(){const e=this.selectManifest();ee(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){bt(this.video).then(e=>{e||(this.videoState.setState(oe.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}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 Fm{constructor(e){this.subscription=new ae,this.videoState=new ue(ce.STOPPED),this.trackUrls={},this.textTracksManager=new Ke,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(i===p.STOPPED){t!==ce.STOPPED&&(this.videoState.startTransitionTo(ce.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ce.STOPPED),I(this.params.desiredState.playbackState,p.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===z.None&&this.params.desiredState.seekState.setState({state:z.Requested,position:u*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!==p.PAUSED&&o.state===z.Requested&&this.seek(o.position),t){case ce.READY:i===p.READY?I(this.params.desiredState.playbackState,p.READY):i===p.PAUSED?(this.videoState.setState(ce.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):i===p.PLAYING&&(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed());return;case ce.PLAYING:i===p.PAUSED?(this.videoState.startTransitionTo(ce.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case ce.PAUSED:i===p.PLAYING?(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return U(t)}},this.params=e,this.video=lt(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:D.WTF,message:"MpegProvider internal logic error",thrown:o})},r=ht(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$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(It(this.video,t.isLooped,i)),this.subscription.add(ut(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(gt(this.video,t.playbackRate,r.playbackRateState$,i)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ce.PLAYING),I(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ce.PAUSED),I(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ce.READY&&this.videoState.setState(ce.READY);const u=this.params.desiredState.videoTrack.getTransition();u&&k(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=V(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Re(["init"])).pipe(Le(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ct(this.video)}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(we(r))}playIfAllowed(){bt(this.video).then(e=>{e||(this.videoState.setState(ce.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}const on=["stun:videostun.mycdn.me:80"],Um=1e3,Vm=3,zs=()=>null;class Hm{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:on}]};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:D.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),Um)}normalizeOptions(e={}){const t={stunServerList:on,maxRetryNumber:Vm,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var se;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(se||(se={}));class Ym{constructor(e){this.videoState=new ue(se.STOPPED),this.maxSeekBackTime$=new T(0),this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(i===p.STOPPED){t!==se.STOPPED&&(this.videoState.startTransitionTo(se.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(se.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===se.STOPPED){this.videoState.startTransitionTo(se.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case se.READY:i===p.PAUSED?(this.videoState.setState(se.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):i===p.PLAYING&&(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed());return;case se.PLAYING:i===p.PAUSED?(this.videoState.startTransitionTo(se.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case se.PAUSED:i===p.PLAYING?(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return U(t)}},this.subscription=new ae,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=lt(e.container),this.liveStreamClient=new Hm(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ct(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:D.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};V(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=ht(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)===se.READY&&this.videoState.setState(se.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(se.PAUSED)},i)).add(r.playing$.subscribe(()=>{this.videoState.setState(se.PLAYING)},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ut(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case se.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(p.STOPPED);break;case se.READY:break;case se.PAUSED:t.playbackState.setState(p.PAUSED);break;case se.PLAYING:t.playbackState.setState(p.PLAYING);break;default:return U(n.to)}},i)).add(V(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Re(["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(we(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:re.INVARIANT}),this.video.srcObject=e,I(this.params.desiredState.playbackState,p.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(se.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:D.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){bt(this.video).then(e=>{e||(this.videoState.setState(se.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class dn{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return Boolean(this.current.done)}}var qm=()=>{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,xi,Zs,Oi,er,Ni,tr,Bi,ir,Mi,sr,Fi,rr;const Ao=qm(),vt=document.createElement("video"),Gm='video/mp4; codecs="avc1.42000a,mp4a.40.2"',zm='video/mp4; codecs="hev1.1.6.L93.B0"',wo='video/webm; codecs="vp09.00.10.08"',_o='video/webm; codecs="av01.0.00M.08"',jm='audio/mp4; codecs="mp4a.40.2"',Wm='audio/webm; codecs="opus"',Be={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=vt.canPlayType)===null||Qs===void 0?void 0:Qs.call(vt,"application/x-mpegurl"))||((Js=vt.canPlayType)===null||Js===void 0?void 0:Js.call(vt,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection),ws:Boolean(window.WebSocket)},Pe={mp4:Boolean((Ks=vt.canPlayType)===null||Ks===void 0?void 0:Ks.call(vt,"video/mp4")),webm:Boolean((Xs=vt.canPlayType)===null||Xs===void 0?void 0:Xs.call(vt,"video/webm")),cmaf:!0},We={h264:Boolean((Zs=(xi=window.MediaSource)===null||xi===void 0?void 0:xi.isTypeSupported)===null||Zs===void 0?void 0:Zs.call(xi,Gm)),h265:Boolean((er=(Oi=window.MediaSource)===null||Oi===void 0?void 0:Oi.isTypeSupported)===null||er===void 0?void 0:er.call(Oi,zm)),vp9:Boolean((tr=(Ni=window.MediaSource)===null||Ni===void 0?void 0:Ni.isTypeSupported)===null||tr===void 0?void 0:tr.call(Ni,wo)),av1:Boolean((ir=(Bi=window.MediaSource)===null||Bi===void 0?void 0:Bi.isTypeSupported)===null||ir===void 0?void 0:ir.call(Bi,_o)),aac:Boolean((sr=(Mi=window.MediaSource)===null||Mi===void 0?void 0:Mi.isTypeSupported)===null||sr===void 0?void 0:sr.call(Mi,jm)),opus:Boolean((rr=(Fi=window.MediaSource)===null||Fi===void 0?void 0:Fi.isTypeSupported)===null||rr===void 0?void 0:rr.call(Fi,Wm))},Mt=(We.h264||We.h265)&&We.aac;var et;(function(s){s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient"})(et||(et={}));let At;const Qm=async()=>{if(!window.navigator.mediaCapabilities)return;const s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:_o}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:wo}})]);At={[y.DASH_WEBM_AV1]:e,[y.DASH_WEBM]:t}};try{Qm()}catch(s){console.error(s)}const cs=Be.hls&&Pe.mp4,Jm=()=>Object.keys(We).filter(s=>We[s]),Km=(s,e=!1)=>s.filter(t=>{switch(t){case y.DASH:return Be.mse&&Pe.mp4&&Mt;case y.DASH_SEP:return Be.mse&&Pe.mp4&&Mt;case y.DASH_WEBM:return Be.mse&&Pe.webm&&We.vp9&&We.opus;case y.DASH_WEBM_AV1:return Be.mse&&Pe.webm&&We.av1&&We.opus;case y.DASH_LIVE:return Be.mse&&Pe.mp4&&Mt;case y.DASH_LIVE_CMAF:return Be.mse&&Pe.mp4&&Mt&&Pe.cmaf;case y.DASH_ONDEMAND:return Be.mse&&Pe.mp4&&Mt;case y.HLS:case y.HLS_LIVE:case y.HLS_LIVE_CMAF:case y.HLS_ONDEMAND:return cs||e&&Be.mse&&Pe.mp4&&Mt;case y.MPEG:return Pe.mp4;case y.DASH_LIVE_WEBM:return!1;case y.WEB_RTC_LIVE:return Be.webrtc&&Be.ws&&We.h264&&(Pe.mp4||Pe.webm);default:return U(t)}}),ar=s=>{const e=y.DASH_WEBM,t=y.DASH_WEBM_AV1;switch(s){case et.VP9:return[e,t];case et.AV1:return[t,e];case et.NONE:return[];case et.SMOOTH:return At?At[t].smooth?[t,e]:At[e].smooth?[e,t]:[t,e]:[e,t];case et.POWER_EFFICIENT:return At?At[t].powerEfficient?[t,e]:At[e].powerEfficient?[e,t]:[t,e]:[e,t];default:U(s)}return[e,t]},Xm=(s=et.VP9)=>Ao?[y.MPEG,...ar(s),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND]:cs?[...ar(s),y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG,y.DASH]:[...ar(s),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG],Zm=()=>Ao?[y.HLS_LIVE,y.HLS_LIVE_CMAF,y.WEB_RTC_LIVE,y.DASH_LIVE,y.DASH_LIVE_CMAF]:cs?[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],un=s=>s?[y.HLS_LIVE]:[y.DASH_WEBM,y.DASH_WEBM_AV1,y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG];var ev=s=>new ts(e=>{const t=new ae,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(_(({from:d,to:l})=>`${d}-${l}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(_(({type:d})=>d!==void 0)),n=new x;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(d=>{o&&window.clearTimeout(o),d&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const ln={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},tv={cacheDuration:12e4},iv={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},sv={maxPausedTime:3e4},cn={maxPausedTime:3e4};class rv{constructor(e){this.current$=new T({type:void 0}),this.providerError$=new x,this.noAvailableProvidersError$=new x,this.providerOutput={position$:new T(0),duration$:new T(1/0),volume$:new T({muted:!1,volume:1}),currentVideoTrack$:new T(void 0),availableVideoTracks$:new T([]),availableAudioTracks$:new T([]),isAudioAvailable$:new T(!0),autoVideoTrackLimitingAvailable$:new T(!1),currentBuffer$:new T(void 0),isBuffering$:new T(!0),error$:new x,willSeekEvent$:new x,seekedEvent$:new x,loopedEvent$:new x,endedEvent$:new x,firstBytesEvent$:new x,firstFrameEvent$:new x,canplay$:new x,isLive$:new T(void 0),liveTime$:new T(void 0),availableTextTracks$:new T([]),currentTextTrack$:new T(void 0),hostname$:new T(void 0),httpConnectionType$:new T(void 0),httpConnectionReused$:new T(void 0),inPiP$:new T(!1),inFullscreen$:new T(!1),element$:new T(void 0)},this.subscription=new ae,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Km([...Zm(),...Xm(this.params.tuning.webmCodec)],this.params.tuning.useHlsJs).filter(o=>k(e.sources[o])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning;let a=[];i?a=[i]:r.length?a=[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:a=t,this.screenFormatsIterator=new dn(a);const n=[...un(!0),...un(!1)];this.chromecastFormatsIterator=new dn(n.filter(o=>k(e.sources[o])))}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(ee(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:D.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!==z.None;this.params.desiredState.seekState.setState({state:z.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 U(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 Ap({...n,source:o,config:tv})}case y.DASH_SEP:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return R(o),this.params.tuning.useDashJs?new Ga({...n,source:o,format:e,config:cn}):new Cm({...n,source:o})}case y.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return R(o),new Ga({...n,source:o,format:e,config:cn})}case y.HLS:case y.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return R(o),cs||!this.params.tuning.useHlsJs?new Mm({...n,source:o}):new Om({...n,source:o})}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return R(o),new Bm({...n,source:o,config:sv})}case y.MPEG:{const o=this.applyFailoverHost(t[e]);return R(o),new Fm({...n,source:o})}case y.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return R(o),new bp({...n,source:o,config:iv})}case y.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return R(o),new Ym({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 U(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 $f({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 U(e)}}skipFormat(e){switch(e){case $e.SCREEN:return this.screenFormatsIterator.next();case $e.CHROMECAST:return this.chromecastFormatsIterator.next();default:return U(e)}}handleNoFormatsError(e){switch(e){case $e.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case $e.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return U(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const 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 vi(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){const e=new ae;let t=!1,i=0;return e.add(V(this.providerOutput.error$,ev({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:ln.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(_(r=>({id:`ProviderHangup:${r}`,category:D.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(te(({to:a})=>a===p.PLAYING),be()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{const a=this.current$.getValue().destination;if(a===$e.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider($e.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=r.category===D.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),u=i<ln.providerErrorLimit;o&&(n&&t||!u)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):u?(i++,this.reinitProvider()):this.switchToNextProvider(a!=null?a:$e.SCREEN)}})),e}}const gr=(s,e,t)=>t*e+(1-t)*s,ko=(s,e)=>s.reduce((t,i)=>t+i,0)/e,av=(s,e,t,i)=>{let r=0,a=t;const n=ko(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};class Po{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new T(e.initial),this.debounced$=new T(e.initial);const i=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new je(`raw_${i}`),this.smoothedSeries$=new je(`smoothed_${i}`),this.reportedSeries$=new je(`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)&&(ee(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class nv extends Po{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=gr(this.slow,e,this.params.emaAlphaSlow),this.fast=gr(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class ov extends Po{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=ko(this.pastMeasures,this.takenMeasures);this.emaSmoothed=gr(this.emaSmoothed,e,this.params.emaAlpha);const i=av(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class hn{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new nv({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new ov({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}}const dv=5e3,fn="one_video_throughput",pn="one_video_rtt",rt=window.navigator.connection,mn=()=>{const s=rt==null?void 0:rt.downlink;if(k(s)&&s!==10)return s*1e3},vn=()=>{const s=rt==null?void 0:rt.rtt;if(k(s)&&s!==3e3)return s},Sn=(s,e,t)=>{const i=t*8,r=i/s;return i/(r+e)};class li{constructor(e){var t,i;this.subscription=new ae,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=li.load(fn)||(e.useBrowserEstimation?mn():void 0)||dv,a=(i=(t=li.load(pn))!==null&&t!==void 0?t:e.useBrowserEstimation?vn():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new T(r),this.rtt$=new T(a),this.rttAdjustedThroughput$=new T(Sn(r,a,e.rttPenaltyRequestSize)),this.throughput=hn.getSmoothedValue(r,-1,e),this.rtt=hn.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const u=mn();u&&this.throughput.next(u);const d=vn();k(d)&&this.rtt.next(d)};rt&&"onchange"in rt&&this.subscription.add(M(rt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{bs.set(fn,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{bs.set(pn,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Qe({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(_(({throughput:n,rtt:o})=>Sn(n,o,e.rttPenaltyRequestSize)),te(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 ae;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(M(e,"progress").pipe(be()).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(li.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=bs.get(e);if(k(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const gn={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5},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,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,webmCodec:et.VP9,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}},uv=s=>{const e={};for(const t of Object.keys(gn)){const i=gn[t],r=s[t];Array.isArray(i)&&Array.isArray(r)?t==="configName"?e[t]=[...r,...i]:e[t]=r:typeof i=="object"&&typeof r=="object"?e[t]={...i,...r}:e[t]=r!=null?r:i}return e};var lv=({seekState:s,position$:e})=>V(s.stateChangeEnded$.pipe(_(({to:t})=>{var i;return t.state===z.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),te(k)),e.pipe(te(()=>s.getState().state===z.None))),cv=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return R(e,`Wrong container or containerId {${s.container}}`),e};class Sv{constructor(e={configName:[]}){if(this.subscription=new ae,this.logger=new jo,this.isPlaybackStarted=!1,this.desiredState={playbackState:new ue(p.STOPPED),seekState:new ue({state:z.None}),volume:new ue({volume:1,muted:!1}),videoTrack:new ue(void 0),autoVideoTrackSwitching:new ue(!0),autoVideoTrackLimits:new ue({}),isLooped:new ue(!1),playbackRate:new ue(1),externalTextTracks:new ue([]),internalTextTracks:new ue([]),currentTextTrack:new ue(void 0),textTrackCuesSettings:new ue({})},this.info={playbackState$:new T(p.STOPPED),position$:new T(0),duration$:new T(1/0),muted$:new T(!1),volume$:new T(1),availableQualities$:new T([]),availableQualitiesFps$:new T({}),availableAudioTracks$:new T([]),isAudioAvailable$:new T(!0),currentQuality$:new T(void 0),isAutoQualityEnabled$:new T(!0),autoQualityLimitingAvailable$:new T(!1),autoQualityLimits$:new T({}),currentPlaybackRate$:new T(1),currentBuffer$:new T({start:0,end:0}),isBuffering$:new T(!0),isStalled$:new T(!1),isEnded$:new T(!1),isLooped$:new T(!1),isLive$:new T(void 0),atLiveEdge$:new T(void 0),liveTime$:new T(void 0),currentFormat$:new T(void 0),availableTextTracks$:new T([]),currentTextTrack$:new T(void 0),throughputEstimation$:new T(void 0),rttEstimation$:new T(void 0),videoBitrate$:new T(void 0),hostname$:new T(void 0),httpConnectionType$:new T(void 0),httpConnectionReused$:new T(void 0),surface$:new T(mt.NONE),chromecastState$:new T(Te.NOT_AVAILABLE),chromecastDeviceName$:new T(void 0),intrinsicVideoSize$:new T(void 0)},this.events={inited$:new x,ready$:new x,started$:new x,playing$:new x,paused$:new x,stopped$:new x,willStart$:new x,willResume$:new x,willPause$:new x,willStop$:new x,willDestruct$:new x,watchCoverageRecord$:new x,watchCoverageLive$:new x,managedError$:new x,fatalError$:new x,ended$:new x,looped$:new x,seeked$:new x,willSeek$:new x,firstBytes$:new x,firstFrame$:new x,canplay$:new x,log$:new x},this.experimental={element$:new T(void 0),tuningConfigName$:new T([]),enableDebugTelemetry$:new T(!1),dumpTelemetry:Xf},this.initLogs(),this.tuning=uv(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Xo({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new li(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{const a=Reflect.get(t,i,r);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const u=n.map(c=>JSON.stringify(c,(h,f)=>{const v=typeof f;return["number","string","boolean"].includes(v)?f:f===null?null:`<${v}>`})),d=`Player.${String(i)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:D.WTF,message:l,thrown:o}),o}}}})}initVideo(e){var t,i,r;return this.config=e,this.domContainer=cv(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new rv({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(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===p.STOPPED&&e.startTransitionTo(p.READY),this}play(){const e=this.desiredState.playbackState;return e.getState()!==p.PLAYING&&e.startTransitionTo(p.PLAYING),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==p.PAUSED&&e.startTransitionTo(p.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==p.STOPPED&&e.startTransitionTo(p.STOPPED),this}seekTime(e,t=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:z.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()===Te.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()===Te.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()}getExactTime(){R(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(ee(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===z.None?void 0:t.position;return k(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(V(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(te(({from:e})=>e===p.STOPPED),be()).subscribe(()=>{this.initedAt=he(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case p.READY:this.events.ready$.next();break;case p.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case p.PAUSED:this.events.paused$.next();break;case p.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case p.PAUSED:this.events.willPause$.next();break;case p.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case p.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===z.Requested?this.desiredState.seekState.setState({...n,state:z.Applying}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:D.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===z.Applying&&(this.desiredState.seekState.setState({state:z.None}),this.events.seeked$.next())})).add(e.current$.pipe(_(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(_(n=>n.destination),me()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(_(n=>n.map(({quality:o})=>o).sort((o,u)=>Qi(o)?1:Qi(u)?-1:Yi(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{const o={};for(const u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.hostname$.pipe(me()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(me()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(me()).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(_(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(Qe({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$}).pipe(_(({isLive:n,position:o})=>n&&o>-Wo),me()).subscribe(this.info.atLiveEdge$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(_(n=>n.muted),me()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(_(n=>n.volume),me()).subscribe(this.info.volume$)).add(lv({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(V(e.providerOutput.endedEvent$.pipe(Ht(!0)),e.providerOutput.seekedEvent$.pipe(Ht(!1))).pipe(me()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(_(n=>({id:n?`No${n}`:"NoProviders",category:D.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(be(),_(n=>n!=null?n:he()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(be(),_(()=>he()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(be(),_(()=>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 T(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new T(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(te(({to:n})=>n===p.PLAYING),be()).subscribe(()=>i.next(!1)));let r=0;const a=V(e.providerOutput.isBuffering$,t,i).pipe(_(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),me());this.subscription.add(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(V(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var o,u;const d=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(o=n==null?void 0:n.size)===null||o===void 0?void 0:o.width,height:(u=n==null?void 0:n.size)===null||u===void 0?void 0:u.height},{width:d==null?void 0:d.videoWidth,height:d==null?void 0:d.videoHeight})})),this.subscription.add(V(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),d=this.chromecastInitializer.castState$.getValue();let l;d===Te.CONNECTED?l=mt.SECOND_SCREEN:u?n?l=mt.PIP:o?l=mt.FULLSCREEN:l=mt.INLINE:l=mt.NONE,this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(_(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new ae;this.subscription.add(t),this.subscription.add(e.current$.pipe(me((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(te(i=>i.length>0),be()).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=Si(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(V(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),Kf(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Jf(i)),this.providerContainer.current$.subscribe(({type:i})=>Di("provider",i)),t.duration$.subscribe(i=>Di("duration",i)),t.availableVideoTracks$.pipe(te(i=>!!i.length),be()).subscribe(i=>Di("tracks",i)),this.events.fatalError$.subscribe(new je("fatalError")),this.events.managedError$.subscribe(new je("managedError")),t.position$.subscribe(new je("position")),t.currentVideoTrack$.pipe(_(i=>i==null?void 0:i.quality)).subscribe(new je("quality")),this.info.currentBuffer$.subscribe(new je("buffer")),t.isBuffering$.subscribe(new je("isBuffering"))].forEach(i=>this.subscription.add(i)),Di("codecs",Jm())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:D.DOM,message:String(r)})})};this.subscription.add(V(M(document,"visibilitychange"),M(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===p.PLAYING,n=Boolean(e)&&!(e!=null&&e.released);r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}}const gv=`@vkontakte/videoplayer-core@${Jo}`;export{Te as ChromecastState,ci as HttpConnectionType,Tv as Observable,p as PlaybackState,Sv as Player,gv as SDK_VERSION,Ev as Subject,$v as Subscription,mt as Surface,Jo as VERSION,Av as ValueSubject,y as VideoFormat,re as VideoQuality};
|
|
6
|
+
import{ValueSubject as T,Subject as x,Subscription as re,isNonNullable as _,ErrorCategory as D,isNullable as ee,fromEvent as M,assertNever as U,merge as V,tap as jr,map as k,observableFrom as _e,filterChanged as fe,assertNonNullable as R,debounce as Ie,getHighestQuality as jo,timeout as Wo,getCurrentBrowser as Zi,CurrentClientBrowser as gr,CurrentClientDevice as yn,combine as je,once as ge,mapTo as Vt,filter as te,now as ce,videoSizeToQuality as kt,isInvariantQuality as Yi,isHigher as Mi,isLower as Ss,isLowerOrEqual as Qo,isHigherOrEqual as Jo,Observable as es,VideoQuality as Be,videoQualityToHeight as Ko,abortable as Me,getExponentialDelay as Wr,interval as Xo,safeStorage as gs,Logger as Zo,ACTIVE_LIVE_VALID_DELAY as ed}from"@vkontakte/videoplayer-shared/es2018.esm.js";import{Observable as yv,Subject as Tv,Subscription as Ev,ValueSubject as $v,VideoQuality as Av}from"@vkontakte/videoplayer-shared/es2018.esm.js";import td from"lodash/debounce.js";const id="2.0.88";var p;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(p||(p={}));var y;(function(s){s.MPEG="MPEG",s.DASH="DASH",s.DASH_SEP="DASH_SEP",s.DASH_SEP_VK="DASH_SEP",s.DASH_WEBM="DASH_WEBM",s.DASH_WEBM_AV1="DASH_WEBM_AV1",s.DASH_WEBM_VK="DASH_WEBM",s.DASH_ONDEMAND="DASH_ONDEMAND",s.DASH_ONDEMAND_VK="DASH_ONDEMAND",s.DASH_LIVE="DASH_LIVE",s.DASH_LIVE_CMAF="DASH_LIVE_CMAF",s.DASH_LIVE_WEBM="DASH_LIVE_WEBM",s.HLS="HLS",s.HLS_ONDEMAND="HLS_ONDEMAND",s.HLS_JS="HLS",s.HLS_LIVE="HLS_LIVE",s.HLS_LIVE_CMAF="HLS_LIVE_CMAF",s.WEB_RTC_LIVE="WEB_RTC_LIVE"})(y||(y={}));var Ee;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(Ee||(Ee={}));var ye;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})(ye||(ye={}));var ui;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(ui||(ui={}));var z;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(z||(z={}));var ft;(function(s){s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip"})(ft||(ft={}));var sd=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 rd{constructor(e){var t;this.connection$=new T(void 0),this.castState$=new T(ye.NOT_AVAILABLE),this.errorEvent$=new x,this.realCastState$=new T(ye.NOT_AVAILABLE),this.subscription=new re,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const i="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${i}`}),e.isDisabled||!i)return;const r=_((t=window.chrome)===null||t===void 0?void 0:t.cast),a=Boolean(window.__onGCastApiAvailable);r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||sd("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:D.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();ee(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();ee(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 U(r.sessionState)}})).add(V(M(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(jr(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),k(r=>r.castState)),_e([i.getCastState()])).pipe(fe(),k(ad),jr(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===ye.CONNECTED,o=_(this.connection$.getValue());if(n&&!o){const u=i.getCurrentSession();R(u);const d=u.getCastDevice(),l=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(ee(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===ye.CONNECTED?_(this.connection$.getValue())?ye.CONNECTED:ye.AVAILABLE:r)}))}initializeCastApi(){var e;let t,i,r;try{t=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:i,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:D.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const ad=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return ye.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return ye.AVAILABLE;case cast.framework.CastState.CONNECTING:return ye.CONNECTING;case cast.framework.CastState.CONNECTED:return ye.CONNECTED;default:return U(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}},nd=st,ts=!nd(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),Tn=ts,En=Function.prototype,ar=En.call,od=Tn&&En.bind.bind(ar,ar),rt=Tn?od:function(s){return function(){return ar.apply(s,arguments)}},$n=rt,dd=$n({}.toString),ud=$n("".slice),is=function(s){return ud(dd(s),8,-1)},ld=rt,cd=st,hd=is,bs=Object,fd=ld("".split),pd=cd(function(){return!bs("z").propertyIsEnumerable(0)})?function(s){return hd(s)=="String"?fd(s,""):bs(s)}:bs,ss=function(s){return s==null},md=ss,vd=TypeError,br=function(s){if(md(s))throw vd("Can't call method on "+s);return s},Sd=pd,gd=br,ci=function(s){return Sd(gd(s))},bd=function(){},zt={},Ti=function(s){return s&&s.Math==Math&&s},We=Ti(typeof globalThis=="object"&&globalThis)||Ti(typeof window=="object"&&window)||Ti(typeof self=="object"&&self)||Ti(typeof Qr=="object"&&Qr)||function(){return this}()||Function("return this")(),nr=typeof document=="object"&&document.all,yd=typeof nr=="undefined"&&nr!==void 0,An={all:nr,IS_HTMLDDA:yd},wn=An,Td=wn.all,De=wn.IS_HTMLDDA?function(s){return typeof s=="function"||s===Td}:function(s){return typeof s=="function"},Ed=We,$d=De,Jr=Ed.WeakMap,Ad=$d(Jr)&&/native code/.test(String(Jr)),Kr=De,kn=An,wd=kn.all,_t=kn.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:Kr(s)||s===wd}:function(s){return typeof s=="object"?s!==null:Kr(s)},kd=st,mt=!kd(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),jt={},_d=We,Xr=_t,or=_d.document,Pd=Xr(or)&&Xr(or.createElement),_n=function(s){return Pd?or.createElement(s):{}},Rd=mt,Id=st,Dd=_n,Pn=!Rd&&!Id(function(){return Object.defineProperty(Dd("div"),"a",{get:function(){return 7}}).a!=7}),Ld=mt,Cd=st,Rn=Ld&&Cd(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),xd=_t,Od=String,Bd=TypeError,Pt=function(s){if(xd(s))return s;throw Bd(Od(s)+" is not an object")},Nd=ts,Ei=Function.prototype.call,at=Nd?Ei.bind(Ei):function(){return Ei.apply(Ei,arguments)},yr={},ys=yr,Ts=We,Md=De,Zr=function(s){return Md(s)?s:void 0},Tr=function(s,e){return arguments.length<2?Zr(ys[s])||Zr(Ts[s]):ys[s]&&ys[s][e]||Ts[s]&&Ts[s][e]},Fd=rt,Er=Fd({}.isPrototypeOf),Ud=typeof navigator!="undefined"&&String(navigator.userAgent)||"",In=We,Es=Ud,ea=In.process,ta=In.Deno,ia=ea&&ea.versions||ta&&ta.version,sa=ia&&ia.v8,Ne,qi;sa&&(Ne=sa.split("."),qi=Ne[0]>0&&Ne[0]<4?1:+(Ne[0]+Ne[1]));!qi&&Es&&(Ne=Es.match(/Edge\/(\d+)/),(!Ne||Ne[1]>=74)&&(Ne=Es.match(/Chrome\/(\d+)/),Ne&&(qi=+Ne[1])));var Vd=qi,ra=Vd,Hd=st,Dn=!!Object.getOwnPropertySymbols&&!Hd(function(){var s=Symbol();return!String(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&ra&&ra<41}),Yd=Dn,Ln=Yd&&!Symbol.sham&&typeof Symbol.iterator=="symbol",qd=Tr,Gd=De,zd=Er,jd=Ln,Wd=Object,Cn=jd?function(s){return typeof s=="symbol"}:function(s){var e=qd("Symbol");return Gd(e)&&zd(e.prototype,Wd(s))},Qd=String,$r=function(s){try{return Qd(s)}catch(e){return"Object"}},Jd=De,Kd=$r,Xd=TypeError,Ar=function(s){if(Jd(s))return s;throw Xd(Kd(s)+" is not a function")},Zd=Ar,eu=ss,rs=function(s,e){var t=s[e];return eu(t)?void 0:Zd(t)},$s=at,As=De,ws=_t,tu=TypeError,iu=function(s,e){var t,i;if(e==="string"&&As(t=s.toString)&&!ws(i=$s(t,s))||As(t=s.valueOf)&&!ws(i=$s(t,s))||e!=="string"&&As(t=s.toString)&&!ws(i=$s(t,s)))return i;throw tu("Can't convert object to primitive value")},Gi={},su={get exports(){return Gi},set exports(s){Gi=s}},ru=!0,aa=We,au=Object.defineProperty,nu=function(s,e){try{au(aa,s,{value:e,configurable:!0,writable:!0})}catch(t){aa[s]=e}return e},ou=We,du=nu,na="__core-js_shared__",uu=ou[na]||du(na,{}),xn=uu,oa=xn;(su.exports=function(s,e){return oa[s]||(oa[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 lu=br,cu=Object,as=function(s){return cu(lu(s))},hu=rt,fu=as,pu=hu({}.hasOwnProperty),nt=Object.hasOwn||function(e,t){return pu(fu(e),t)},mu=rt,vu=0,Su=Math.random(),gu=mu(1 .toString),On=function(s){return"Symbol("+(s===void 0?"":s)+")_"+gu(++vu+Su,36)},bu=We,yu=Gi,da=nt,Tu=On,Eu=Dn,$u=Ln,Mt=bu.Symbol,ks=yu("wks"),Au=$u?Mt.for||Mt:Mt&&Mt.withoutSetter||Tu,Ue=function(s){return da(ks,s)||(ks[s]=Eu&&da(Mt,s)?Mt[s]:Au("Symbol."+s)),ks[s]},wu=at,ua=_t,la=Cn,ku=rs,_u=iu,Pu=Ue,Ru=TypeError,Iu=Pu("toPrimitive"),Du=function(s,e){if(!ua(s)||la(s))return s;var t=ku(s,Iu),i;if(t){if(e===void 0&&(e="default"),i=wu(t,s,e),!ua(i)||la(i))return i;throw Ru("Can't convert object to primitive value")}return e===void 0&&(e="number"),_u(s,e)},Lu=Du,Cu=Cn,wr=function(s){var e=Lu(s,"string");return Cu(e)?e:e+""},xu=mt,Ou=Pn,Bu=Rn,$i=Pt,ca=wr,Nu=TypeError,_s=Object.defineProperty,Mu=Object.getOwnPropertyDescriptor,Ps="enumerable",Rs="configurable",Is="writable";jt.f=xu?Bu?function(e,t,i){if($i(e),t=ca(t),$i(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Is in i&&!i[Is]){var r=Mu(e,t);r&&r[Is]&&(e[t]=i.value,i={configurable:Rs in i?i[Rs]:r[Rs],enumerable:Ps in i?i[Ps]:r[Ps],writable:!1})}return _s(e,t,i)}:_s:function(e,t,i){if($i(e),t=ca(t),$i(i),Ou)try{return _s(e,t,i)}catch(r){}if("get"in i||"set"in i)throw Nu("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var ns=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},Fu=mt,Uu=jt,Vu=ns,hi=Fu?function(s,e,t){return Uu.f(s,e,Vu(1,t))}:function(s,e,t){return s[e]=t,s},Hu=Gi,Yu=On,ha=Hu("keys"),kr=function(s){return ha[s]||(ha[s]=Yu(s))},_r={},qu=Ad,Bn=We,Gu=_t,zu=hi,Ds=nt,Ls=xn,ju=kr,Wu=_r,fa="Object already initialized",dr=Bn.TypeError,Qu=Bn.WeakMap,zi,li,ji,Ju=function(s){return ji(s)?li(s):zi(s,{})},Ku=function(s){return function(e){var t;if(!Gu(e)||(t=li(e)).type!==s)throw dr("Incompatible receiver, "+s+" required");return t}};if(qu||Ls.state){var Ye=Ls.state||(Ls.state=new Qu);Ye.get=Ye.get,Ye.has=Ye.has,Ye.set=Ye.set,zi=function(s,e){if(Ye.has(s))throw dr(fa);return e.facade=s,Ye.set(s,e),e},li=function(s){return Ye.get(s)||{}},ji=function(s){return Ye.has(s)}}else{var Ct=ju("state");Wu[Ct]=!0,zi=function(s,e){if(Ds(s,Ct))throw dr(fa);return e.facade=s,zu(s,Ct,e),e},li=function(s){return Ds(s,Ct)?s[Ct]:{}},ji=function(s){return Ds(s,Ct)}}var Xu={set:zi,get:li,has:ji,enforce:Ju,getterFor:Ku},Zu=ts,Nn=Function.prototype,pa=Nn.apply,ma=Nn.call,el=typeof Reflect=="object"&&Reflect.apply||(Zu?ma.bind(pa):function(){return ma.apply(pa,arguments)}),tl=is,il=rt,Mn=function(s){if(tl(s)==="Function")return il(s)},Fn={},Un={},Vn={}.propertyIsEnumerable,Hn=Object.getOwnPropertyDescriptor,sl=Hn&&!Vn.call({1:2},1);Un.f=sl?function(e){var t=Hn(this,e);return!!t&&t.enumerable}:Vn;var rl=mt,al=at,nl=Un,ol=ns,dl=ci,ul=wr,ll=nt,cl=Pn,va=Object.getOwnPropertyDescriptor;Fn.f=rl?va:function(e,t){if(e=dl(e),t=ul(t),cl)try{return va(e,t)}catch(i){}if(ll(e,t))return ol(!al(nl.f,e,t),e[t])};var hl=st,fl=De,pl=/#|\.prototype\./,fi=function(s,e){var t=vl[ml(s)];return t==gl?!0:t==Sl?!1:fl(e)?hl(e):!!e},ml=fi.normalize=function(s){return String(s).replace(pl,".").toLowerCase()},vl=fi.data={},Sl=fi.NATIVE="N",gl=fi.POLYFILL="P",bl=fi,Sa=Mn,yl=Ar,Tl=ts,El=Sa(Sa.bind),Yn=function(s,e){return yl(s),e===void 0?s:Tl?El(s,e):function(){return s.apply(e,arguments)}},Ai=We,$l=el,Al=Mn,wl=De,kl=Fn.f,_l=bl,xt=yr,Pl=Yn,Ot=hi,ga=nt,Rl=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 $l(s,this,arguments)};return e.prototype=s.prototype,e},os=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?Ai:r?Ai[t]:(Ai[t]||{}).prototype,o=i?xt:xt[t]||Ot(xt,t,{})[t],u=o.prototype,d,l,c,h,f,v,g,b,m;for(h in e)d=_l(i?h:t+(r?".":"#")+h,s.forced),l=!d&&n&&ga(n,h),v=o[h],l&&(s.dontCallGetSet?(m=kl(n,h),g=m&&m.value):g=n[h]),f=l&&g?g:e[h],!(l&&typeof v==typeof f)&&(s.bind&&l?b=Pl(f,Ai):s.wrap&&l?b=Rl(f):a&&wl(f)?b=Al(f):b=f,(s.sham||f&&f.sham||v&&v.sham)&&Ot(b,"sham",!0),Ot(o,h,b),a&&(c=t+"Prototype",ga(xt,c)||Ot(xt,c,{}),Ot(xt[c],h,f),s.real&&u&&(d||!u[h])&&Ot(u,h,f)))},ur=mt,Il=nt,qn=Function.prototype,Dl=ur&&Object.getOwnPropertyDescriptor,Pr=Il(qn,"name"),Ll=Pr&&function(){}.name==="something",Cl=Pr&&(!ur||ur&&Dl(qn,"name").configurable),xl={EXISTS:Pr,PROPER:Ll,CONFIGURABLE:Cl},Gn={},Ol=Math.ceil,Bl=Math.floor,Nl=Math.trunc||function(e){var t=+e;return(t>0?Bl:Ol)(t)},Ml=Nl,Rr=function(s){var e=+s;return e!==e||e===0?0:Ml(e)},Fl=Rr,Ul=Math.max,Vl=Math.min,Hl=function(s,e){var t=Fl(s);return t<0?Ul(t+e,0):Vl(t,e)},Yl=Rr,ql=Math.min,Gl=function(s){return s>0?ql(Yl(s),9007199254740991):0},zl=Gl,Ir=function(s){return zl(s.length)},jl=ci,Wl=Hl,Ql=Ir,ba=function(s){return function(e,t,i){var r=jl(e),a=Ql(r),n=Wl(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}},Jl={includes:ba(!0),indexOf:ba(!1)},Kl=rt,Cs=nt,Xl=ci,Zl=Jl.indexOf,ec=_r,ya=Kl([].push),tc=function(s,e){var t=Xl(s),i=0,r=[],a;for(a in t)!Cs(ec,a)&&Cs(t,a)&&ya(r,a);for(;e.length>i;)Cs(t,a=e[i++])&&(~Zl(r,a)||ya(r,a));return r},zn=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],ic=tc,sc=zn,rc=Object.keys||function(e){return ic(e,sc)},ac=mt,nc=Rn,oc=jt,dc=Pt,uc=ci,lc=rc;Gn.f=ac&&!nc?Object.defineProperties:function(e,t){dc(e);for(var i=uc(t),r=lc(t),a=r.length,n=0,o;a>n;)oc.f(e,o=r[n++],i[o]);return e};var cc=Tr,hc=cc("document","documentElement"),fc=Pt,pc=Gn,Ta=zn,mc=_r,vc=hc,Sc=_n,gc=kr,Ea=">",$a="<",lr="prototype",cr="script",jn=gc("IE_PROTO"),xs=function(){},Wn=function(s){return $a+cr+Ea+s+$a+"/"+cr+Ea},Aa=function(s){s.write(Wn("")),s.close();var e=s.parentWindow.Object;return s=null,e},bc=function(){var s=Sc("iframe"),e="java"+cr+":",t;return s.style.display="none",vc.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Wn("document.F=Object")),t.close(),t.F},wi,Fi=function(){try{wi=new ActiveXObject("htmlfile")}catch(e){}Fi=typeof document!="undefined"?document.domain&&wi?Aa(wi):bc():Aa(wi);for(var s=Ta.length;s--;)delete Fi[lr][Ta[s]];return Fi()};mc[jn]=!0;var Qn=Object.create||function(e,t){var i;return e!==null?(xs[lr]=fc(e),i=new xs,xs[lr]=null,i[jn]=e):i=Fi(),t===void 0?i:pc.f(i,t)},yc=st,Tc=!yc(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),Ec=nt,$c=De,Ac=as,wc=kr,kc=Tc,wa=wc("IE_PROTO"),hr=Object,_c=hr.prototype,Jn=kc?hr.getPrototypeOf:function(s){var e=Ac(s);if(Ec(e,wa))return e[wa];var t=e.constructor;return $c(t)&&e instanceof t?t.prototype:e instanceof hr?_c:null},Pc=hi,Kn=function(s,e,t,i){return i&&i.enumerable?s[e]=t:Pc(s,e,t),s},Rc=st,Ic=De,Dc=_t,Lc=Qn,ka=Jn,Cc=Kn,xc=Ue,fr=xc("iterator"),Xn=!1,tt,Os,Bs;[].keys&&(Bs=[].keys(),"next"in Bs?(Os=ka(ka(Bs)),Os!==Object.prototype&&(tt=Os)):Xn=!0);var Oc=!Dc(tt)||Rc(function(){var s={};return tt[fr].call(s)!==s});Oc?tt={}:tt=Lc(tt);Ic(tt[fr])||Cc(tt,fr,function(){return this});var Zn={IteratorPrototype:tt,BUGGY_SAFARI_ITERATORS:Xn},Bc=Ue,Nc=Bc("toStringTag"),eo={};eo[Nc]="z";var Dr=String(eo)==="[object z]",Mc=Dr,Fc=De,Ui=is,Uc=Ue,Vc=Uc("toStringTag"),Hc=Object,Yc=Ui(function(){return arguments}())=="Arguments",qc=function(s,e){try{return s[e]}catch(t){}},ds=Mc?Ui:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=qc(e=Hc(s),Vc))=="string"?t:Yc?Ui(e):(i=Ui(e))=="Object"&&Fc(e.callee)?"Arguments":i},Gc=Dr,zc=ds,jc=Gc?{}.toString:function(){return"[object "+zc(this)+"]"},Wc=Dr,Qc=jt.f,Jc=hi,Kc=nt,Xc=jc,Zc=Ue,_a=Zc("toStringTag"),to=function(s,e,t,i){if(s){var r=t?s:s.prototype;Kc(r,_a)||Qc(r,_a,{configurable:!0,value:e}),i&&!Wc&&Jc(r,"toString",Xc)}},eh=Zn.IteratorPrototype,th=Qn,ih=ns,sh=to,rh=zt,ah=function(){return this},nh=function(s,e,t,i){var r=e+" Iterator";return s.prototype=th(eh,{next:ih(+!i,t)}),sh(s,r,!1,!0),rh[r]=ah,s},oh=os,dh=at,io=xl,uh=nh,lh=Jn,ch=to,Pa=Kn,hh=Ue,Ra=zt,so=Zn,fh=io.PROPER;io.CONFIGURABLE;so.IteratorPrototype;var ki=so.BUGGY_SAFARI_ITERATORS,Ns=hh("iterator"),Ia="keys",_i="values",Da="entries",ph=function(){return this},mh=function(s,e,t,i,r,a,n){uh(t,e,i);var o=function(m){if(m===r&&h)return h;if(!ki&&m in l)return l[m];switch(m){case Ia:return function(){return new t(this,m)};case _i:return function(){return new t(this,m)};case Da:return function(){return new t(this,m)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,l=s.prototype,c=l[Ns]||l["@@iterator"]||r&&l[r],h=!ki&&c||o(r),f=e=="Array"&&l.entries||c,v,g,b;if(f&&(v=lh(f.call(new s)),v!==Object.prototype&&v.next&&(ch(v,u,!0,!0),Ra[u]=ph)),fh&&r==_i&&c&&c.name!==_i&&(d=!0,h=function(){return dh(c,this)}),r)if(g={values:o(_i),keys:a?h:o(Ia),entries:o(Da)},n)for(b in g)(ki||d||!(b in l))&&Pa(l,b,g[b]);else oh({target:e,proto:!0,forced:ki||d},g);return n&&l[Ns]!==h&&Pa(l,Ns,h,{name:r}),Ra[e]=h,g},vh=function(s,e){return{value:s,done:e}},Sh=ci,Lr=bd,La=zt,ro=Xu,gh=jt.f,bh=mh,Pi=vh,yh=ru,Th=mt,ao="Array Iterator",Eh=ro.set,$h=ro.getterFor(ao);bh(Array,"Array",function(s,e){Eh(this,{type:ao,target:Sh(s),index:0,kind:e})},function(){var s=$h(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,Pi(void 0,!0)):t=="keys"?Pi(i,!1):t=="values"?Pi(e[i],!1):Pi([i,e[i]],!1)},"values");var Ca=La.Arguments=La.Array;Lr();Lr();Lr();if(!yh&&Th&&Ca.name!=="values")try{gh(Ca,"name",{value:"values"})}catch(s){}var Ah=Ue,wh=zt,kh=Ah("iterator"),_h=Array.prototype,Ph=function(s){return s!==void 0&&(wh.Array===s||_h[kh]===s)},Rh=ds,xa=rs,Ih=ss,Dh=zt,Lh=Ue,Ch=Lh("iterator"),no=function(s){if(!Ih(s))return xa(s,Ch)||xa(s,"@@iterator")||Dh[Rh(s)]},xh=at,Oh=Ar,Bh=Pt,Nh=$r,Mh=no,Fh=TypeError,Uh=function(s,e){var t=arguments.length<2?Mh(s):e;if(Oh(t))return Bh(xh(t,s));throw Fh(Nh(s)+" is not iterable")},Vh=at,Oa=Pt,Hh=rs,Yh=function(s,e,t){var i,r;Oa(s);try{if(i=Hh(s,"return"),!i){if(e==="throw")throw t;return t}i=Vh(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return Oa(i),t},qh=Yn,Gh=at,zh=Pt,jh=$r,Wh=Ph,Qh=Ir,Ba=Er,Jh=Uh,Kh=no,Na=Yh,Xh=TypeError,Vi=function(s,e){this.stopped=s,this.result=e},Ma=Vi.prototype,Zh=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=qh(e,i),d,l,c,h,f,v,g,b=function(S){return d&&Na(d,"normal",S),new Vi(!0,S)},m=function(S){return r?(zh(S),o?u(S[0],S[1],b):u(S[0],S[1])):o?u(S,b):u(S)};if(a)d=s.iterator;else if(n)d=s;else{if(l=Kh(s),!l)throw Xh(jh(s)+" is not iterable");if(Wh(l)){for(c=0,h=Qh(s);h>c;c++)if(f=m(s[c]),f&&Ba(Ma,f))return f;return new Vi(!1)}d=Jh(s,l)}for(v=a?s.next:d.next;!(g=Gh(v,d)).done;){try{f=m(g.value)}catch(S){Na(d,"throw",S)}if(typeof f=="object"&&f&&Ba(Ma,f))return f}return new Vi(!1)},ef=wr,tf=jt,sf=ns,rf=function(s,e,t){var i=ef(e);i in s?tf.f(s,i,sf(0,t)):s[i]=t},af=os,nf=Zh,of=rf;af({target:"Object",stat:!0},{fromEntries:function(e){var t={};return nf(e,function(i,r){of(t,i,r)},{AS_ENTRIES:!0}),t}});var df=yr,uf=df.Object.fromEntries,lf={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},cf=lf,hf=We,ff=ds,pf=hi,Fa=zt,mf=Ue,Ua=mf("toStringTag");for(var Ms in cf){var Va=hf[Ms],Fs=Va&&Va.prototype;Fs&&ff(Fs)!==Ua&&pf(Fs,Ua,Ms),Fa[Ms]=Fa.Array}var vf=uf,Sf=vf,gf=Sf,bf=gf,pi=bf,Ut;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(Ut||(Ut={}));var Ht=(s,e=0,t=Ut.OFFSET_P)=>{switch(t){case Ut.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Ut.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}default:U(t)}return s},I=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};class de{constructor(e){this.transitionStarted$=new x,this.transitionEnded$=new x,this.transitionUpdated$=new x,this.forceChanged$=new x,this.stateChangeStarted$=V(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=V(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 yf=s=>{switch(s){case y.MPEG:case y.DASH:case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.HLS:case y.HLS_ONDEMAND:return!1;case y.DASH_LIVE:case y.DASH_LIVE_CMAF:case y.HLS_LIVE:case y.HLS_LIVE_CMAF:case y.DASH_LIVE_WEBM:case y.WEB_RTC_LIVE:return!0;default:return U(s)}};var Y;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Y||(Y={}));const Tf=5,Ef=5,$f=500,Ha=7e3;class Af{constructor(e){this.subscription=new re,this.loadMediaTimeoutSubscription=new re,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===p.STOPPED){i!==Y.STOPPED&&(this.videoState.startTransitionTo(Y.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==p.PAUSED&&o.state===z.Requested&&i!==Y.STOPPED){this.seek(o.position/1e3);return}switch(a){case p.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:U(i)}break}case p.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:U(i)}break}case p.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:U(i)}break}default:U(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(yf(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new re;this.subscription.add(e),this.subscription.add(V(this.videoState.stateChangeStarted$.pipe(k(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(k(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 x;e.add(r.pipe(Ie($f)).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===z.Applying||Math.abs(o-a)>Tf)&&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<Ef&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),I(this.params.desiredState.playbackState,p.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:U(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=V(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,_e(["init"])).pipe(Ie(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),I(this.params.desiredState.playbackState,p.PAUSED)):(this.videoState.setState(Y.PLAYING),I(this.params.desiredState.playbackState,p.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:z.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===Y.PAUSED||e===Y.PLAYING)&&(this.videoState.setState(Y.PAUSED),I(this.params.desiredState.playbackState,p.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),I(this.params.desiredState.playbackState,p.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)===p.READY&&I(this.params.desiredState.playbackState,p.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=jo(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:case y.DASH_WEBM_AV1:{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=Ht(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:D.VIDEO_PIPELINE,message:l,thrown:c}),c}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return U(e)}const o=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,a);o.contentUrl=r,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return _(u)&&(o.metadata.title=u),_(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===z.Applying||i.state===z.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(Wo(Ha).subscribe(()=>a(`timeout(${Ha})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===z.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{const a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:D.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}class Ya{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 oo extends Ya{constructor(){super(),this.listeners||Ya.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 uo=class{constructor(){Object.defineProperty(this,"signal",{value:new oo,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&&(uo.prototype[Symbol.toStringTag]="AbortController",oo.prototype[Symbol.toStringTag]="AbortSignal");function lo(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 wf(s){typeof s=="function"&&(s={fetch:s});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!lo({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(d,l){let c;l&&l.signal&&(c=l.signal,delete l.signal);const h=new t(d,l);return c&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),h},a.prototype=t.prototype);const n=e;return{fetch:(u,d)=>{const l=a&&a.prototype.isPrototypeOf(u)?u.signal:d?d.signal:void 0;if(l){let c;try{c=new DOMException("Aborted","AbortError")}catch(f){c=new Error("Aborted"),c.name="AbortError"}if(l.aborted)return Promise.reject(c);const h=new Promise((f,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 us=lo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),co=us?wf({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Yt=us?co.fetch:window.fetch;us?co.Request:window.Request;const wt=us?uo:window.AbortController,si=s=>s.range?s.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class oi{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]=si(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(si),r=i[0][0];let a=i[0][1];for(let h=1;h<i.length&&a<this.params.minDataSize;h++){const f=i[h][1];f-r<=2*this.params.minDataSize&&(a=Math.max(a,f))}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 wt,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 f,v;throw(v=(f=this.params).onError)===null||v===void 0||v.call(f,{id:"BigRequestParsing",category:D.PARSER,message:"Error parsing response data",thrown:h}),h};return Yt(o,{signal:d}).then(h=>{var f,v,g;if(l.response=h,!h.ok||!h.body){this.onBigRequestError(l);return}const[b,m]=h.body.tee();(v=(f=this.params).onDownloadStream)===null||v===void 0||v.call(f,m);const S=b.getReader(),A=parseInt((g=h.headers.get("Content-Length"))!==null&&g!==void 0?g:"",10)||a-r+1;l.data=new ArrayBuffer(A);const E=new Uint8Array(l.data),$=async({done:L,value:q})=>{L?this.onBigRequestProgress(l):q&&(E.set(q,l.loaded),l.loaded+=q.byteLength,this.onBigRequestProgress(l),await(S==null?void 0:S.read().then($,oi.suppressStreamErrors).catch(c)))};S==null||S.read().then($,oi.suppressStreamErrors).catch(c)},oi.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,f,v;if(!this.activeRequests.has(e)||!a)return;const g=(o=this.dashJsRequestQueue.get(e))!==null&&o!==void 0?o:[];for(const b of g){const{request:m}=b,[S,A]=si(m),E=S>=t&&A<=t+r,$=t>=S&&t+r<A,L=a.slice(S-t,Math.min(A-t+1,r));if((E||$)&&(m.requestStartDate=(u=m.requestStartDate)!==null&&u!==void 0?u:new Date,m.firstByteDate=(d=m.firstByteDate)!==null&&d!==void 0?d:new Date,m.bytesLoaded=L.byteLength,m.bytesTotal=i-t),E){m.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[]).filter(B=>B!==b)),(c=b.success)===null||c===void 0||c.call(b,L,"",e);const q=n?Array.from(n.headers.entries()).map(([B,F])=>`${B}: ${F}`).join(`\r
|
|
7
|
+
`):"";(h=this.dashMetrics)===null||h===void 0||h.addHttpRequest(m,e,(f=n==null?void 0:n.status)!==null&&f!==void 0?f:200,q,[])}else $&&((v=b.progress)===null||v===void 0||v.call(b,{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:D.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]=si(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]=si(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 Wi{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(Wi.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;Wi.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const kf=(s,e)=>t=>({create:i=>{const r=s(t).create(i);return new Wi(r,e,i)}}),_f=(s,e)=>{const t=new oi(e);return s.extend("SchemeLoaderFactory",function(){const{parent:i}=this,r=i.getLoader;return{getLoader:a=>{const n=r(a);return kf(n,t)}}},!0),()=>t.destroy()};var Pf=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)},Rf=s=>{const e=new T(1/0),t=new x,i=new T(void 0),r=new T(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},u=l=>{var c,h,f,v,g;const b=pi(l.getAllResponseHeaders().trim().split(/[\n\r]+/).map(A=>A.split(": ")));if("x-playback-duration"in b||"x-playback-duration-millis"in b){const A=parseInt((c=l.getResponseHeader("X-Playback-Duration"))!==null&&c!==void 0?c:"",10),E=parseInt((h=l.getResponseHeader("X-Playback-Duration-Millis"))!==null&&h!==void 0?h:"",10),$=(f=E!=null?E:A*1e3)!==null&&f!==void 0?f:NaN;_($)&&!isNaN($)&&e.next($)}const m=(v=b["x-delivery-type"])!==null&&v!==void 0?v:ui.HTTP1,S=(g={1:!0,0:!1}[b["x-reused"]])!==null&&g!==void 0?g:void 0;i.next(m),r.next(S)},d=l=>{l.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return s.extend("XHRLoader",function(){const{parent:l}=this,c=l.load.bind(l);return{load:function(h){if(h.request.type==="MPD"){const f=h.onload,v=h.progress;h.onload=function(...g){return u(this),f(...g)},h.progress=function(...g){return d(this),v(...g)},o()}return c(h)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:i}},qt=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},If=s=>s.extend("RequestModifier",()=>({modifyRequestURL:qt}),!0),Df=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 Fe=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=s.getState(),o=e(),u=ee(r),d=new re;return r&&d.add(r.subscribe(l=>{const c=s.getState();i(l,c)&&s.setState(l)},a)),i(o,n)||(t(n),u&&s.setState(n)),d.add(s.stateChangeStarted$.subscribe(l=>{t(l.to),u&&s.setState(l.to)},a)),d},Rt=(s,e,t)=>Fe(e,()=>s.loop,i=>{_(i)&&(s.loop=i)},{onError:t}),ot=(s,e,t,i)=>Fe(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}),vt=(s,e,t,i)=>Fe(e,()=>s.playbackRate,r=>{_(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Lf=s=>["__",s.language,s.label].join("|"),Cf=(s,e)=>{if(s.id===e)return!0;const[t,i,r]=e.split("|");return s.language===i&&s.label===r};class Qe{constructor(){this.available$=new x,this.current$=new T(void 0),this.error$=new x,this.subscription=new re,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:D.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(Fe(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{_(a)&&this.setInternal(a)},{equal:(a,n)=>_(a)&&_(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(k(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Fe(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(k(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Fe(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(Fe(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(M(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();this.select(i)})),this.subscription.add(V(M(e,"addtrack"),M(e,"removetrack"),_e(["init"])).pipe(k(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),fe((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(V(M(e,"change"),_e(["init"])).pipe(k(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),k(i=>i&&this.htmlTextTrackToITextTrack(i).id),fe()).subscribe(this.current$));const t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(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 f=(d=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&d!==void 0?d:null;f&&f.length&&(this.applyCueSettings((c=(l=o.target)===null||l===void 0?void 0:l.cues)!==null&&c!==void 0?c:null),(h=o.target)===null||h===void 0||h.removeEventListener("cuechange",n))};(a=i.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(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){R(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Qe.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,r=e.id!==""?e.id:Lf(e),a=this.externalTracks.has(r),n=r.includes("auto");return a?{id:r,type:"external",isAuto:n,language:t,label:i,url:this.externalTracks.get(r).url}:{id:r,type:"internal",isAuto:n,language:t,label:i,url:this.internalTracks.get(r).url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){this.externalTracks.size===0&&(e.filter(({id:t})=>!this.internalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.internalTracks).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))_(e)&&Cf(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),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){R(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const Cr=s=>{s.removeAttribute("src"),s.load()},xf=s=>{try{s.pause(),s.playbackRate=0,Cr(s),s.remove()}catch(e){console.error(e)}};class Of{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}}const pr=window.WeakMap?new WeakMap:new Of,dt=s=>{let e=s.querySelector("video");const t=Boolean(e);return e?Cr(e):(e=document.createElement("video"),s.appendChild(e)),pr.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},ut=s=>{const e=pr.get(s);pr.delete(s),e?Cr(s):xf(s)};class xr{constructor(){this.pausedTime=0,this.streamOffset=0,this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}}const ho=s=>{var e;let t=s;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},qa=s=>{const e=ho(s);return Boolean(e&&e.fullscreenElement&&e.fullscreenElement===s)},Bf=s=>{const e=ho(s);return Boolean(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)},mr=3;class Nf{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<mr&&(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||mr))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 fo=(s,e,t=mr)=>{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 Mf=1e3,Ff=s=>{const e=Zi();return e.browser===gr.Chrome&&e.device===yn.Android?!0:s.webkitAudioDecodedByteCount!==void 0?!!s.webkitAudioDecodedByteCount:s.mozHasAudio!==void 0?s.mozHasAudio:s.audioTracks?!!s.audioTracks.length:!0},lt=s=>{const e=E=>M(s,E).pipe(Vt(void 0)),i=V(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(E=>M(s,E))).pipe(k(E=>E.type==="ended"?s.readyState<2:s.readyState<3),fe()),r=V(M(s,"progress"),M(s,"timeupdate")).pipe(k(()=>fo(s.buffered,s.currentTime))),n=Zi().browser===gr.Safari?je({play:e("play").pipe(ge()),playing:e("playing")}).pipe(Vt(void 0)):e("playing"),o=M(s,"playing").pipe(Ie(Mf),k(()=>Ff(s))),u=M(s,"volumechange").pipe(k(()=>({muted:s.muted,volume:s.volume}))),d=M(s,"ratechange").pipe(k(()=>s.playbackRate)),l=M(s,"error").pipe(te(()=>Boolean(s.error||s.played.length)),k(()=>{var E;const $=s.error;return{id:$?`MediaError#${$.code}`:"HtmlVideoError",category:D.VIDEO_PIPELINE,message:$?$.message:"Error event from HTML video element",thrown:(E=s.error)!==null&&E!==void 0?E:void 0}})),c=M(s,"timeupdate").pipe(k(()=>s.currentTime)),h=new x,f=.3;let v;c.subscribe(E=>{s.loop&&_(v)&&_(E)&&v>=s.duration-f&&E<=f&&h.next(v),v=E});const g=M(s,"enterpictureinpicture"),b=M(s,"leavepictureinpicture"),m=new T(Bf(s));g.subscribe(()=>m.next(!0)),b.subscribe(()=>m.next(!1));const S=new T(qa(s));return M(s,"fullscreenchange").pipe(k(()=>qa(s))).subscribe(S),{playing$:n,pause$:e("pause").pipe(te(()=>!s.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:h,error$:l,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:M(s,"durationchange").pipe(k(()=>s.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:u,isAudioAvailable$:o,playbackRateState$:d,inPiP$:m,inFullscreen$:S}},Or=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var Uf=os,Vf=as,Hf=Ir,Yf=Rr;Uf({target:"Array",proto:!0},{at:function(e){var t=Vf(this),i=Hf(t),r=Yf(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});var qf=Tr,po=qf,Gf=po,zf=Gf("Array","at"),jf=zf,Wf=jf,Qf=Wf,Jf=Qf,Ke=Jf;let Br=!1,Ze={};const Kf=s=>{Br=s},Xf=()=>{Ze={}},Zf=s=>{s(Ze)},Ri=(s,e)=>{var t;Br&&(Ze.meta=(t=Ze.meta)!==null&&t!==void 0?t:{},Ze.meta[s]=e)};class Ge{constructor(e){this.name=e}next(e){var t,i;if(!Br)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 ep=new Ge("best_bitrate"),tp=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class ip{constructor(){this.history={}}recordSelection(e){this.history[e.id]=ce()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const mi=(s,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:d})=>{var l,c,h,f;const v=i.usePixelRatio&&(l=window.devicePixelRatio)!==null&&l!==void 0?l:1,g=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*v*i.containerSizeFactor,height:e.height*v*i.containerSizeFactor},b=g&&kt(g),m=i.considerPlaybackRate&&_(o)?o:1,S=s.filter(N=>!Yi(N.quality)).sort((N,O)=>Mi(N.quality,O.quality)?-1:1),A=(c=Ke(S,-1))===null||c===void 0?void 0:c.quality,E=(h=Ke(S,0))===null||h===void 0?void 0:h.quality,$=ee(r)||_(r.min)&&_(r.max)&&Ss(r.max,r.min)||_(r.min)&&E&&Mi(r.min,E)||_(r.max)&&A&&Ss(r.max,A),L=m*tp(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),B=S.filter(N=>{const O=b?Ss(N.quality,b):!0,X=_(t)&&isFinite(t)&&_(N.bitrate)?t-a>=N.bitrate*L:!0,oe=i.lazyQualitySwitch&&_(i.minBufferToSwitchUp)&&u&&!Yi(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&Mi(N.quality,u.quality),ve=$||(ee(r.max)||Qo(N.quality,r.max))&&(ee(r.min)||Jo(N.quality,r.min));return O&&X&&!oe&&ve})[0];B&&B.bitrate&&ep.next(B.bitrate);const F=(f=B!=null?B:S[Math.ceil((S.length-1)/2)])!==null&&f!==void 0?f:s[0],W=F&&d&&d.history[F.id]&&ce()-d.history[F.id]<=i.trackCooldown&&(!d.last||F.id!==d.last.id);if(F!=null&&F.id&&d&&!W&&d.recordSelection(F),W&&(d!=null&&d.last)){const N=d.last;return d==null||d.recordSwitch(N),N}return d==null||d.recordSwitch(F),F};var Ae=s=>new URL(s).hostname;const sp=300,Qi=(s,e=sp)=>new es(t=>{const{width:i,height:r}=s.getBoundingClientRect();if(t.next({width:i,height:r}),!window.ResizeObserver)return;const a=new ResizeObserver(td(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()}),rp=5e3,ri={};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 me=(s,e)=>new es(t=>{const i=r=>t.next(r);return s.on(e,i),()=>s.off(e,i)});class Ga{constructor(e){this.subscription=new re,this.videoState=new de(j.DOWNLOADING_LIB),this.textTracksManager=new Qe,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new T(void 0),this.maxSeekBackTime$=new T(1/0),this.availableFrom$=new T(void 0),this.elementSize$=new T(void 0),this.liveOffset=new xr,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)!==p.PAUSED&&a.state===z.Requested&&t!==j.STOPPED&&i!==p.STOPPED&&(n?this.seek(a.position-this.liveOffset.getTotalPausedTime()):this.seek(a.position)),i){case p.STOPPED:{switch(t){case j.STOPPED:break;case j.PLAYING:case j.PAUSED:case j.READY:this.stop();break;default:U(t)}break}case p.READY:{switch(t){case j.STOPPED:this.prepare();break;case j.PLAYING:case j.PAUSED:case j.READY:break;default:U(t)}break}case p.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:U(t)}break}case p.PAUSED:{switch(t){case j.PLAYING:this.pause(),this.liveOffset.pause();break;case j.PAUSED:break;case j.READY:this.videoState.setState(j.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED);break;case j.STOPPED:this.prepare();break;default:U(t)}break}default:U(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:D.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"),rp);import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(ri.MediaPlayer=r.MediaPlayer,ri.Debug=r.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){R(ri.MediaPlayer,"dashjs not loaded"),R(ri.Debug,"dashjs not loaded"),this.player=ri.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?Or(t.frameRate+""):void 0),!0)),(this.params.format===y.DASH_WEBM||this.params.format===y.DASH_WEBM_AV1)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=_f(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&&Df(this.player),Pf(this.player),this.params.tuning.requestQuick&&If(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(j.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=m=>{e.error$.next({id:"DashIFProvider",category:D.WTF,message:"DashIFProvider internal logic error",thrown:m})},r=(m,S)=>this.subscription.add(m.subscribe(S,i));r(Qi(this.video),this.elementSize$),r(me(this.player,"error").pipe(k(m=>{const S=typeof m.error=="object"?m.error.code:m.error,A=typeof m.error=="object"?m.error.message:void 0;return{id:`DashJS#${S}`,message:A}})),e.error$),r(me(this.player,"playbackError").pipe(k(m=>({id:"DashJSPlayback",message:m.error}))),e.error$);const a=me(this.player,"qualityChangeRendered").pipe(te(({mediaType:m})=>m==="video"),k(({newQuality:m})=>{var S;return(S=this.videoTracks.find(({bitrateInfo:A})=>A.qualityIndex===m))===null||S===void 0?void 0:S.track}));a.pipe(te(_)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(te(({to:m})=>m===j.STREAM_INITIALIZED),ge()).subscribe(()=>{this.subscription.add(Fe(t.videoTrack,()=>{var m,S;const A=this.player.getQualityFor("video");return(S=(m=this.videoTracks.find(({bitrateInfo:E})=>E.qualityIndex===A))===null||m===void 0?void 0:m.track)===null||S===void 0?void 0:S.id},m=>{var S;if(ee(m))return;const A=(S=this.videoTracks.find(({track:E})=>E.id===m))===null||S===void 0?void 0:S.bitrateInfo;A&&this.player.setQualityFor("video",A.qualityIndex)},{changed$:a.pipe(k(m=>m==null?void 0:m.id)),onError:i}))},i)),this.subscription.add(Fe(t.autoVideoTrackSwitching,()=>{var m,S,A;return(A=(S=(m=this.player.getSettings().streaming)===null||m===void 0?void 0:m.abr)===null||S===void 0?void 0:S.autoSwitchBitrate)===null||A===void 0?void 0:A.video},m=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:m}}}}),{onError:i})),r(me(this.player,"bufferStateChanged").pipe(te(({mediaType:m})=>m==="video"),k(({state:m})=>m==="bufferStalled")),e.isBuffering$),r(me(this.player,"fragmentLoadingStarted"),({mediaType:m,request:{url:S}})=>{var A,E;const $=this.player.getDashMetrics(),L=$.getLatestFragmentRequestHeaderValueByID(m,"X-Reused"),q=(A=$.getLatestFragmentRequestHeaderValueByID(m,"X-Delivery-Type"))!==null&&A!==void 0?A:ui.HTTP1,B=(E={1:!0,0:!1}[L])!==null&&E!==void 0?E:void 0;this.params.output.httpConnectionType$.next(q),this.params.output.httpConnectionReused$.next(B),e.hostname$.next(Ae(S))}),r(me(this.player,"streamInitialized"),({streamInfo:{duration:m,manifestInfo:{isDynamic:S,availableFrom:A}}})=>{this.isLive$.next(S),this.availableFrom$.next(A.getTime()),S||e.duration$.next(m),this.videoTracks=[];const E=this.player.getQualityFor("video");let $;for(const L of this.player.getBitrateInfoListFor("video")){const q=L.qualityIndex.toString(10),B=kt(L),F=L.bitrate/1e3,W={width:L.width,height:L.height},N=this.frameRatesByFrameHeight[L.height];if(B){const O={id:q,quality:B,bitrate:F,size:W,fps:N};this.videoTracks.push({track:O,bitrateInfo:L}),L.qualityIndex===E&&($=O)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:L})=>L)),$&&e.currentVideoTrack$.next($),this.videoState.setState(j.STREAM_INITIALIZED),this.videoState.startTransitionTo(j.READY)}),r(me(this.player,"fragmentLoadingCompleted"),({request:m})=>{if(!m.requestEndDate||!m.firstByteDate||!m.bytesLoaded)return;const S=m.requestEndDate.getTime()-m.firstByteDate.getTime(),A=m.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(A,S)}),r(V(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const m=this.params.dependencies.throughputEstimator.throughput$.getValue(),S=mi(this.videoTracks.map(({track:E})=>E),{container:this.elementSize$.getValue(),throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),A=this.videoTracks.find(({track:E})=>E===S);A!=null&&A.bitrateInfo&&this.player.setQualityFor("video",A==null?void 0:A.bitrateInfo.qualityIndex,!1)}),r(je({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(te(_))}).pipe(te(({isLive:m})=>m),k(({maxSeekBackTime:m})=>-m/1e3)),this.params.output.duration$);const n=me(this.player,"playbackTimeUpdated").pipe(k(({time:m})=>m!=null?m:0));r(je({availableFrom:this.availableFrom$.pipe(te(_)),currentTime:n}),({availableFrom:m,currentTime:S})=>this.params.output.liveTime$.next(m+S*1e3)),r(n.pipe(te(()=>this.isLive$.getValue()===!1)),e.position$),r(me(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),r(me(this.player,"playbackEnded"),e.endedEvent$),r(me(this.player,"playbackProgress").pipe(k(()=>fo(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(me(this.player,"playbackPlaying"),()=>{this.videoState.setState(j.PLAYING),I(t.playbackState,p.PLAYING)}),r(me(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(j.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(me(this.player,"playbackPaused"),()=>{this.videoState.setState(j.PAUSED),I(t.playbackState,p.PAUSED)}),r(me(this.player,"canPlay"),()=>{var m;((m=this.videoState.getTransition())===null||m===void 0?void 0:m.to)===j.READY&&this.videoState.setState(j.READY)}),r(this.isLive$,e.isLive$),r(Qi(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=V(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,_e(["init"])).pipe(Ie(0));r(o,this.syncPlayback);const{playbackDuration$:u,ping$:d,connectionType$:l,connectionReused$:c}=Rf(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(me(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(je({isLive:this.isLive$,isShort:e.duration$.pipe(k(m=>m<60))}),({isLive:m,isShort:S})=>{const A=!m&&S;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:A}}})}),r(n.pipe(te(m=>m>this.params.tuning.insufficientBufferRuleMargin),ge()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(me(this.player,"manifestLoaded").pipe(ge()).subscribe(()=>{this.subscription.add(me(this.player,"playbackPlaying").pipe(ge(),Vt(void 0)).subscribe(e.firstFrameEvent$,i))},i)),r(me(this.player,"manifestLoaded"),m=>{var S,A,E,$,L,q,B;if(!((A=(S=m.data)===null||S===void 0?void 0:S.Period)===null||A===void 0)&&A.AdaptationSet){const F=[];for(const W of($=(E=m.data)===null||E===void 0?void 0:E.Period)===null||$===void 0?void 0:$.AdaptationSet)if(W.contentType==="text"){const N=(L=W.Representation)===null||L===void 0?void 0:L.id,O=new URL((q=W.Representation)===null||q===void 0?void 0:q.BaseURL,(B=m.data)===null||B===void 0?void 0:B.baseUri).toString(),X="internal",oe=W.lang;F.push({id:N,url:O,type:X,language:oe})}t.internalTextTracks.startTransitionTo(F)}}),this.subscription.add(Rt(this.video,t.isLooped,i));const{volumeState$:h,looped$:f,playbackRateState$:v,inPiP$:g,inFullscreen$:b}=lt(this.video);this.subscription.add(ot(this.video,t.volume,h,i)),this.subscription.add(h.subscribe(e.volume$,i)),this.subscription.add(f.subscribe(e.loopedEvent$)),this.subscription.add(vt(this.video,t.playbackRate,v,i)),this.subscription.add(g.subscribe(e.inPiP$)),this.subscription.add(b.subscribe(e.inFullscreen$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(j.STOPPED),I(this.params.desiredState.playbackState,p.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=Ht(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Ut.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){}ut(this.video),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var vi=s=>{switch(s){case"mobile":return Be.Q_144P;case"lowest":return Be.Q_240P;case"low":return Be.Q_360P;case"sd":case"medium":return Be.Q_480P;case"hd":case"high":return Be.Q_720P;case"fullhd":case"full":return Be.Q_1080P;case"quadhd":case"quad":return Be.Q_1440P;case"ultrahd":case"ultra":return Be.Q_2160P}};const za=s=>{if(s instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(s.message))throw s;return!(s instanceof DOMException&&(s.code===20||s.name==="AbortError"))};var St=async s=>{const e=s.muted;try{await s.play()}catch(t){if(!za(t))return!1;if(e)return console.warn(t),!1;s.muted=!0;try{await s.play()}catch(i){return za(i)&&(s.muted=!1,console.warn(i)),!1}}return!0};function $e(){return ce()}function mo(s){return $e()-s}function ja(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 ap(s,e,t){const i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Hi(s,e,t,i){const r=window.XMLHttpRequest;let a,n,o,u=!1,d=0,l,c,h=!1,f="arraybuffer",v=7e3,g=2e3,b=()=>{if(u)return;R(l);const O=mo(l);let X;if(O<g){X=g-O,setTimeout(b,X);return}g*=2,g>v&&(g=v),n&&n.abort(),n=new r,L()};const m=O=>(a=O,N),S=O=>(c=O,N),A=()=>(f="json",N),E=()=>{if(!u){if(--d>=0){b(),i&&i();return}u=!0,c&&c(),t&&t()}},$=O=>(h=O,N),L=()=>{l=$e(),n=new r,n.open("get",s);let O=0,X,oe=0;const ve=()=>(R(l),Math.max(l,Math.max(X||0,oe||0)));if(a&&n.addEventListener("progress",P=>{const H=$e();a.updateChunk&&P.loaded>O&&(a.updateChunk(ve(),P.loaded-O),O=P.loaded,X=H)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>E())),n.addEventListener("load",()=>{if(u)return;R(n);const P=n.status;if(P>=200&&P<300){if(n.response.byteLength&&a){const H=n.response.byteLength-O;H&&a.updateChunk&&a.updateChunk(ve(),H)}c&&c(),n&&e(n.response)}else E()}),n.addEventListener("error",()=>{E()}),h){const P=()=>{R(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(oe=$e(),n.removeEventListener("readystatechange",P))};n.addEventListener("readystatechange",P)}return n.responseType=f,n.send(),N},N={withBitrateReporting:m,withParallel:$,withJSONResponse:A,withRetryCount:O=>(d=O,N),withRetryInterval:(O,X)=>(_(O)&&(g=O),_(X)&&(v=X),N),withTimeout:O=>(o=O,N),withFinally:S,send:L,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return N}const np=100,op=2e3,dp=500;let up=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-dp;if(t-e>op){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>np&&(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 lp{constructor(e,t,i,r,a){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const i=$e(),r=u=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=u,e._errorCB?e._errorCB(u):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=u=>{e._complete=1,e._responseData=u,e._downloadTime=$e()-i,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(u,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Hi(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=$e()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=$e();if(Object.keys(this.activeRequests).length>=e)return!1;const i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,r){const a={};return a.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=i,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),i(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=i,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Ii=1e4,Di=3,cp=300,hp=2e3,fp=6e4,pp=10,mp=1,vp=500;class Sp{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 up(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ja(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=ja(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=()=>{ap(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 lp(Di,Ii,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,playerCallback:r}=this.params;let a=!1,n=null,o=null,u=null,d=null,l=!1;const c=()=>{const E=a&&(!l||l===this.rep);return E||t("Not running!"),E},h=(E,$,L)=>{u&&u.abort(),u=Hi(this.urlResolver.resolve(E,!1),$,L,()=>this._retryCallback()).withTimeout(Ii).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Di).withFinally(()=>{u=null}).send()},f=(E,$,L)=>{R(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),$,L,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},v=E=>{const $=i.playbackRate;i.playbackRate!==E&&(t(`Playback rate switch: ${$}=>${E}`),i.playbackRate=E)},g=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)v(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){v(1);return}const L=$e()-1e4;let q=0;for(let F=0;F<this.bufferStates.length;F++){const W=this.bufferStates[F];E=Math.min(E,W.buf),W.ts<L&&q++}this.bufferStates.splice(0,q),t(`update playback rate; minBuffer=${E} drop=${q} jitter=${this.sourceJitter}`);let B=E-mp;this.sourceJitter>=0?B-=this.sourceJitter/2:this.sourceJitter-=1,B>3?v(1.15):B>1?v(1.1):B>.3?v(1.05):v(1)}},m=E=>{let $;const L=()=>$&&$.start?$.start.length:0,q=P=>$.start[P]/1e3,B=P=>$.dur[P]/1e3,F=P=>$.fragIndex+P,W=(P,H)=>({chunkIdx:F(P),startTS:q(P),dur:B(P),discontinuity:H}),N=()=>{let P=0;if($&&$.dur){let H=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,ae=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,he=H;this.sourceJitter>1&&(he+=this.sourceJitter-1);let Se=$.dur.length-1;for(;Se>=0&&(he-=$.dur[Se],!(he<=0));--Se);P=Math.min(Se,$.dur.length-1-ae),P=Math.max(P,0)}return W(P,!0)},O=P=>{const H=L();if(!(H<=0)){if(_(P)){for(let ae=0;ae<H;ae++)if(q(ae)>P)return W(ae)}return N()}},X=P=>{const H=L(),ae=P?P.chunkIdx+1:0,he=ae-$.fragIndex;if(!(H<=0)){if(!P||he<0||he-H>pp)return t(`Resync: offset=${he} bChunks=${H} chunk=`+JSON.stringify(P)),N();if(!(he>=H))return W(ae-$.fragIndex,!1)}},oe=(P,H,ae)=>{d&&d.abort(),d=Hi(this.urlResolver.resolve(P,!0,this.lowLatency),H,ae,()=>this._retryCallback()).withTimeout(Ii).withRetryCount(Di).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(P,H)=>{oe(E,ae=>{if(!c())return;$=ae;const he=Boolean($.lowLatency);he!==this.lowLatency&&g(he);let Se=0;for(let we=0;we<$.dur.length;++we)Se+=$.dur[we];Se>0&&(R(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(Se/$.dur.length)),r({name:"index",zeroTime:$.zeroTime,shiftDuration:$.shiftDuration}),this.sourceJitter=$.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,$.jitter/1e3)):1,P(O(H))},()=>this._handleNetworkError())},nextChunk:X}},S=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),R(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:E=>{const{videoElement:$,logger:L}=this.params;let q=m(e.jidxUrl),B,F,W,N,O=0,X,oe,ve;const P=()=>{X&&(clearTimeout(X),X=void 0);const J=Math.max(vp,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),be=O+J,Le=$e(),Ce=Math.min(1e4,be-Le);O=Le;const Je=()=>{d||c()&&q.seek(()=>{c()&&(O=$e(),H(),P())})};Ce>0?X=window.setTimeout(()=>{this.paused?P():Je()},Ce):Je()},H=()=>{let J;for(;J=q.nextChunk(N);)N=J,Ve(J);const be=q.nextChunk(W);if(be){if(W&&be.discontinuity){L("Detected discontinuity; restarting playback"),this.paused?P():(S(),this._initPlayerWith(e));return}we(be)}else P()},ae=(J,be)=>{if(!c()||!this.sourceBuffer)return;let Le,Ce,Je;const gt=ht=>{window.setTimeout(()=>{c()&&ae(J,be)},ht)};if(this.sourceBuffer.updating)L("Source buffer is updating; delaying appendBuffer"),gt(100);else{const ht=$e(),It=$.currentTime;!this.paused&&$.buffered.length>1&&oe===It&&ht-ve>500&&(L("Stall suspected; trying to fix"),this._fixupStall()),oe!==It&&(oe=It,ve=ht);const He=this._getBufferSizeSec();if(He>30)L(`Buffered ${He} seconds; delaying appendBuffer`),gt(2e3);else try{this.sourceBuffer.appendBuffer(J),this.videoPlayStarted?(this.bufferStates.push({ts:ht,buf:He}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),be&&be()}catch(Wt){if(Wt.name==="QuotaExceededError")L("QuotaExceededError; delaying appendBuffer"),Je=this.sourceBuffer.buffered.length,Je!==0&&(Le=this.sourceBuffer.buffered.start(0),Ce=It,Ce-Le>4&&this.sourceBuffer.remove(Le,Ce-3)),gt(1e3);else throw Wt}}},he=()=>{F&&B&&(L([`Appending chunk, sz=${F.byteLength}:`,JSON.stringify(W)]),ae(F,function(){F=null,H()}))},Se=J=>e.fragUrlTemplate.replace("%%id%%",J.chunkIdx),we=J=>{c()&&f(Se(J),(be,Le)=>{if(c()){if(Le/=1e3,F=be,W=J,n=J.startTS,Le){const Ce=Math.min(10,J.dur/Le);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ce:Ce}he()}},()=>this._handleNetworkError())},Ve=J=>{c()&&(R(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(Se(J),!1)))},ct=J=>{c()&&(e.cachedHeader=J,ae(J,()=>{B=!0,he()}))};a=!0,q.seek(J=>{if(c()){if(O=$e(),!J){P();return}N=J,!ee(E)||J.startTS>E?we(J):(W=J,H())}},E),e.cachedHeader?ct(e.cachedHeader):h(e.headerUrl,ct,()=>this._handleNetworkError())},stop:S,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,R(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return _(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=c=>{if(!this.autoQuality)return;let h,f,v;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(f=this._getBufferSizeSec(),v=c/this.bitrate,f>10&&v>.8||f>15&&v>.5||f>20&&v>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},a=(()=>({updateChunk:(h,f)=>{const v=$e();if(this.chunkRateEstimator.addInterval(h,v,f)){const b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:v-h,speed:b}),!0}},get:()=>{const h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}}))();let n=-1/0,o,u=!0;const d=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&mo(n)<3e4)return;i(c)}u=this.autoQuality};return{updateChunk:(c,h)=>{const f=a.updateChunk(c,h);return f&&d(),f},notifySwitch:c=>{const h=$e();c<o&&(n=h),o=c}}}_fetchManifest(e,t,i){this.manifestRequest=Hi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(Ii).withRetryCount(Di).withRetryInterval(cp,hp).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;St(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))},fp))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var G;(function(s){s.STOPPED="stopped",s.MANIFEST_READY="manifest_ready",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(G||(G={}));const gp=[G.PAUSED,G.PLAYING,G.READY],bp=[G.PAUSED,G.PLAYING,G.READY];class yp{constructor(e){this.subscription=new re,this.videoState=new de(G.STOPPED),this.representations$=new T([]),this.textTracksManager=new Qe,this.maxSeekBackTime$=new T(1/0),this.zeroTime$=new T(void 0),this.liveOffset=new xr,this._dashCb=r=>{var a,n,o,u;switch(r.name){case"buffering":{const d=r.isBuffering;this.params.output.isBuffering$.next(d);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:D.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const d=r.manifest,l=[];for(const c of d){const h=(a=c.name)!==null&&a!==void 0?a:c.index.toString(10),f=(n=vi(c.name))!==null&&n!==void 0?n:kt(c.video),v=c.bitrate/1e3,g={...c.video};if(!f)continue;const b={id:h,quality:f,bitrate:v,size:g};l.push({track:b,representation:c})}this.representations$.next(l),this.params.output.availableVideoTracks$.next(l.map(({track:c})=>c)),((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===G.MANIFEST_READY&&this.videoState.setState(G.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===p.STOPPED){a!==G.STOPPED&&(this.videoState.startTransitionTo(G.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(G.STOPPED));return}if(!n){if(bp.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)!==p.PAUSED&&d.state===z.Requested&&gp.includes(a)){this.seek(d.position-this.liveOffset.getTotalPausedTime());return}switch(a){case G.STOPPED:this.videoState.startTransitionTo(G.MANIFEST_READY),this.dash.attachSource(Ht(this.params.source.url));return;case G.MANIFEST_READY:this.videoState.startTransitionTo(G.READY),this.prepare();break;case G.READY:if(o===p.PAUSED)this.videoState.setState(G.PAUSED);else if(o===p.PLAYING){this.videoState.startTransitionTo(G.PLAYING);const l=u==null?void 0:u.from;l&&l===p.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(G.PAUSED)})}return;case G.PLAYING:o===p.PAUSED&&(this.videoState.startTransitionTo(G.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case G.PAUSED:o===p.PLAYING&&(this.videoState.startTransitionTo(G.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(G.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return U(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:D.WTF,message:"DashLiveProvider internal logic error",thrown:r})};V(this.videoState.stateChangeStarted$.pipe(k(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(k(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=lt(this.video);this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===G.READY&&this.videoState.setState(G.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(G.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===z.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(G.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(fe(),k(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(je({zeroTime:this.zeroTime$.pipe(te(_)),position:i.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Rt(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(vt(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:r}})=>{const a=r&&Ko(r);this.dash.setMaxAutoQuality(a)})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case G.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(p.STOPPED);break;case G.MANIFEST_READY:case G.READY:((a=this.params.desiredState.playbackState.getTransition())===null||a===void 0?void 0:a.to)===p.READY&&this.params.desiredState.playbackState.setState(p.READY);break;case G.PAUSED:this.params.desiredState.playbackState.setState(p.PAUSED);break;case G.PLAYING:this.params.desiredState.playbackState.setState(p.PLAYING);break;default:return U(r.to)}},t)).add(V(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,_e(["init"])).pipe(Ie(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),ut(this.video)}createLiveDashPlayer(){const e=new Sp({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=mi(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=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t===p.PAUSED&&i===G.PAUSED,a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Ht(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}}var vo=s=>{var e,t;const i=s.get("X-Delivery-Type"),r=s.get("X-Reused"),a=i===null?ui.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}},At=(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 Tp=s=>{const e=document.createElement("a");return e.href=s,e.origin},Ep=s=>{const e=document.createElement("a");return e.href=s,e.host};class So{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=pi(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(Ep(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 Ji{constructor(e){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t==null||t()}catch(i){if(i.name==="QuotaExceededError"){this._isFull=!0;const r=this._sourceBuffer.buffered;let a=0;for(let n=0,o=r.length;n<o;n++)a+=r.end(n)-r.start(n);a&&(this._maxBufferDuration=Math.round(a))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",i),i}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,i,r,a,n,o){this.abort(()=>{let u=0;const d=Date.now();let l=0,c=0,h=0;const f=g=>{r(Ji._str2ua(g.substr(u))),u=g.length};let v=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(v=qt(v)),this._lastXhr=new So(v,e.failoverHosts,g=>{this._lastXhr=void 0,f(g);const b=Date.now()-d;this._params.onBandwidthChange({size:g.length,duration:b,speed:8*g.length/(b/1e3)}),this._onDashCallback("loading",{size:g.length,done:!0}),a==null||a()},g=>{if(g.length-u>o&&f(g),c===0){c=Date.now();return}h=g.length-l;const b=Date.now()-c;h>=100*1024&&b>=1e3&&(this._params.onBandwidthChange({size:h,duration:b,speed:8*h/(b/1e3)}),h=0,l=g.length,c=Date.now()),this._onDashCallback("loading",{size:g.length,done:!1})},n,(g,b,m)=>this._params.onError(g,b,m))})}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=Ji._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 $p{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=qt(i)),new So(i,t,r=>{this.attachManifest(r,t,Tp(i))},void 0,r=>{this._params.onResponseHeaders(r)},(r,a,n)=>this._params.onError(r,a,n))}attachManifest(e,t,i){const a=new DOMParser().parseFromString(e,"text/xml").documentElement,n=(d,l)=>{const c=d.attributes.getNamedItem(l);return c?c.value:null};this._duration=this._parseDurationFromISO8601(String(n(a,"mediaPresentationDuration")));const o=[],u=[];if(Array.prototype.forEach.call(a.getElementsByTagName("Representation"),d=>{var l,c,h,f,v,g,b,m,S,A,E,$,L,q,B,F,W,N,O;const X=d.getElementsByTagName("SegmentBase")[0],oe=X&&n(X,"indexRange").split("-"),ve=X&&X.getElementsByTagName("Initialization")[0],P=ve&&n(ve,"range").split("-");if(!P||!oe){const Ve=d.parentElement;if((Ve==null?void 0:Ve.getAttribute("contentType"))==="text"){const ct=(l=d.getAttribute("id"))!==null&&l!==void 0?l:void 0,J=(i?i+"/":"")+((v=(f=(h=(c=d.getElementsByTagName("BaseURL"))===null||c===void 0?void 0:c[0])===null||h===void 0?void 0:h.childNodes)===null||f===void 0?void 0:f[0])===null||v===void 0?void 0:v.data),be=(g=Ve.getAttribute("lang"))!==null&&g!==void 0?g:void 0;J&&u.push({id:ct,url:J,language:be})}return}const H=.1,ae=Number((b=d.attributes.getNamedItem("bandwidth"))===null||b===void 0?void 0:b.value),he=(i?i+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let Se;const we=(S=(m=d.attributes.getNamedItem("frameRate"))===null||m===void 0?void 0:m.value)!==null&&S!==void 0?S:void 0;Se=we?Or(we):void 0,o.push({width:Number((A=d.attributes.getNamedItem("width"))===null||A===void 0?void 0:A.value),height:Number((E=d.attributes.getNamedItem("height"))===null||E===void 0?void 0:E.value),bandwidth:ae,baseURL:he,failoverHosts:t,indexFrom:Number(oe[0]),indexTo:Number(oe[1]),initFrom:Number(P[0]),initTo:Number(P[1]),codecs:(L=($=d.attributes.getNamedItem("codecs"))===null||$===void 0?void 0:$.value)!==null&&L!==void 0?L:void 0,mimeType:(B=(q=d.attributes.getNamedItem("mimeType"))===null||q===void 0?void 0:q.value)!==null&&B!==void 0?B:void 0,fps:Se,bufferSize:H*ae/8,bufferLength:H,name:(W=(F=d.attributes.getNamedItem("okQuality"))===null||F===void 0?void 0:F.value)!==null&&W!==void 0?W:void 0,id:(O=(N=d.attributes.getNamedItem("id"))===null||N===void 0?void 0:N.value)!==null&&O!==void 0?O:void 0})}),o.length)this._representations=o;else{this._onDashCallback("error");return}u.forEach(({id:d,language:l,url:c})=>{const h=document.createElement("track");c&&h.setAttribute("src",c),d&&h.setAttribute("id",d),l&&h.setAttribute("srclang",l),this._video.appendChild(h)}),this._representations.sort((d,l)=>l.bandwidth-d.bandwidth),this._params.onManifestReady({representations:this._representations,textRepresentations:u})}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const i=Date.now();this._stream.load(e,e.initFrom,e.indexTo,r=>{let a=e.initTo-e.initFrom+1;if(!r.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(r.buffer,0,a);const n=new DataView(r.buffer);a+=12;const o=n.getUint32(a+4,!1);a+=8;let u=n.getUint32(a,!1),d=n.getUint32(a+4,!1)+(e.indexTo+1);a+=8;const l=n.getUint16(a+2,!1);a+=4,e.refs=[];for(let h=0;h<l;h+=1){const f=d+(n.getUint32(a,!1)&2147483647),v=u+n.getUint32(a+4,!1);a+=12,e.refs.push({fromTime:u/o,toTime:v/o,fromOffset:d,toOffset:f-1}),d=f,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 f=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),f)}const l=this._appendVector[String(d.fromTime)];l!==r&&(r=l,this._params.onRepresentationPlay(l));let c;if(this._findRef(d.toTime)){const f=this._buffer.getByTime(this._video.currentTime);if(!f){this._onDashCallback("buffering");return}c=f.to-this._video.currentTime,c<e.bufferLength&&(this._onDashCallback("buffering"),a!==f.to&&(a=f.to,window.setTimeout(()=>{try{const v=this._buffer.getNextWithGap(f);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 Ji({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||ee(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 Q;(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"})(Q||(Q={}));const Ap=[Q.PAUSED,Q.PLAYING];class wp{constructor(e){this.videoState=new de(Q.STOPPED),this.subscription=new re,this.representations$=new T([]),this.currentRepresentation$=new T(void 0),this.textTracksManager=new Qe,this.elementSize$=new T(void 0),this.dashLiteEvents={idxRequestPing$:new x,responseHeaders$:new x,manifestReady$:new x,representationPlay$:new x,error$:new x},this.handleManifestReady=({representations:t,textRepresentations:i})=>{var r,a,n;const o=[];for(const u of t){const d=(a=(r=u.name)!==null&&r!==void 0?r:u.id)!==null&&a!==void 0?a:u.height.toString(10),l=(n=u.name&&vi(u.name))!==null&&n!==void 0?n:kt(u),c=u.bandwidth/1e3,h={width:u.width,height:u.height},f=u.fps;if(!l)continue;const v={id:d,quality:l,bitrate:c,size:h,fps:f};o.push({track:v,representation:u})}if(this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:u})=>u)),(i==null?void 0:i.length)>0){const u=[];for(const d of i){const l=d.id||`${d.language}_${Date.now()}`;u.push({id:l,type:"internal",url:d.url||"",language:d.language,isAuto:d.isAuto})}this.params.desiredState.internalTextTracks.startTransitionTo(u)}this.videoState.setState(Q.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===p.STOPPED){t!==Q.STOPPED&&(this.videoState.startTransitionTo(Q.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Q.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(!i)switch((a==null?void 0:a.to)!==p.PAUSED&&n.state===z.Requested&&Ap.includes(t)&&this.seek(n.position,n.forcePrecise),t){case Q.STOPPED:this.videoState.startTransitionTo(Q.MANIFEST_LOADED),this.prepare();return;case Q.MANIFEST_LOADED:this.videoState.startTransitionTo(Q.INITIAL_REPRESENTATION_SELECTED);return;case Q.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(Q.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case Q.METADATA_LOADED:this.videoState.startTransitionTo(Q.READY),this.dash.updateRefsForCurrentTime();return;case Q.READY:r===p.READY?I(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(Q.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(Q.PLAYING),this.playIfAllowed());return;case Q.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(Q.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case Q.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(Q.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return U(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),V(this.videoState.stateChangeStarted$.pipe(k(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(k(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 Nf(this.video),this.dash=new $p({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:({representations:t,textRepresentations:i})=>this.dashLiteEvents.manifestReady$.next({representations:t,textRepresentations:i}),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,i,r)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:i,thrown:r,category:D.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:D.WTF,message:"DashProvider internal logic error",thrown:o})},r=()=>{const o=this.params.desiredState.autoVideoTrackSwitching.getState(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();return u?u.to:o},a=lt(this.video),n=(o,u)=>this.subscription.add(o.subscribe(u,i));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.isAudioAvailable$,e.isAudioAvailable$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(a.seeking$.subscribe(()=>{ee(this.params.desiredState.seekState.getState().state!==z.Applying)&&(this.videoState.getState()===Q.PLAYING||this.videoState.getState()===Q.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(Rt(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(vt(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),n(Qi(this.video),this.elementSize$),this.subscription.add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===Q.READY&&this.videoState.setState(Q.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(Q.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)})).add(a.playing$.subscribe(()=>{this.videoState.setState(Q.PLAYING),I(this.params.desiredState.playbackState,p.PLAYING)},i)).add(a.loadedMetadata$.subscribe(()=>{this.videoState.setState(Q.METADATA_LOADED)},i)).add(a.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},i)).add(this.dashLiteEvents.error$.pipe(k(({id:o,message:u,thrown:d})=>({id:`DashLite_${o}`,category:D.WTF,message:u,thrown:d}))).subscribe(this.params.output.error$)).add(V(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(k(()=>{var o,u,d;const l=this.currentRepresentation$.getValue(),c=this.representations$.getValue(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition(),f=this.params.desiredState.videoTrack.getState(),v=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),g=this.elementSize$.getValue(),b=r();h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to);let m;if(!b&&_(f))m=f;else{const S=At(this.video.buffered,this.video.currentTime*1e3),A=b?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,E=Math.min(S/A,1);m=(u=mi(c.map(({track:$})=>$),{container:g,throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:E,playbackRate:this.video.playbackRate,current:(o=c.find(({representation:$})=>$===l))===null||o===void 0?void 0:o.track}))===null||u===void 0?void 0:u.id}return _(m)?(d=c.find(({track:S})=>S.id===m))===null||d===void 0?void 0:d.representation:void 0}),fe()).subscribe(this.currentRepresentation$,i)).add(je({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(te(o=>o.to===Q.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(te(_))}).pipe(ge()).subscribe(()=>this.videoState.setState(Q.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(te(_),fe((o,u)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?o.height<=u.height:o===u)).subscribe(o=>{const u=At(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}=vo(o);this.params.output.httpConnectionType$.next(u),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(ge(),Vt(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(te(_)).subscribe(this.handleRepresentationPlay,i)).add(V(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,_e(["init"])).pipe(Ie(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),ut(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return U(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){St(this.video).then(e=>{e||(this.videoState.setState(Q.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}}var Te;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(Te||(Te={}));var Ki;(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"})(Ki||(Ki={}));var Re;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(Re||(Re={}));var Z;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(Z||(Z={}));var Gt;(function(s){s.MP4="mp4",s.WEBM="webm"})(Gt||(Gt={}));var vr=(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 kp=(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)},_p=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Wa=_p?kp:window.requestIdleCallback;var Us,Vs;let go=!1;try{go=Zi().browser===gr.Safari&&parseInt((Vs=(Us=navigator.userAgent.match(/Version\/(\d+)/))===null||Us===void 0?void 0:Us[1])!==null&&Vs!==void 0?Vs:"",10)<16}catch(s){console.error(s)}class Pp{constructor(e){this.bufferFull$=new x,this.error$=new x,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:D.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;go&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:i}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&i==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${i}`,category:D.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:U(t)}}}var Qa=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};const bo=new TextDecoder("ascii"),yo=s=>{let e=0,t=s.getUint32(e);e+=4;const i=new DataView(s.buffer,s.byteOffset+e,4),r=bo.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}},Rp=s=>bo.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",Ip=(s,e,t)=>{const i=yo(s),r=[];let a=0;const n=()=>{const g=i.contents.getUint32(a);return a+=4,g};if((n()&4278190080)!==0)throw new SyntaxError("Unsupported sidx version");n();const d=n(),l=n(),c=n(),h=n()&4294967295;let f=l/d*1e3,v=(t?t.to+1:s.byteOffset+s.byteLength)+c;for(let g=0;g<h;g++){const b=n(),m=b>>>31,S=b<<1>>>1,A=n();if(n(),m!==0)throw new Error("Unsupported multilevel sidx");const E=A/d*1e3;r.push({status:Z.NONE,time:{from:f,to:f+E},byte:{from:v,to:v+S-1}}),f+=E,v+=S}return r},Dp=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=yo(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},Lp={validateData:Rp,parseInit:()=>null,getIndexRange:()=>{},parseSegments:Ip,parseFeedableSegmentChunk:Dp};var w;(function(s){s[s.EBML=440786851]="EBML",s[s.EBMLVersion=17030]="EBMLVersion",s[s.EBMLReadVersion=17143]="EBMLReadVersion",s[s.EBMLMaxIDLength=17138]="EBMLMaxIDLength",s[s.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",s[s.DocType=17026]="DocType",s[s.DocTypeVersion=17031]="DocTypeVersion",s[s.DocTypeReadVersion=17029]="DocTypeReadVersion",s[s.Void=236]="Void",s[s.Segment=408125543]="Segment",s[s.SeekHead=290298740]="SeekHead",s[s.Seek=19899]="Seek",s[s.SeekID=21419]="SeekID",s[s.SeekPosition=21420]="SeekPosition",s[s.Info=357149030]="Info",s[s.TimestampScale=2807729]="TimestampScale",s[s.Duration=17545]="Duration",s[s.Tracks=374648427]="Tracks",s[s.Chapters=272869232]="Chapters",s[s.Cluster=524531317]="Cluster",s[s.Timestamp=231]="Timestamp",s[s.SilentTracks=22612]="SilentTracks",s[s.SilentTrackNumber=22743]="SilentTrackNumber",s[s.Position=167]="Position",s[s.PrevSize=171]="PrevSize",s[s.SimpleBlock=163]="SimpleBlock",s[s.BlockGroup=160]="BlockGroup",s[s.EncryptedBlock=175]="EncryptedBlock",s[s.Attachments=423732329]="Attachments",s[s.Tags=307544935]="Tags",s[s.Cues=475249515]="Cues",s[s.CuePoint=187]="CuePoint",s[s.CueTime=179]="CueTime",s[s.CueTrackPositions=183]="CueTrackPositions",s[s.CueTrack=247]="CueTrack",s[s.CueClusterPosition=241]="CueClusterPosition",s[s.CueRelativePosition=240]="CueRelativePosition",s[s.CueDuration=178]="CueDuration",s[s.CueBlockNumber=21368]="CueBlockNumber",s[s.CueCodecState=234]="CueCodecState",s[s.CueReference=219]="CueReference",s[s.CueRefTime=150]="CueRefTime"})(w||(w={}));var C;(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"})(C||(C={}));const Ja={[w.EBML]:{type:C.Master},[w.EBMLVersion]:{type:C.UnsignedInteger},[w.EBMLReadVersion]:{type:C.UnsignedInteger},[w.EBMLMaxIDLength]:{type:C.UnsignedInteger},[w.EBMLMaxSizeLength]:{type:C.UnsignedInteger},[w.DocType]:{type:C.String},[w.DocTypeVersion]:{type:C.UnsignedInteger},[w.DocTypeReadVersion]:{type:C.UnsignedInteger},[w.Void]:{type:C.Binary},[w.Segment]:{type:C.Master},[w.SeekHead]:{type:C.Master},[w.Seek]:{type:C.Master},[w.SeekID]:{type:C.Binary},[w.SeekPosition]:{type:C.UnsignedInteger},[w.Info]:{type:C.Master},[w.TimestampScale]:{type:C.UnsignedInteger},[w.Duration]:{type:C.Float},[w.Tracks]:{type:C.Master},[w.Chapters]:{type:C.Master},[w.Cluster]:{type:C.Master},[w.Timestamp]:{type:C.UnsignedInteger},[w.SilentTracks]:{type:C.Master},[w.SilentTrackNumber]:{type:C.UnsignedInteger},[w.Position]:{type:C.UnsignedInteger},[w.PrevSize]:{type:C.UnsignedInteger},[w.SimpleBlock]:{type:C.Binary},[w.BlockGroup]:{type:C.Master},[w.EncryptedBlock]:{type:C.Binary},[w.Attachments]:{type:C.Master},[w.Tags]:{type:C.Master},[w.Cues]:{type:C.Master},[w.CuePoint]:{type:C.Master},[w.CueTime]:{type:C.UnsignedInteger},[w.CueTrackPositions]:{type:C.Master},[w.CueTrack]:{type:C.UnsignedInteger},[w.CueClusterPosition]:{type:C.UnsignedInteger},[w.CueRelativePosition]:{type:C.UnsignedInteger},[w.CueDuration]:{type:C.UnsignedInteger},[w.CueBlockNumber]:{type:C.UnsignedInteger},[w.CueCodecState]:{type:C.UnsignedInteger},[w.CueReference]:{type:C.Master},[w.CueRefTime]:{type:C.UnsignedInteger}},To=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=Xi(s,t),r=i in Ja,a=r?Ja[i].type:C.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=Xi(u),c=d*2**((o-1)*8)+l,h=t+o;let f;return h+c>s.byteLength?f=new DataView(s.buffer,s.byteOffset+h):f=new DataView(s.buffer,s.byteOffset+h,c),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:f,valueSize:c}},Xi=(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},et=(s,e)=>{switch(e){case C.SignedInteger:return s.getInt8(0);case C.UnsignedInteger:return Xi(s);case C.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case C.String:return new TextDecoder("ascii").decode(s);case C.UTF8:return new TextDecoder("utf-8").decode(s);case C.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case C.Master:return s;case C.Binary:return s;default:U(e)}},Si=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=To(i);if(!e(r))return;r.type===C.Master&&Si(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},Cp=s=>{if(s.getUint32(0)!==w.EBML)return!1;let e,t,i;const r=To(s);return Si(r.value,({tag:a,type:n,value:o})=>(a===w.EBMLReadVersion?e=et(o,n):a===w.DocType?t=et(o,n):a===w.DocTypeReadVersion&&(i=et(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Eo=[w.Info,w.SeekHead,w.Tracks,w.Chapters,w.Cluster,w.Cues,w.Attachments,w.Tags],xp=[w.Timestamp,w.SilentTracks,w.SilentTrackNumber,w.Position,w.PrevSize,w.SimpleBlock,w.BlockGroup,w.EncryptedBlock],Op=s=>{let e,t,i,r,a=!1,n=!1,o=!1,u,d;return Si(s,({tag:l,type:c,value:h,valueSize:f})=>{if(l===w.SeekID){const v=et(h,c);d=Xi(v)}else l!==w.SeekPosition&&(d=void 0);return l===w.Segment?(e=h.byteOffset,t=h.byteOffset+f):l===w.Info?a=!0:l===w.SeekHead?n=!0:l===w.TimestampScale?i=et(h,c):l===w.Duration?r=et(h,c):l===w.SeekPosition&&d===w.Cues?u=et(h,c):a&&n&&Eo.includes(l)&&(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}},Bp=s=>{if(ee(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Np=(s,e)=>{let t=!1,i=!1;const r=o=>_(o.time)&&_(o.position),a=[];let n;return Si(s,({tag:o,type:u,value:d})=>{switch(o){case w.Cues:t=!0;break;case w.CuePoint:n&&r(n)&&a.push(n),n={};break;case w.CueTime:n&&(n.time=et(d,u));break;case w.CueTrackPositions:break;case w.CueClusterPosition:n&&(n.position=et(d,u));break;default:t&&Eo.includes(o)&&(i=!0)}return!(t&&i)}),n&&r(n)&&a.push(n),a.map((o,u)=>{const{time:d,position:l}=o,c=a[u+1];return{status:Z.NONE,time:{from:d,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},Mp=s=>{let e=0,t=!1;try{Si(s,i=>i.tag===w.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):xp.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[w.SimpleBlock,w.BlockGroup,w.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},Fp={validateData:Cp,parseInit:Op,getIndexRange:Bp,parseSegments:Np,parseFeedableSegmentChunk:Mp};class Ka{constructor(e,t,i,r,{fetcher:a,tuning:n,getCurrentPosition:o,compatibilityMode:u=!1}){switch(this.onLastSegment$=new T(!1),this.fullyBuffered$=new T(!1),this.playingRepresentation$=new T(void 0),this.error$=new x,this.gaps=[],this.subscription=new re,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new wt,this.destroyAbortController=new wt,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 Pp(this.sourceBuffer),this.subscription.add(M(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},v=>this.error$.next({id:"SegmentEjection",category:D.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:D.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(v=>{if(!this.sourceBuffer)return;const g=Math.min(this.bufferLimit,Qa(this.sourceBuffer.buffered)*.8);this.bufferLimit=g,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(R(c,"No init buffer for starting representation"),R(h,"No segments for starting representation"),!(c instanceof ArrayBuffer))return;let f=0;for(const v of h)v.time.from-f>0&&this.gaps.push({representation:l.id,from:f,to:v.time.from}),f=v.time.to;_(l.duration)&&l.duration-f>0&&this.gaps.push({representation:l.id,from:f,to:l.duration}),yield this.sourceBufferTaskQueue.append(c,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId)}.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(ee(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 Gt.MP4:this.containerParser=Lp;break;case Gt.WEBM:this.containerParser=Fp;break;default:U(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 wt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(ee(e)||ee(this.downloadingRepresentationId)||ee(this.playingRepresentationId)||ee(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=At(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)&&Qa(this.sourceBuffer.buffered)>=this.bufferLimit){const d=At(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=Ke(o,0);l&&l.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===Z.FED&&!o.length&&At(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const u=Ke(i,-1);u&&u.status===Z.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;if(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();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){const r=e.findIndex(({status:c,time:{from:h,to:f}},v)=>{const g=h<=i&&f>=i,b=h>i||g||v===0&&i===0,m=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&h<=i+m||f<=i+m;return(c===Z.NONE||c===Z.PARTIALLY_EJECTED&&b&&S&&this.sourceBuffer&&!vr(this.sourceBuffer.buffered,i))&&b&&S});if(r===-1)return[];if(t!==Re.BYTE_RANGE)return e.slice(r,r+1);const a=e;let n=0,o=0;const u=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=d||o<=l);c++){const h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status===Z.NONE||h.status===Z.PARTIALLY_EJECTED)u.push(h);else break}return u}async loadSegments(e,t,i="auto"){if(!e.length)return;let r,a,n=e;const{type:o}=t.segmentReference;switch(o){case Re.BYTE_RANGE:{r=t.segmentReference.url,a={from:Ke(e,0).byte.from,to:Ke(e,-1).byte.to};break}case Re.TEMPLATE:{const d=Ke(e,0);r=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:U(o)}for(const d of n)d.status=Z.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=Wr(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:D.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=At((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:D.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=Z.FED,"size"in c.segment&&(c.segment.size=c.fedBytes);for(const f of this.representations.values())if(f.id!==t)for(const v of(h=this.segments.get(f.id))!==null&&h!==void 0?h:[])v.status===Z.FED&&v.time.from===c.segment.time.from&&v.time.to===c.segment.time.to&&(v.status=Z.NONE);this.activeSegments.delete(c),this.detectGapsWhenIdle(t,[c.segment])},u=this.representations.get(t);if(!u)return;const d=u.segmentReference.type,l=e.byteLength;for(const c of this.activeSegments){const{segment:h}=c,f=d===Re.BYTE_RANGE,v=f?h.byte.to-h.byte.from+1:l;if(c.representationId!==t||!(!f||h.byte.from>=i&&h.byte.to<i+e.byteLength))continue;if(a.aborted){n();continue}const b=f?h.byte.from-i:0,m=f?h.byte.to-i:e.byteLength,S=b<r,A=m<=r;if(h.status===Z.DOWNLOADING&&S&&A){h.status=Z.DOWNLOADED,this.activeSegments.delete(c);const E=new DataView(e.buffer,e.byteOffset+b,v);this.sourceBufferTaskQueue.append(E,a).then($=>$&&!a.aborted?o(c):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&(c.loadedBytes=Math.min(v,r-b),c.loadedBytes>c.feedingBytes)){const E=new DataView(e.buffer,e.byteOffset+b+c.feedingBytes,c.loadedBytes-c.feedingBytes),$=c.loadedBytes===v?E:this.containerParser.parseFeedableSegmentChunk(E);$!=null&&$.byteLength&&(h.status=Z.PARTIALLY_FED,c.feedingBytes+=$.byteLength,this.sourceBufferTaskQueue.append($,a).then(L=>{if(a.aborted)n();else if(L)c.fedBytes+=$.byteLength,c.fedBytes===v&&o(c);else{if(c.feedingBytes<v)return;n()}}))}}}abortSegment(e){e.status===Z.PARTIALLY_FED||e.status===Z.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=Z.NONE),e.status=Z.PARTIALLY_EJECTED):e.status=Z.NONE;for(const 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=Wa(()=>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=Wr(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:D.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||ee(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===Z.FED&&u(l)}if(o=isFinite(a)&&isFinite(n),!o){r=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const l of d){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;l.status===Z.FED&&u(l)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const l=this.sourceBuffer.buffered.start(d)*1e3,c=this.sourceBuffer.buffered.end(d)*1e3;for(const h of this.segments.values())for(const f of h)if(f.status===Z.NONE&&Math.round(f.time.from)<=Math.round(l)&&Math.round(f.time.to)>=Math.round(c)){a=l,n=c;break}}if(o=isFinite(a)&&isFinite(n),!o&&i){r=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const l of this.segments.values())for(const c of l)c.time.from>e+d&&c.status===Z.FED&&u(c)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}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=Wa(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:D.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(ee(this.sourceBuffer)||ee(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),a=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:a})}const t=1;for(const i of this.segments.values())for(const r of i){const{status:a}=r;if(a!==Z.FED&&a!==Z.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(l=>l.from-t<=n&&l.to+t>=o),d=e.filter(l=>n>=l.from-t&&n<=l.to+t||o>=l.from-t&&o<=l.to+t);u||(d.length===1?r.status=Z.PARTIALLY_EJECTED:r.status=Z.NONE)}}}var Ft;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(Ft||(Ft={}));class Up{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new T(void 0),this.lastConnectionReused$=new T(void 0),this.lastRequestFirstBytes$=new T(void 0),this.abortAllController=new wt,this.subscription=new re,this.fetchManifest=Me(this.abortAllController.signal,async function*(r){let a=r;this.requestQuic&&(a=qt(a));const n=yield Yt(a,{signal:this.abortAllController.signal}).catch(ai);return n?(this.onHeadersReceived(n.headers),n.text()):null}.bind(this)),this.fetch=Me(this.abortAllController.signal,async function*(r,{rangeMethod:a=this.compatibilityMode?Ft.HEADER:Ft.PARAM,range:n,onProgress:o,priority:u="auto",signal:d,measureThroughput:l=!0}={}){var c,h,f,v;let g=r;const b=new Headers;if(n)switch(a){case Ft.HEADER:{b.append("Range",`bytes=${n.from}-${n.to}`);break}case Ft.PARAM:{const P=new URL(g,location.href);P.searchParams.append("bytes",`${n.from}-${n.to}`),g=P.toString();break}default:U(a)}this.requestQuic&&(g=qt(g));let m=this.abortAllController.signal;if(d){const P=new wt;if(this.subscription.add(V(M(this.abortAllController.signal,"abort"),M(d,"abort")).subscribe(()=>{try{P.abort()}catch(H){ai(H)}})),this.abortAllController.signal.aborted||d.aborted)try{P.abort()}catch(H){ai(H)}m=P.signal}const S=ce(),A=yield Yt(g,{priority:u,headers:b,signal:m}).catch(ai),E=ce();if((c=this.throughputEstimator)===null||c===void 0||c.addRawRtt(E-S),!A)return null;if(!A.ok||!A.body)return Promise.reject(new Error(`Fetch error ${A.status}: ${A.statusText}`));this.onHeadersReceived(A.headers);const $=parseInt((h=A.headers.get("Content-Length"))!==null&&h!==void 0?h:"",10)||n&&n.to-n.from+1||NaN;if(!$){const P=yield A.arrayBuffer();return(f=this.throughputEstimator)===null||f===void 0||f.addRawSpeed(P.byteLength,ce()-E),o==null||o(new DataView(P),P.byteLength),P}if(!o&&!l)return A.arrayBuffer();const[L,q]=A.body.tee(),B=L.getReader();l&&((v=this.throughputEstimator)===null||v===void 0||v.trackStream(q));let F=0;const W=new ArrayBuffer($),N=new Uint8Array(W),O=new DataView(W);let X=!1;const oe=P=>{X=!0,ai(P)},ve=Me(m,async function*({done:P,value:H}){F===0&&this.lastRequestFirstBytes$.next(ce()-S),!m.aborted&&!P&&H&&(N.set(H,F),F+=H.byteLength,o==null||o(O,F),yield B==null?void 0:B.read().then(ve,oe))}.bind(this));return yield B==null?void 0:B.read().then(ve,oe),X?null:W}.bind(this)),this.fetchByteRangeRepresentation=Me(this.abortAllController.signal,async function*(r,a,n){var o;if(r.type!==Re.BYTE_RANGE)return null;const{from:u,to:d}=r.initRange;let l=u,c=d,h=!1,f,v;r.indexRange&&(f=r.indexRange.from,v=r.indexRange.to,h=d+1===f,h&&(l=Math.min(f,u),c=Math.max(v,d))),l=Math.min(l,0);const g=yield this.fetch(r.url,{range:{from:l,to:c},priority:n,measureThroughput:!1});if(!g)return null;const b=new DataView(g,u-l,d-l+1);if(!a.validateData(b))throw new Error("Invalid media file");const m=a.parseInit(b),S=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(m);if(!S)throw new ReferenceError("No way to load representation index");let A;if(h)A=new DataView(g,S.from-l,S.to-S.from+1);else{const $=yield this.fetch(r.url,{range:S,priority:n,measureThroughput:!1});if(!$)return null;A=new DataView($)}const E=a.parseSegments(A,m,S);return{dataView:new DataView(g),segments:E}}.bind(this)),this.fetchTemplateRepresentation=Me(this.abortAllController.signal,async function*(r,a){if(r.type!==Re.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:Z.NONE,size:void 0})),dataView:new DataView(o)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=vo(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 Re.BYTE_RANGE:return(r=await this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case Re.TEMPLATE:return(a=await this.fetchTemplateRepresentation(e,i))!==null&&a!==void 0?a:null;default:U(n)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const ai=s=>{if(!(s instanceof DOMException)||!(s.name==="AbortError"||s.code===20))throw s};var Vp=_t,Hp=is,Yp=Ue,qp=Yp("match"),Gp=function(s){var e;return Vp(s)&&((e=s[qp])!==void 0?!!e:Hp(s)=="RegExp")},zp=ds,jp=String,Wp=function(s){if(zp(s)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return jp(s)},Qp=Pt,Jp=function(){var s=Qp(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},Kp=at,Xp=nt,Zp=Er,em=Jp,Xa=RegExp.prototype,tm=function(s){var e=s.flags;return e===void 0&&!("flags"in Xa)&&!Xp(s,"flags")&&Zp(Xa,s)?Kp(em,s):e},Nr=rt,im=as,sm=Math.floor,Hs=Nr("".charAt),rm=Nr("".replace),Ys=Nr("".slice),am=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,nm=/\$([$&'`]|\d{1,2})/g,om=function(s,e,t,i,r,a){var n=t+s.length,o=i.length,u=nm;return r!==void 0&&(r=im(r),u=am),rm(a,u,function(d,l){var c;switch(Hs(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 f=sm(h/10);return f===0?d:f<=o?i[f-1]===void 0?Hs(l,1):i[f-1]+Hs(l,1):d}c=i[h-1]}return c===void 0?"":c})},dm=os,um=at,Mr=rt,Za=br,lm=De,cm=ss,hm=Gp,Bt=Wp,fm=rs,pm=tm,mm=om,vm=Ue,Sm=vm("replace"),gm=TypeError,$o=Mr("".indexOf),bm=Mr("".replace),en=Mr("".slice),ym=Math.max,tn=function(s,e,t){return t>s.length?-1:e===""?t:$o(s,e,t)};dm({target:"String",proto:!0},{replaceAll:function(e,t){var i=Za(this),r,a,n,o,u,d,l,c,h,f=0,v=0,g="";if(!cm(e)){if(r=hm(e),r&&(a=Bt(Za(pm(e))),!~$o(a,"g")))throw gm("`.replaceAll` does not allow non-global regexes");if(n=fm(e,Sm),n)return um(n,e,i,t);if(r)return bm(Bt(i),e,t)}for(o=Bt(i),u=Bt(e),d=lm(t),d||(t=Bt(t)),l=u.length,c=ym(1,l),f=tn(o,u,0);f!==-1;)h=d?Bt(t(u,f,o)):mm(u,o,f,[],void 0,t),g+=en(o,v,f)+h,v=f+l,f=tn(o,u,f+c);return v<o.length&&(g+=en(o,v)),g}});var Tm=po,Em=Tm("String","replaceAll"),$m=Em,Am=$m,wm=Am,km=wm,sn=km;const rn=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=sn(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=sn(t,n,(o,u)=>ee(a)?o:ee(u)?a:a.padStart(parseInt(u,10),"0"))}return t},_m=(s,e)=>{var t,i,r,a,n,o,u,d,l,c,h,f,v,g,b,m,S,A,E,$,L,q,B,F,W,N,O,X,oe,ve,P,H,ae,he,Se,we,Ve,ct,J,be;const Ce=new DOMParser().parseFromString(s,"application/xml"),Je={video:[],audio:[],text:[]},gt=Ce.children[0],ht=gt.getElementsByTagName("Period")[0],It=ht.children;let He;const Wt=gt.getAttribute("mediaPresentationDuration"),Fr=ht.getAttribute("duration");if(Wt)He=rn(Wt);else if(Fr){const xe=rn(Fr);_(xe)&&(He=xe)}let Io=0;const cs=(i=(t=gt.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],Do=cs.includes(Ki.WEBM_AS_IN_FFMPEG)||cs.includes(Ki.WEBM_AS_IN_SPEC)?Gt.WEBM:Gt.MP4;for(const xe of It){const gi=xe.getAttribute("mimeType"),Lo=xe.getAttribute("codecs"),Ur=(r=xe.getAttribute("contentType"))!==null&&r!==void 0?r:gi==null?void 0:gi.split("/")[0],Co=(n=(a=xe.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],Vr=xe.querySelectorAll("Representation"),xo=xe.querySelector("SegmentTemplate");if(Ur===Te.TEXT){for(const pe of Vr){const bt=pe.getAttribute("id")||"",bi=xe.getAttribute("lang"),Dt=(d=(u=(o=pe.querySelector("BaseURL"))===null||o===void 0?void 0:o.textContent)===null||u===void 0?void 0:u.trim())!==null&&d!==void 0?d:"",hs=new URL(Dt,e).toString();Je[Te.TEXT].push({id:bt,lang:bi,kind:Te.TEXT,url:hs})}continue}for(const pe of Vr){const bt=(l=pe.getAttribute("mimeType"))!==null&&l!==void 0?l:gi,bi=(h=(c=pe.getAttribute("codecs"))!==null&&c!==void 0?c:Lo)!==null&&h!==void 0?h:"",Dt=(v=(f=pe.getAttribute("contentType"))!==null&&f!==void 0?f:bt==null?void 0:bt.split("/")[0])!==null&&v!==void 0?v:Ur,hs=(b=(g=xe.getAttribute("profiles"))===null||g===void 0?void 0:g.split(","))!==null&&b!==void 0?b:[],Oo=parseInt((m=pe.getAttribute("width"))!==null&&m!==void 0?m:"",10),Hr=parseInt((S=pe.getAttribute("height"))!==null&&S!==void 0?S:"",10),Yr=parseInt((A=pe.getAttribute("bandwidth"))!==null&&A!==void 0?A:"",10)/1e3,qr=(E=pe.getAttribute("frameRate"))!==null&&E!==void 0?E:"",Bo=($=pe.getAttribute("quality"))!==null&&$!==void 0?$:void 0,No=qr?Or(qr):void 0,Mo=(L=pe.getAttribute("id"))!==null&&L!==void 0?L:(Io++).toString(10),Fo=Dt==="video"?`${Hr}p`:Dt==="audio"?`${Yr}Kbps`:bi,Uo=`${Mo}@${Fo}`,Vo=(F=(B=(q=pe.querySelector("BaseURL"))===null||q===void 0?void 0:q.textContent)===null||B===void 0?void 0:B.trim())!==null&&F!==void 0?F:"",Gr=new URL(Vo,e).toString(),Ho=[...cs,...Co,...hs];let fs;const Yo=pe.querySelector("SegmentBase"),yt=(W=pe.querySelector("SegmentTemplate"))!==null&&W!==void 0?W:xo;if(Yo){const Qt=(O=(N=pe.querySelector("SegmentBase Initialization"))===null||N===void 0?void 0:N.getAttribute("range"))!==null&&O!==void 0?O:"",[Jt,ms]=Qt.split("-").map(Tt=>parseInt(Tt,10)),Kt={from:Jt,to:ms},Xt=(X=pe.querySelector("SegmentBase"))===null||X===void 0?void 0:X.getAttribute("indexRange"),[vs,yi]=Xt?Xt.split("-").map(Tt=>parseInt(Tt,10)):[],Zt=Xt?{from:vs,to:yi}:void 0;fs={type:Re.BYTE_RANGE,url:Gr,initRange:Kt,indexRange:Zt}}else if(yt){const Qt={representationId:(oe=pe.getAttribute("id"))!==null&&oe!==void 0?oe:void 0,bandwidth:(ve=pe.getAttribute("bandwidth"))!==null&&ve!==void 0?ve:void 0},Jt=parseInt((P=yt.getAttribute("timescale"))!==null&&P!==void 0?P:"",10),ms=(H=yt.getAttribute("initialization"))!==null&&H!==void 0?H:"",Kt=yt.getAttribute("media"),Xt=(he=parseInt((ae=yt.getAttribute("startNumber"))!==null&&ae!==void 0?ae:"",10))!==null&&he!==void 0?he:1,vs=qs(ms,Qt);if(!Kt)throw new ReferenceError("No media attribute in SegmentTemplate");const yi=(Se=yt.querySelectorAll("SegmentTimeline S"))!==null&&Se!==void 0?Se:[],Zt=[];if(yi.length){let Tt=Xt,Et=0;for(const ei of yi){const Lt=parseInt((we=ei.getAttribute("d"))!==null&&we!==void 0?we:"",10)*1e3,ti=parseInt((Ve=ei.getAttribute("r"))!==null&&Ve!==void 0?Ve:"",10)||0,ii=(J=parseInt((ct=ei.getAttribute("t"))!==null&&ct!==void 0?ct:"",10))!==null&&J!==void 0?J:void 0;for(let zr=0;zr<ti+1;zr++){const qo=qs(Kt,{...Qt,segmentNumber:Tt.toString(10),segmentTime:ii.toString(10)}),Go=ii?ii/Jt:Et;Et+=Lt/Jt;const zo=Et;Tt++,Zt.push({time:{from:Go,to:zo},url:qo})}}}else if(_(He)){const Et=parseInt((be=yt.getAttribute("duration"))!==null&&be!==void 0?be:"",10)/Jt*1e3,ei=Math.ceil(He/Et);let Lt=0;for(let ti=1;ti<ei;ti++){const ii=qs(Kt,{...Qt,segmentNumber:ti.toString(10),segmentTime:Lt.toString(10)});Zt.push({time:{from:Lt,to:Lt+Et},url:ii}),Lt+=Et}}fs={type:Re.TEMPLATE,baseUrl:Gr,initUrl:vs,segments:Zt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Dt||!bt)continue;const ps={video:Te.VIDEO,audio:Te.AUDIO,text:Te.TEXT}[Dt];ps&&Je[ps].push({id:Uo,kind:ps,segmentReference:fs,profiles:Ho,duration:He,bitrate:Yr,mime:bt,codecs:bi,width:Oo,height:Hr,fps:No,quality:Bo})}}return{duration:He,container:Do,representations:Je}},Pm=["timeupdate","progress","play","seeked","stalled","waiting"];var Pe;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(Pe||(Pe={}));let Rm=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new re,this.state$=new de(Pe.NONE),this.currentVideoRepresentation$=new T(void 0),this.error$=new x,this.lastConnectionType$=new T(void 0),this.lastConnectionReused$=new T(void 0),this.lastRequestFirstBytes$=new T(void 0),this.forceEnded$=new x,this.gapWatchdogStarted=!1,this.destroyController=new wt,this.initManifest=Me(this.destroyController.signal,async function*(t,i){this.element=t,this.state$.startTransitionTo(Pe.MANIFEST_READY);const r=yield this.fetcher.fetchManifest(i).catch(o=>this.error$.next({id:"LoadManifest",category:D.NETWORK,message:"Failed to load manifest",thrown:o}));if(!r)return;let a;try{a=_m(r!=null?r:"",i)}catch(o){this.error$.next({id:"ManifestParsing",category:D.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!a)return;const n=({kind:o,mime:u,codecs:d})=>{var l,c,h;return Boolean(((l=t.canPlayType)===null||l===void 0?void 0:l.call(t,u))&&((h=(c=window.MediaSource)===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0?void 0:h.call(c,`${u}; codecs="${d}"`))||o===Te.TEXT)};this.manifest={...a,representations:pi(Object.entries(a.representations).map(([o,u])=>[o,u.filter(n)]))},this.manifest.representations.video.length?this.state$.setState(Pe.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:D.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(Pe.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 Ka(Te.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],_(i)&&(this.audioBufferManager=new Ka(Te.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=V(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe(k(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=V(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe(k(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.subscription.add(V(this.forceEnded$,je({allBuffersFull:a,someBufferEnded:n}).pipe(te(({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:D.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:u})}})),this.subscription.add(V(...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(Pe.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:D.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Up({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initBuffer(){R(this.element),this.state$.setState(Pe.RUNNING),this.subscription.add(V(...Pm.map(e=>M(this.element,e)),M(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:D.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&&vr(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){const i={[Te.VIDEO]:this.videoBufferManager,[Te.AUDIO]:this.audioBufferManager,[Te.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)}seek(e,t){var i,r,a,n,o;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),vr(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(Pe.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)===null||e===void 0?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}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 ue;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(ue||(ue={}));const Im=({id:s,width:e,height:t,bitrate:i,fps:r,quality:a})=>{var n;const o=(n=a?vi(a):void 0)!==null&&n!==void 0?n:kt({width:e,height:t});return o&&{id:s,quality:o,bitrate:i,size:{width:e,height:t},fps:r}},Dm=({id:s,bitrate:e})=>({id:s,bitrate:e}),Lm=({id:s,lang:e,url:t,isAuto:i})=>({id:s,url:t,isAuto:i,type:"internal",language:e}),Cm=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=Ke(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:Ke(s,-1)};class xm{constructor(e){this.subscription=new re,this.videoState=new de(ue.STOPPED),this.elementSize$=new T(void 0),this.textTracksManager=new Qe,this.videoTracks=[],this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new ip,this.textTracks=[],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===z.Requested&&(r==null?void 0:r.to)!==p.PAUSED&&t!==ue.STOPPED&&i!==p.STOPPED&&this.seek(a.position,a.forcePrecise),i===p.STOPPED){t!==ue.STOPPED&&(this.videoState.startTransitionTo(ue.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ue.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}switch(t){case ue.STOPPED:this.videoState.startTransitionTo(ue.READY),this.prepare();return;case ue.READY:i===p.PAUSED?(this.videoState.setState(ue.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):i===p.PLAYING?(this.videoState.startTransitionTo(ue.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.READY&&I(this.params.desiredState.playbackState,p.READY);return;case ue.PLAYING:i===p.PAUSED?(this.videoState.startTransitionTo(ue.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case ue.PAUSED:i===p.PLAYING?(this.videoState.startTransitionTo(ue.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return U(t)}}},this.params=e,this.video=dt(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ae(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Rm({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=lt(this.video),r=d=>{e.error$.next({id:"DashVKProvider",category:D.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(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.lastRequestFirstBytes$.pipe(te(_),ge()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Rt(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(vt(this.video,t.playbackRate,i.playbackRateState$,r)),a(Qi(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(ue.PLAYING),I(t.playbackState,p.PLAYING)},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(ue.PAUSED),I(t.playbackState,p.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===ue.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d===Pe.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[],this.textTracks=[];const c=this.player.getRepresentations();R(c,"Manifest not loaded or empty");const h=Array.from(c.audio).sort((b,m)=>m.bitrate-b.bitrate),f=Array.from(c.video).sort((b,m)=>m.bitrate-b.bitrate),v=Array.from(c.text);if(!this.params.tuning.isAudioDisabled)for(const b of h){const m=Dm(b);m&&this.audioTracks.push({track:m,representation:b})}for(const b of f){const m=Im(b);if(m){this.videoTracks.push({track:m,representation:b});const S=!this.params.tuning.isAudioDisabled&&Cm(h,f,b);S&&this.audioRepresentations.set(b.id,S)}}for(const b of v){const m=Lm(b);m&&this.textTracks.push({track:m,representation:b})}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:b})=>b)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:b})=>b)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:b})=>b));const g=this.selectVideoRepresentation();R(g),this.player.initRepresentations(g.id,(l=this.audioRepresentations.get(g.id))===null||l===void 0?void 0:l.id)}else d===Pe.REPRESENTATIOS_READY&&(this.videoState.setState(ue.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:D.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(V(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!==Pe.RUNNING||l||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation();if(c){this.player.switchRepresentation(Te.VIDEO,c.id).catch(n);const h=this.audioRepresentations.get(c.id);h&&this.player.switchRepresentation(Te.AUDIO,h.id).catch(n)}},r)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(fe(),k(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(k(({to:d})=>d===p.READY),fe());this.subscription.add(V(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===p.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(V(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===p.READY)));const u=V(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,_e(["init"])).pipe(Ie(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:m}})=>m===u))===null||e===void 0?void 0:e.track,l=this.params.output.currentVideoTrack$.getValue(),c=At(this.video.buffered,this.video.currentTime*1e3),h=o?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,f=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),g=mi(this.videoTracks.map(({track:m})=>m),{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:f,current:l,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),b=o?g!=null?g:d:d!=null?d:g;return b&&((n=this.videoTracks.find(({track:m})=>m===b))===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.player.destroy(),this.params.output.element$.next(void 0),ut(this.video)}playIfAllowed(){St(this.video).then(e=>{e||(this.videoState.setState(ue.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}}const Om=5e3,qe={};var K;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(K||(K={}));const ni=(s,e)=>new es(t=>{const i=(r,a)=>t.next(a);return s.on(e,i),()=>s.off(e,i)});class Bm{constructor(e){this.subscription=new re,this.videoState=new de(K.INITIALIZING),this.textTracksManager=new Qe,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!==K.INITIALIZING)switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===z.Requested&&this.seek(a.position),i){case p.STOPPED:switch(t){case K.STOPPED:break;case K.READY:case K.PLAYING:case K.PAUSED:this.stop();break;default:U(t)}break;case p.READY:switch(t){case K.STOPPED:this.prepare();break;case K.READY:case K.PLAYING:case K.PAUSED:break;default:U(t)}break;case p.PLAYING:switch(t){case K.PLAYING:break;case K.STOPPED:this.prepare();break;case K.READY:case K.PAUSED:this.playIfAllowed();break;default:U(t)}break;case p.PAUSED:switch(t){case K.PAUSED:break;case K.STOPPED:this.prepare();break;case K.READY:this.videoState.setState(K.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED);break;case K.PLAYING:this.pause();break;default:U(t)}break;default:U(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.params.output.element$.next(void 0),ut(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:D.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),Om);import("hls.js").then(r=>{e||(qe.Hls=r.default,qe.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){R(qe.Hls,"hls.js not loaded"),this.hls=new qe.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(K.STOPPED)}subscribe(){R(qe.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:D.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=lt(this.video),a=(d,l)=>this.subscription.add(d.subscribe(l,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.isAudioAvailable$,t.isAudioAvailable$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(Rt(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(vt(this.video,e.playbackRate,r.playbackRateState$,i)),this.subscription.add(ni(this.hls,qe.Events.ERROR).subscribe(d=>{var l;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:D.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(K.PLAYING),I(e.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(K.PAUSED),I(e.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())===null||d===void 0?void 0:d.to)===K.READY&&this.videoState.setState(K.READY),this.videoState.getState()===K.PLAYING&&this.playIfAllowed()},i)),a(ni(this.hls,qe.Events.MANIFEST_PARSED).pipe(k(({levels:d})=>d.reduce((l,c)=>{var h,f;const v=c.name||c.height.toString(10),{width:g,height:b}=c,m=(f=vi((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:kt({width:g,height:b});if(!m)return l;const S=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,A={id:v.toString(),quality:m,bitrate:c.bitrate/1e3,size:{width:g,height:b},fps:S};return this.trackLevels.set(v,{track:A,level:c}),l.push(A),l},[]))),t.availableVideoTracks$),a(ni(this.hls,qe.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){const l=[];for(const c of d.subtitleTracks){const h=c.name,f=c.attrs.URI||"",v=c.lang,g="internal";l.push({id:h,url:f,language:v,type:g})}e.internalTextTracks.startTransitionTo(l)}}),a(ni(this.hls,qe.Events.LEVEL_LOADING).pipe(k(({url:d})=>Ae(d))),t.hostname$),this.subscription.add(Fe(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=ni(this.hls,qe.Events.LEVEL_SWITCHED).pipe(k(({level:d})=>n(this.hls.levels[d])));o.pipe(te(_)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Fe(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(ee(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),f=this.hls.currentLevel,v=this.hls.levels[f];!v||c.bitrate>v.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o.pipe(k(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=V(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,_e(["init"])).pipe(Ie(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(K.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(K.PLAYING),await St(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:t}))||(this.videoState.setState(K.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))}pause(){this.videoState.startTransitionTo(K.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(K.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0)}}const an="X-Playback-Duration";var nn=async s=>{const e=await Yt(s,{method:"HEAD"});return e.headers.has(an)?parseInt(e.headers.get(an),10):void 0};const Nm=s=>{let e=null;if(s.QUALITY&&(e=vi(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=kt({width:t,height:i})}return e!=null?e:null},Ao=async(s,e=s)=>{var t;const a=(await(await Yt(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=pi(d[1].split(",").map(m=>m.split("="))),c=(t=l.QUALITY)!==null&&t!==void 0?t:`stream-${l.BANDWIDTH}`,h=Nm(l);let f;l.BANDWIDTH&&(f=parseInt(l.BANDWIDTH,10)/1e3||void 0),!f&&l["AVERAGE-BANDWIDTH"]&&(f=parseInt(l["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const v=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0;let g;if(l.RESOLUTION){const[m,S]=l.RESOLUTION.split("x").map(A=>parseInt(A,10));m&&S&&(g={width:m,height:S})}const b=new URL(a[++o],e).toString();h&&n.push({id:c,quality:h,url:b,bandwidth:f,size:g,fps:v})}return n};var ie;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(ie||(ie={}));class Mm{constructor(e){var t;this.subscription=new re,this.videoState=new de(ie.STOPPED),this.textTracksManager=new Qe,this.manifests$=new T([]),this.liveOffset=new xr,this.manifestStartTime$=new T(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===p.STOPPED){r!==ie.STOPPED&&(this.videoState.startTransitionTo(ie.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ie.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(r===ie.STOPPED){this.videoState.startTransitionTo(ie.READY),this.prepare();return}if(o||u){const c=this.videoState.getState();this.videoState.setState(ie.CHANGING_MANIFEST),this.videoState.startTransitionTo(c),this.prepare(),l.state===z.None&&this.params.desiredState.seekState.setState({state:z.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==p.PAUSED&&l.state===z.Requested){this.videoState.startTransitionTo(ie.READY),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case ie.READY:a===p.READY?I(this.params.desiredState.playbackState,p.READY):a===p.PAUSED?(this.videoState.setState(ie.PAUSED),this.liveOffset.pause(),I(this.params.desiredState.playbackState,p.PAUSED)):a===p.PLAYING&&(this.videoState.startTransitionTo(ie.PLAYING),this.playIfAllowed());return;case ie.PLAYING:a===p.PAUSED?(this.videoState.startTransitionTo(ie.PAUSED),this.liveOffset.pause(),this.video.pause()):(n==null?void 0:n.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case ie.PAUSED:a===p.PLAYING?(this.videoState.startTransitionTo(ie.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)===p.PAUSED&&(I(this.params.desiredState.playbackState,p.PAUSED),this.liveOffset.pause());return;case ie.CHANGING_MANIFEST:break;default:return U(r)}},this.params=e,this.video=dt(e.container),this.params.output.element$.next(this.video);const i={id:"master",quality:Be.INVARIANT,url:this.params.source.url};this.manifests$.next([i]),Ao(Ht(this.params.source.url),this.params.source.url).then(r=>{this.manifests$.next([i,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:D.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 T((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:r}=this.params.desiredState,a=i.getState(),n=r.getTransition(),o=(t=(e=n==null?void 0:n.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",u=this.manifests$.getValue();if(!u)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:D.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=lt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.isAudioAvailable$,e.isAudioAvailable$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(ot(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(vt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ie.PLAYING),I(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ie.PAUSED),I(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ie.READY&&this.videoState.setState(ie.READY),this.videoState.getState()===ie.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(fe(),k(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(f=>f.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===ie.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===z.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(je({startTime:this.manifestStartTime$.pipe(te(_)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(k(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=V(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,_e(["init"])).pipe(Ie(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ut(this.video)}prepare(){const e=this.selectManifest();if(ee(e))return;const t=Ht(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),nn(t).then(i=>{var r;if(!ee(i))this.maxSeekBackTime$.next(i);else{const a=(r=this.params.source.maxSeekBackTime)!==null&&r!==void 0?r:this.maxSeekBackTime$.getValue();if(ee(a)||!isFinite(a))try{Yt(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();nn(d).then(l=>{ee(l)||this.maxSeekBackTime$.next(l)})}})}catch(n){}}})}playIfAllowed(){St(this.video).then(e=>{e||(this.videoState.setState(ie.PAUSED),this.liveOffset.pause(),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}var ne;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(ne||(ne={}));class Fm{constructor(e){this.subscription=new re,this.videoState=new de(ne.STOPPED),this.textTracksManager=new Qe,this.manifests$=new T([]),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===p.STOPPED){i!==ne.STOPPED&&(this.videoState.startTransitionTo(ne.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ne.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.seekState.getState();if(i===ne.STOPPED){this.videoState.startTransitionTo(ne.READY),this.prepare();return}if(n||o){const l=this.videoState.getState();this.videoState.setState(ne.CHANGING_MANIFEST),this.videoState.startTransitionTo(l);const{currentTime:c}=this.video;this.prepare(),d.state===z.None&&this.params.desiredState.seekState.setState({state:z.Requested,position:c*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==p.PAUSED&&d.state===z.Requested&&this.seek(d.position),i){case ne.READY:r===p.READY?I(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(ne.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(ne.PLAYING),this.playIfAllowed());return;case ne.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(ne.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case ne.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(ne.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;case ne.CHANGING_MANIFEST:break;default:return U(i)}},this.params=e,this.video=dt(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:Be.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)),Ao(this.params.source.url).then(i=>{this.manifests$.next([t,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:D.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:D.WTF,message:"HlsProvider internal logic error",thrown:o})},r=lt(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$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(Rt(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(vt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ne.PLAYING),I(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ne.PAUSED),I(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ne.READY&&this.videoState.setState(ne.READY),this.videoState.getState()===ne.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(f=>f.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===ne.CHANGING_MANIFEST&&this.videoState.setState(u.to),o.state===z.Requested&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(k(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=V(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,_e(["init"])).pipe(Ie(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ut(this.video)}prepare(){const e=this.selectManifest();ee(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){St(this.video).then(e=>{e||(this.videoState.setState(ne.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var le;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(le||(le={}));class Um{constructor(e){this.subscription=new re,this.videoState=new de(le.STOPPED),this.trackUrls={},this.textTracksManager=new Qe,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(i===p.STOPPED){t!==le.STOPPED&&(this.videoState.startTransitionTo(le.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(le.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(t===le.STOPPED){this.videoState.startTransitionTo(le.READY),this.prepare();return}if(n){const{currentTime:u}=this.video;this.prepare(),o.state===z.None&&this.params.desiredState.seekState.setState({state:z.Requested,position:u*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!==p.PAUSED&&o.state===z.Requested&&this.seek(o.position),t){case le.READY:i===p.READY?I(this.params.desiredState.playbackState,p.READY):i===p.PAUSED?(this.videoState.setState(le.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):i===p.PLAYING&&(this.videoState.startTransitionTo(le.PLAYING),this.playIfAllowed());return;case le.PLAYING:i===p.PAUSED?(this.videoState.startTransitionTo(le.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case le.PAUSED:i===p.PLAYING?(this.videoState.startTransitionTo(le.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return U(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:D.WTF,message:"MpegProvider internal logic error",thrown:o})},r=lt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.isAudioAvailable$,e.isAudioAvailable$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(Rt(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(vt(this.video,t.playbackRate,r.playbackRateState$,i)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(le.PLAYING),I(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(le.PAUSED),I(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===le.READY&&this.videoState.setState(le.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()===le.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const n=V(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,_e(["init"])).pipe(Ie(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ut(this.video)}prepare(){var e,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=qt(r)),this.video.setAttribute("src",r),this.video.load(),this.params.output.hostname$.next(Ae(r))}playIfAllowed(){St(this.video).then(e=>{e||(this.videoState.setState(le.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}const on=["stun:videostun.mycdn.me:80"],Vm=1e3,Hm=3,Gs=()=>null;class Ym{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=Gs,this.externalStopCallback=Gs,this.externalErrorCallback=Gs,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:on}]};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:D.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),Vm)}normalizeOptions(e={}){const t={stunServerList:on,maxRetryNumber:Hm,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var se;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(se||(se={}));class qm{constructor(e){this.videoState=new de(se.STOPPED),this.maxSeekBackTime$=new T(0),this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(i===p.STOPPED){t!==se.STOPPED&&(this.videoState.startTransitionTo(se.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(se.STOPPED),I(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===se.STOPPED){this.videoState.startTransitionTo(se.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case se.READY:i===p.PAUSED?(this.videoState.setState(se.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED)):i===p.PLAYING&&(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed());return;case se.PLAYING:i===p.PAUSED?(this.videoState.startTransitionTo(se.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&I(this.params.desiredState.playbackState,p.PLAYING);return;case se.PAUSED:i===p.PLAYING?(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&I(this.params.desiredState.playbackState,p.PAUSED);return;default:return U(t)}},this.subscription=new re,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=dt(e.container),this.liveStreamClient=new Ym(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ut(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:D.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};V(this.videoState.stateChangeStarted$.pipe(k(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(k(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const r=lt(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),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)===se.READY&&this.videoState.setState(se.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(se.PAUSED)},i)).add(r.playing$.subscribe(()=>{this.videoState.setState(se.PLAYING)},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(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 se.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(p.STOPPED);break;case se.READY:break;case se.PAUSED:t.playbackState.setState(p.PAUSED);break;case se.PLAYING:t.playbackState.setState(p.PLAYING);break;default:return U(n.to)}},i)).add(V(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,_e(["init"])).pipe(Ie(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:Be.INVARIANT}),this.video.srcObject=e,I(this.params.desiredState.playbackState,p.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(se.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:D.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){St(this.video).then(e=>{e||(this.videoState.setState(se.PAUSED),I(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class dn{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return Boolean(this.current.done)}}var zs,js,Ws,Qs,Js,Ks,Li,Xs,Ci,Zs,xi,er,Oi,tr,Bi,ir,Ni,sr;const wo=Zi().device===yn.Android,pt=document.createElement("video"),Gm='video/mp4; codecs="avc1.42000a,mp4a.40.2"',zm='video/mp4; codecs="hev1.1.6.L93.B0"',ko='video/webm; codecs="vp09.00.10.08"',_o='video/webm; codecs="av01.0.00M.08"',jm='audio/mp4; codecs="mp4a.40.2"',Wm='audio/webm; codecs="opus"',Oe={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&((js=(zs=window.SourceBuffer)===null||zs===void 0?void 0:zs.prototype)===null||js===void 0?void 0:js.appendBuffer)),hls:Boolean(((Ws=pt.canPlayType)===null||Ws===void 0?void 0:Ws.call(pt,"application/x-mpegurl"))||((Qs=pt.canPlayType)===null||Qs===void 0?void 0:Qs.call(pt,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection),ws:Boolean(window.WebSocket)},ke={mp4:Boolean((Js=pt.canPlayType)===null||Js===void 0?void 0:Js.call(pt,"video/mp4")),webm:Boolean((Ks=pt.canPlayType)===null||Ks===void 0?void 0:Ks.call(pt,"video/webm")),cmaf:!0},ze={h264:Boolean((Xs=(Li=window.MediaSource)===null||Li===void 0?void 0:Li.isTypeSupported)===null||Xs===void 0?void 0:Xs.call(Li,Gm)),h265:Boolean((Zs=(Ci=window.MediaSource)===null||Ci===void 0?void 0:Ci.isTypeSupported)===null||Zs===void 0?void 0:Zs.call(Ci,zm)),vp9:Boolean((er=(xi=window.MediaSource)===null||xi===void 0?void 0:xi.isTypeSupported)===null||er===void 0?void 0:er.call(xi,ko)),av1:Boolean((tr=(Oi=window.MediaSource)===null||Oi===void 0?void 0:Oi.isTypeSupported)===null||tr===void 0?void 0:tr.call(Oi,_o)),aac:Boolean((ir=(Bi=window.MediaSource)===null||Bi===void 0?void 0:Bi.isTypeSupported)===null||ir===void 0?void 0:ir.call(Bi,jm)),opus:Boolean((sr=(Ni=window.MediaSource)===null||Ni===void 0?void 0:Ni.isTypeSupported)===null||sr===void 0?void 0:sr.call(Ni,Wm))},Nt=(ze.h264||ze.h265)&&ze.aac;var Xe;(function(s){s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient"})(Xe||(Xe={}));let $t;const Qm=async()=>{if(!window.navigator.mediaCapabilities)return;const s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:_o}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:ko}})]);$t={[y.DASH_WEBM_AV1]:e,[y.DASH_WEBM]:t}};try{Qm()}catch(s){console.error(s)}const ls=Oe.hls&&ke.mp4,Jm=()=>Object.keys(ze).filter(s=>ze[s]),Km=(s,e=!1)=>s.filter(t=>{switch(t){case y.DASH:return Oe.mse&&ke.mp4&&Nt;case y.DASH_SEP:return Oe.mse&&ke.mp4&&Nt;case y.DASH_WEBM:return Oe.mse&&ke.webm&&ze.vp9&&ze.opus;case y.DASH_WEBM_AV1:return Oe.mse&&ke.webm&&ze.av1&&ze.opus;case y.DASH_LIVE:return Oe.mse&&ke.mp4&&Nt;case y.DASH_LIVE_CMAF:return Oe.mse&&ke.mp4&&Nt&&ke.cmaf;case y.DASH_ONDEMAND:return Oe.mse&&ke.mp4&&Nt;case y.HLS:case y.HLS_LIVE:case y.HLS_LIVE_CMAF:case y.HLS_ONDEMAND:return ls||e&&Oe.mse&&ke.mp4&&Nt;case y.MPEG:return ke.mp4;case y.DASH_LIVE_WEBM:return!1;case y.WEB_RTC_LIVE:return Oe.webrtc&&Oe.ws&&ze.h264&&(ke.mp4||ke.webm);default:return U(t)}}),rr=s=>{const e=y.DASH_WEBM,t=y.DASH_WEBM_AV1;switch(s){case Xe.VP9:return[e,t];case Xe.AV1:return[t,e];case Xe.NONE:return[];case Xe.SMOOTH:return $t?$t[t].smooth?[t,e]:$t[e].smooth?[e,t]:[t,e]:[e,t];case Xe.POWER_EFFICIENT:return $t?$t[t].powerEfficient?[t,e]:$t[e].powerEfficient?[e,t]:[t,e]:[e,t];default:U(s)}return[e,t]},Xm=(s=Xe.VP9)=>wo?[y.MPEG,...rr(s),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND]:ls?[...rr(s),y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG,y.DASH]:[...rr(s),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG],Zm=()=>wo?[y.HLS_LIVE,y.HLS_LIVE_CMAF,y.WEB_RTC_LIVE,y.DASH_LIVE,y.DASH_LIVE_CMAF]:ls?[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],un=s=>s?[y.HLS_LIVE]:[y.DASH_WEBM,y.DASH_WEBM_AV1,y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG];var ev=s=>new es(e=>{const t=new re,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(k(({from:d,to:l})=>`${d}-${l}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(k(({type:d})=>d!==void 0)),n=new x;let o=0,u="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>n.next(d),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const ln={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},tv={cacheDuration:12e4},iv={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},sv={maxPausedTime:3e4},cn={maxPausedTime:3e4};class rv{constructor(e){this.current$=new T({type:void 0}),this.providerError$=new x,this.noAvailableProvidersError$=new x,this.providerOutput={position$:new T(0),duration$:new T(1/0),volume$:new T({muted:!1,volume:1}),currentVideoTrack$:new T(void 0),availableVideoTracks$:new T([]),availableAudioTracks$:new T([]),isAudioAvailable$:new T(!0),autoVideoTrackLimitingAvailable$:new T(!1),currentBuffer$:new T(void 0),isBuffering$:new T(!0),error$:new x,willSeekEvent$:new x,seekedEvent$:new x,loopedEvent$:new x,endedEvent$:new x,firstBytesEvent$:new x,firstFrameEvent$:new x,canplay$:new x,isLive$:new T(void 0),liveTime$:new T(void 0),availableTextTracks$:new T([]),currentTextTrack$:new T(void 0),hostname$:new T(void 0),httpConnectionType$:new T(void 0),httpConnectionReused$:new T(void 0),inPiP$:new T(!1),inFullscreen$:new T(!1),element$:new T(void 0),availableSources$:new T(void 0)},this.subscription=new re,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Km([...Zm(),...Xm(this.params.tuning.webmCodec)],this.params.tuning.useHlsJs).filter(o=>_(e.sources[o])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning;let a=[];i?a=[i]:r.length?a=[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:a=t,this.screenFormatsIterator=new dn(a);const n=[...un(!0),...un(!1)];this.chromecastFormatsIterator=new dn(n.filter(o=>_(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(ee(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:D.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!==z.None;this.params.desiredState.seekState.setState({state:z.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 Ee.SCREEN:return this.createScreenProvider(t);case Ee.CHROMECAST:return this.createChromecastProvider(t);default:return U(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 wp({...n,source:o,config:tv})}case y.DASH_SEP:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return R(o),this.params.tuning.useDashJs?new Ga({...n,source:o,format:e,config:cn}):new xm({...n,source:o})}case y.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return R(o),new Ga({...n,source:o,format:e,config:cn})}case y.HLS:case y.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return R(o),ls||!this.params.tuning.useHlsJs?new Fm({...n,source:o}):new Bm({...n,source:o})}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return R(o),new Mm({...n,source:o,config:sv})}case y.MPEG:{const o=this.applyFailoverHost(t[e]);return R(o),new Um({...n,source:o})}case y.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return R(o),new yp({...n,source:o,config:iv})}case y.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return R(o),new qm({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 U(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 Af({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()?Ee.CHROMECAST:Ee.SCREEN}chooseFormat(e){switch(e){case Ee.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case Ee.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return U(e)}}skipFormat(e){switch(e){case Ee.SCREEN:return this.screenFormatsIterator.next();case Ee.CHROMECAST:return this.chromecastFormatsIterator.next();default:return U(e)}}handleNoFormatsError(e){switch(e){case Ee.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case Ee.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return U(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const 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 pi(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){const e=new re;let t=!1,i=0;return e.add(V(this.providerOutput.error$,ev({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:ln.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(k(r=>({id:`ProviderHangup:${r}`,category:D.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(te(({to:a})=>a===p.PLAYING),ge()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{const a=this.current$.getValue().destination;if(a===Ee.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(Ee.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=r.category===D.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),u=i<ln.providerErrorLimit;o&&(n&&t||!u)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):u?(i++,this.reinitProvider()):this.switchToNextProvider(a!=null?a:Ee.SCREEN)}})),e}}const Sr=(s,e,t)=>t*e+(1-t)*s,Po=(s,e)=>s.reduce((t,i)=>t+i,0)/e,av=(s,e,t,i)=>{let r=0,a=t;const n=Po(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};class Ro{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new T(e.initial),this.debounced$=new T(e.initial);const i=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ge(`raw_${i}`),this.smoothedSeries$=new Ge(`smoothed_${i}`),this.reportedSeries$=new Ge(`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)&&(ee(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class nv extends Ro{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Sr(this.slow,e,this.params.emaAlphaSlow),this.fast=Sr(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class ov extends Ro{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Po(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Sr(this.emaSmoothed,e,this.params.emaAlpha);const i=av(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class hn{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new nv({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new ov({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}}const dv=5e3,fn="one_video_throughput",pn="one_video_rtt",it=window.navigator.connection,mn=()=>{const s=it==null?void 0:it.downlink;if(_(s)&&s!==10)return s*1e3},vn=()=>{const s=it==null?void 0:it.rtt;if(_(s)&&s!==3e3)return s},Sn=(s,e,t)=>{const i=t*8,r=i/s;return i/(r+e)};class di{constructor(e){var t,i;this.subscription=new re,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=di.load(fn)||(e.useBrowserEstimation?mn():void 0)||dv,a=(i=(t=di.load(pn))!==null&&t!==void 0?t:e.useBrowserEstimation?vn():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new T(r),this.rtt$=new T(a),this.rttAdjustedThroughput$=new T(Sn(r,a,e.rttPenaltyRequestSize)),this.throughput=hn.getSmoothedValue(r,-1,e),this.rtt=hn.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const u=mn();u&&this.throughput.next(u);const d=vn();_(d)&&this.rtt.next(d)};it&&"onchange"in it&&this.subscription.add(M(it,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{gs.set(fn,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{gs.set(pn,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(je({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(k(({throughput:n,rtt:o})=>Sn(n,o,e.rttPenaltyRequestSize)),te(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=ce();const r=new re;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=ce()}));break;case 1:case 0:r.add(M(e,"loadstart").subscribe(()=>{t=0,i=ce()}));break}r.add(M(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=ce(),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=ce();let a=0,n=ce();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,ce()-r,1),this.concurrentDownloads.delete(e)):l&&(i+=l.byteLength,a+=l.byteLength,a>=this.tuningConfig.streamMinSampleSize&&ce()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,ce()-n,this.concurrentDownloads.size),a=0,n=ce()),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(di.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=gs.get(e);if(_(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const gn={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5},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,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,webmCodec:Xe.VP9,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}},uv=s=>{const e={};for(const t of Object.keys(gn)){const i=gn[t],r=s[t];Array.isArray(i)&&Array.isArray(r)?t==="configName"?e[t]=[...r,...i]:e[t]=r:typeof i=="object"&&typeof r=="object"?e[t]={...i,...r}:e[t]=r!=null?r:i}return e};var bn=({seekState:s,position$:e})=>V(s.stateChangeEnded$.pipe(k(({to:t})=>{var i;return t.state===z.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),te(_)),e.pipe(te(()=>s.getState().state===z.None))),lv=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return R(e,`Wrong container or containerId {${s.container}}`),e};class vv{constructor(e={configName:[]}){if(this.subscription=new re,this.logger=new Zo,this.isPlaybackStarted=!1,this.desiredState={playbackState:new de(p.STOPPED),seekState:new de({state:z.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([]),internalTextTracks:new de([]),currentTextTrack:new de(void 0),textTrackCuesSettings:new de({})},this.info={playbackState$:new T(p.STOPPED),position$:new T(0),duration$:new T(1/0),muted$:new T(!1),volume$:new T(1),availableQualities$:new T([]),availableQualitiesFps$:new T({}),availableAudioTracks$:new T([]),isAudioAvailable$:new T(!0),currentQuality$:new T(void 0),isAutoQualityEnabled$:new T(!0),autoQualityLimitingAvailable$:new T(!1),autoQualityLimits$:new T({}),currentPlaybackRate$:new T(1),currentBuffer$:new T({start:0,end:0}),isBuffering$:new T(!0),isStalled$:new T(!1),isEnded$:new T(!1),isLooped$:new T(!1),isLive$:new T(void 0),atLiveEdge$:new T(void 0),liveTime$:new T(void 0),currentFormat$:new T(void 0),availableTextTracks$:new T([]),currentTextTrack$:new T(void 0),throughputEstimation$:new T(void 0),rttEstimation$:new T(void 0),videoBitrate$:new T(void 0),hostname$:new T(void 0),httpConnectionType$:new T(void 0),httpConnectionReused$:new T(void 0),surface$:new T(ft.NONE),chromecastState$:new T(ye.NOT_AVAILABLE),chromecastDeviceName$:new T(void 0),intrinsicVideoSize$:new T(void 0),availableSources$:new T(void 0)},this.events={inited$:new x,ready$:new x,started$:new x,playing$:new x,paused$:new x,stopped$:new x,willStart$:new x,willResume$:new x,willPause$:new x,willStop$:new x,willDestruct$:new x,watchCoverageRecord$:new x,watchCoverageLive$:new x,managedError$:new x,fatalError$:new x,ended$:new x,looped$:new x,seeked$:new x,willSeek$:new x,firstBytes$:new x,firstFrame$:new x,canplay$:new x,log$:new x},this.experimental={element$:new T(void 0),tuningConfigName$:new T([]),enableDebugTelemetry$:new T(!1),dumpTelemetry:Zf},this.initLogs(),this.tuning=uv(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new rd({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new di(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{const a=Reflect.get(t,i,r);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const u=n.map(c=>JSON.stringify(c,(h,f)=>{const v=typeof f;return["number","string","boolean"].includes(v)?f:f===null?null:`<${v}>`})),d=`Player.${String(i)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:D.WTF,message:l,thrown:o}),o}}}})}initVideo(e){var t,i,r;return this.config=e,this.domContainer=lv(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new rv({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(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===p.STOPPED&&e.startTransitionTo(p.READY),this}play(){const e=this.desiredState.playbackState;return e.getState()!==p.PLAYING&&e.startTransitionTo(p.PLAYING),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==p.PAUSED&&e.startTransitionTo(p.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==p.STOPPED&&e.startTransitionTo(p.STOPPED),this}seekTime(e,t=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:z.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()===ye.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()===ye.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()}getExactTime(){R(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(ee(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===z.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(V(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(k(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(k(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(k(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(k(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(k(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(te(({from:e})=>e===p.STOPPED),ge()).subscribe(()=>{this.initedAt=ce(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case p.READY:this.events.ready$.next();break;case p.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case p.PAUSED:this.events.paused$.next();break;case p.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case p.PAUSED:this.events.willPause$.next();break;case p.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case p.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===z.Requested?this.desiredState.seekState.setState({...n,state:z.Applying}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:D.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===z.Applying&&(this.desiredState.seekState.setState({state:z.None}),this.events.seeked$.next())})).add(e.current$.pipe(k(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(k(n=>n.destination),fe()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(k(n=>n.map(({quality:o})=>o).sort((o,u)=>Yi(o)?1:Yi(u)?-1:Mi(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{const o={};for(const u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.hostname$.pipe(fe()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(fe()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(fe()).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(k(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(je({isLive:e.providerOutput.isLive$,position:bn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(k(({isLive:n,position:o})=>n&&o>-ed),fe()).subscribe(this.info.atLiveEdge$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(k(n=>n.muted),fe()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(k(n=>n.volume),fe()).subscribe(this.info.volume$)).add(bn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(V(e.providerOutput.endedEvent$.pipe(Vt(!0)),e.providerOutput.seekedEvent$.pipe(Vt(!1))).pipe(fe()).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(k(n=>({id:n?`No${n}`:"NoProviders",category:D.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(ge(),k(n=>n!=null?n:ce()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(ge(),k(()=>ce()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ge(),k(()=>ce()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new T(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new T(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(te(({to:n})=>n===p.PLAYING),ge()).subscribe(()=>i.next(!1)));let r=0;const a=V(e.providerOutput.isBuffering$,t,i).pipe(k(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),fe());this.subscription.add(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(V(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var o,u;const d=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(o=n==null?void 0:n.size)===null||o===void 0?void 0:o.width,height:(u=n==null?void 0:n.size)===null||u===void 0?void 0:u.height},{width:d==null?void 0:d.videoWidth,height:d==null?void 0:d.videoHeight})})),this.subscription.add(V(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),d=this.chromecastInitializer.castState$.getValue();let l;d===ye.CONNECTED?l=ft.SECOND_SCREEN:u?n?l=ft.PIP:o?l=ft.FULLSCREEN:l=ft.INLINE:l=ft.NONE,this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(k(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 re;this.subscription.add(t),this.subscription.add(e.current$.pipe(fe((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(te(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=mi(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(V(this.desiredState.videoTrack.stateChangeStarted$.pipe(k(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(k(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(k(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(k(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(k(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(k(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(k(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(k(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(k(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),Xf(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Kf(i)),this.providerContainer.current$.subscribe(({type:i})=>Ri("provider",i)),t.duration$.subscribe(i=>Ri("duration",i)),t.availableVideoTracks$.pipe(te(i=>!!i.length),ge()).subscribe(i=>Ri("tracks",i)),this.events.fatalError$.subscribe(new Ge("fatalError")),this.events.managedError$.subscribe(new Ge("managedError")),t.position$.subscribe(new Ge("position")),t.currentVideoTrack$.pipe(k(i=>i==null?void 0:i.quality)).subscribe(new Ge("quality")),this.info.currentBuffer$.subscribe(new Ge("buffer")),t.isBuffering$.subscribe(new Ge("isBuffering"))].forEach(i=>this.subscription.add(i)),Ri("codecs",Jm())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:D.DOM,message:String(r)})})};this.subscription.add(V(M(document,"visibilitychange"),M(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===p.PLAYING,n=Boolean(e)&&!(e!=null&&e.released);r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}}const Sv=`@vkontakte/videoplayer-core@${id}`;export{ye as ChromecastState,ui as HttpConnectionType,yv as Observable,p as PlaybackState,vv as Player,Sv as SDK_VERSION,Tv as Subject,Ev as Subscription,ft as Surface,id as VERSION,$v as ValueSubject,y as VideoFormat,Av as VideoQuality};
|