@vkontakte/videoplayer-core 2.0.85 → 2.0.86

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.esm.js CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.85
3
- * Fri, 28 Apr 2023 10:45:06 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-85/doc/
2
+ * @vkontakte/videoplayer-core v2.0.86
3
+ * Thu, 11 May 2023 16:24:35 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-86/doc/
5
5
  */
6
- import{ValueSubject as y,Subject as O,Subscription as se,isNonNullable as w,ErrorCategory as C,isNullable as K,fromEvent as U,assertNever as x,merge as L,tap as Qa,map as $,observableFrom as Oe,filterChanged as me,assertNonNullable as P,debounce as Ve,timeout as Yu,combine as dt,once as ye,mapTo as Ot,filter as j,now as pe,Observable as Ii,abortable as qe,getExponentialDelay as Ja,interval as qu,Logger as ju}from"@vkontakte/videoplayer-shared/es2015.esm.js";import{Observable as Uy,Subject as Fy,Subscription as Vy,ValueSubject as Hy}from"@vkontakte/videoplayer-shared/es2015.esm.js";import zu from"lodash/debounce.js";const Wu="2.0.85",Qu="es2015.esm.js";var v;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(v||(v={}));var b;(function(i){i.MPEG="MPEG",i.DASH="DASH",i.DASH_SEP="DASH_SEP",i.DASH_SEP_VK="DASH_SEP",i.DASH_WEBM="DASH_WEBM",i.DASH_WEBM_VK="DASH_WEBM",i.DASH_ONDEMAND="DASH_ONDEMAND",i.DASH_ONDEMAND_VK="DASH_ONDEMAND",i.DASH_LIVE="DASH_LIVE",i.DASH_LIVE_CMAF="DASH_LIVE_CMAF",i.DASH_LIVE_WEBM="DASH_LIVE_WEBM",i.HLS="HLS",i.HLS_ONDEMAND="HLS_ONDEMAND",i.HLS_JS="HLS",i.HLS_LIVE="HLS_LIVE",i.HLS_LIVE_CMAF="HLS_LIVE_CMAF",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(b||(b={}));var De;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(De||(De={}));var _e;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(_e||(_e={}));var ki;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(ki||(ki={}));var H;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(H||(H={}));function ue(i,e,t,s){function r(a){return a instanceof t?a:new t(function(n){n(a)})}return new(t||(t=Promise))(function(a,n){function o(l){try{d(s.next(l))}catch(c){n(c)}}function u(l){try{d(s.throw(l))}catch(c){n(c)}}function d(l){l.done?a(l.value):r(l.value).then(o,u)}d((s=s.apply(i,e||[])).next())})}function M(i){return this instanceof M?(this.v=i,this):new M(i)}function je(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=t.apply(i,e||[]),r,a=[];return r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r;function n(h){s[h]&&(r[h]=function(f){return new Promise(function(m,p){a.push([h,f,m,p])>1||o(h,f)})})}function o(h,f){try{u(s[h](f))}catch(m){c(a[0][3],m)}}function u(h){h.value instanceof M?Promise.resolve(h.value.v).then(d,l):c(a[0][2],h)}function d(h){o("next",h)}function l(h){o("throw",h)}function c(h,f){h(f),a.shift(),a.length&&o(a[0][0],a[0][1])}}var Ju=i=>new Promise((e,t)=>{const s=document.createElement("script");s.setAttribute("src",i),s.onload=()=>e,s.onerror=()=>t,document.body.appendChild(s)});class Ku{constructor(e){var t;this.connection$=new y(void 0),this.castState$=new y(_e.NOT_AVAILABLE),this.errorEvent$=new O,this.realCastState$=new y(_e.NOT_AVAILABLE),this.subscription=new se,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const s="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)return;const r=w((t=window.chrome)===null||t===void 0?void 0:t.cast),a=Boolean(window.__onGCastApiAvailable);r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||Ju("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:C.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var s,r,a;(a=(r=(s=cast.framework.CastContext.getInstance())===null||s===void 0?void 0:s.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||a===void 0||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){w(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();K(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();K(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),s=cast.framework.CastContext.getInstance();this.subscription.add(U(s,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=s.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 x(r.sessionState)}})).add(L(U(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Qa(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),$(r=>r.castState)),Oe([s.getCastState()])).pipe(me(),$(Xu),Qa(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===_e.CONNECTED,o=w(this.connection$.getValue());if(n&&!o){const u=s.getCurrentSession();P(u);const d=u.getCastDevice(),l=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(K(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===_e.CONNECTED?w(this.connection$.getValue())?_e.CONNECTED:_e.AVAILABLE:r)}))}initializeCastApi(){var e;let t,s,r;try{t=cast.framework.CastContext.getInstance(),s=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:s,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:C.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const Xu=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return _e.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return _e.AVAILABLE;case cast.framework.CastState.CONNECTING:return _e.CONNECTING;case cast.framework.CastState.CONNECTED:return _e.CONNECTED;default:return x(i)}};var Ka=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},He=function(i){try{return!!i()}catch(e){return!0}},Zu=He,Is=!Zu(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),qo=Is,jo=Function.prototype,Yr=jo.call,el=qo&&jo.bind.bind(Yr,Yr),Ge=qo?el:function(i){return function(){return Yr.apply(i,arguments)}},zo=Ge,tl=zo({}.toString),il=zo("".slice),Di=function(i){return il(tl(i),8,-1)},sl=Ge,rl=He,al=Di,zs=Object,nl=sl("".split),ol=rl(function(){return!zs("z").propertyIsEnumerable(0)})?function(i){return al(i)=="String"?nl(i,""):zs(i)}:zs,Ci=function(i){return i==null},dl=Ci,ul=TypeError,fa=function(i){if(dl(i))throw ul("Can't call method on "+i);return i},ll=ol,cl=fa,Oi=function(i){return ll(cl(i))},hl=function(){},ri={},ji=function(i){return i&&i.Math==Math&&i},we=ji(typeof globalThis=="object"&&globalThis)||ji(typeof window=="object"&&window)||ji(typeof self=="object"&&self)||ji(typeof Ka=="object"&&Ka)||function(){return this}()||Function("return this")(),qr=typeof document=="object"&&document.all,fl=typeof qr=="undefined"&&qr!==void 0,Wo={all:qr,IS_HTMLDDA:fl},Qo=Wo,pl=Qo.all,Te=Qo.IS_HTMLDDA?function(i){return typeof i=="function"||i===pl}:function(i){return typeof i=="function"},vl=we,ml=Te,Xa=vl.WeakMap,Sl=ml(Xa)&&/native code/.test(String(Xa)),Za=Te,Jo=Wo,gl=Jo.all,ct=Jo.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:Za(i)||i===gl}:function(i){return typeof i=="object"?i!==null:Za(i)},bl=He,ht=!bl(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),xt={},yl=we,en=ct,jr=yl.document,Tl=en(jr)&&en(jr.createElement),pa=function(i){return Tl?jr.createElement(i):{}},El=ht,$l=He,Al=pa,Ko=!El&&!$l(function(){return Object.defineProperty(Al("div"),"a",{get:function(){return 7}}).a!=7}),_l=ht,wl=He,Xo=_l&&wl(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),kl=ct,Pl=String,Rl=TypeError,ft=function(i){if(kl(i))return i;throw Rl(Pl(i)+" is not an object")},Il=Is,zi=Function.prototype.call,Le=Il?zi.bind(zi):function(){return zi.apply(zi,arguments)},va={},Ws=va,Qs=we,Dl=Te,tn=function(i){return Dl(i)?i:void 0},Nt=function(i,e){return arguments.length<2?tn(Ws[i])||tn(Qs[i]):Ws[i]&&Ws[i][e]||Qs[i]&&Qs[i][e]},Cl=Ge,Ds=Cl({}.isPrototypeOf),Cs=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Zo=we,Js=Cs,sn=Zo.process,rn=Zo.Deno,an=sn&&sn.versions||rn&&rn.version,nn=an&&an.v8,Ye,bs;nn&&(Ye=nn.split("."),bs=Ye[0]>0&&Ye[0]<4?1:+(Ye[0]+Ye[1]));!bs&&Js&&(Ye=Js.match(/Edge\/(\d+)/),(!Ye||Ye[1]>=74)&&(Ye=Js.match(/Chrome\/(\d+)/),Ye&&(bs=+Ye[1])));var ed=bs,on=ed,Ol=He,td=!!Object.getOwnPropertySymbols&&!Ol(function(){var i=Symbol();return!String(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&on&&on<41}),Ll=td,id=Ll&&!Symbol.sham&&typeof Symbol.iterator=="symbol",xl=Nt,Nl=Te,Bl=Ds,Ml=id,Ul=Object,sd=Ml?function(i){return typeof i=="symbol"}:function(i){var e=xl("Symbol");return Nl(e)&&Bl(e.prototype,Ul(i))},Fl=String,Os=function(i){try{return Fl(i)}catch(e){return"Object"}},Vl=Te,Hl=Os,Gl=TypeError,Bt=function(i){if(Vl(i))return i;throw Gl(Hl(i)+" is not a function")},Yl=Bt,ql=Ci,Ls=function(i,e){var t=i[e];return ql(t)?void 0:Yl(t)},Ks=Le,Xs=Te,Zs=ct,jl=TypeError,zl=function(i,e){var t,s;if(e==="string"&&Xs(t=i.toString)&&!Zs(s=Ks(t,i))||Xs(t=i.valueOf)&&!Zs(s=Ks(t,i))||e!=="string"&&Xs(t=i.toString)&&!Zs(s=Ks(t,i)))return s;throw jl("Can't convert object to primitive value")},ys={},Wl={get exports(){return ys},set exports(i){ys=i}},rd=!0,dn=we,Ql=Object.defineProperty,Jl=function(i,e){try{Ql(dn,i,{value:e,configurable:!0,writable:!0})}catch(t){dn[i]=e}return e},Kl=we,Xl=Jl,un="__core-js_shared__",Zl=Kl[un]||Xl(un,{}),ma=Zl,ln=ma;(Wl.exports=function(i,e){return ln[i]||(ln[i]=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 ec=fa,tc=Object,xs=function(i){return tc(ec(i))},ic=Ge,sc=xs,rc=ic({}.hasOwnProperty),tt=Object.hasOwn||function(e,t){return rc(sc(e),t)},ac=Ge,nc=0,oc=Math.random(),dc=ac(1 .toString),ad=function(i){return"Symbol("+(i===void 0?"":i)+")_"+dc(++nc+oc,36)},uc=we,lc=ys,cn=tt,cc=ad,hc=td,fc=id,Wt=uc.Symbol,er=lc("wks"),pc=fc?Wt.for||Wt:Wt&&Wt.withoutSetter||cc,ke=function(i){return cn(er,i)||(er[i]=hc&&cn(Wt,i)?Wt[i]:pc("Symbol."+i)),er[i]},vc=Le,hn=ct,fn=sd,mc=Ls,Sc=zl,gc=ke,bc=TypeError,yc=gc("toPrimitive"),Tc=function(i,e){if(!hn(i)||fn(i))return i;var t=mc(i,yc),s;if(t){if(e===void 0&&(e="default"),s=vc(t,i,e),!hn(s)||fn(s))return s;throw bc("Can't convert object to primitive value")}return e===void 0&&(e="number"),Sc(i,e)},Ec=Tc,$c=sd,Sa=function(i){var e=Ec(i,"string");return $c(e)?e:e+""},Ac=ht,_c=Ko,wc=Xo,Wi=ft,pn=Sa,kc=TypeError,tr=Object.defineProperty,Pc=Object.getOwnPropertyDescriptor,ir="enumerable",sr="configurable",rr="writable";xt.f=Ac?wc?function(e,t,s){if(Wi(e),t=pn(t),Wi(s),typeof e=="function"&&t==="prototype"&&"value"in s&&rr in s&&!s[rr]){var r=Pc(e,t);r&&r[rr]&&(e[t]=s.value,s={configurable:sr in s?s[sr]:r[sr],enumerable:ir in s?s[ir]:r[ir],writable:!1})}return tr(e,t,s)}:tr:function(e,t,s){if(Wi(e),t=pn(t),Wi(s),_c)try{return tr(e,t,s)}catch(r){}if("get"in s||"set"in s)throw kc("Accessors not supported");return"value"in s&&(e[t]=s.value),e};var Ns=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},Rc=ht,Ic=xt,Dc=Ns,Li=Rc?function(i,e,t){return Ic.f(i,e,Dc(1,t))}:function(i,e,t){return i[e]=t,i},Cc=ys,Oc=ad,vn=Cc("keys"),ga=function(i){return vn[i]||(vn[i]=Oc(i))},ba={},Lc=Sl,nd=we,xc=ct,Nc=Li,ar=tt,nr=ma,Bc=ga,Mc=ba,mn="Object already initialized",zr=nd.TypeError,Uc=nd.WeakMap,Ts,Pi,Es,Fc=function(i){return Es(i)?Pi(i):Ts(i,{})},Vc=function(i){return function(e){var t;if(!xc(e)||(t=Pi(e)).type!==i)throw zr("Incompatible receiver, "+i+" required");return t}};if(Lc||nr.state){var Xe=nr.state||(nr.state=new Uc);Xe.get=Xe.get,Xe.has=Xe.has,Xe.set=Xe.set,Ts=function(i,e){if(Xe.has(i))throw zr(mn);return e.facade=i,Xe.set(i,e),e},Pi=function(i){return Xe.get(i)||{}},Es=function(i){return Xe.has(i)}}else{var Ht=Bc("state");Mc[Ht]=!0,Ts=function(i,e){if(ar(i,Ht))throw zr(mn);return e.facade=i,Nc(i,Ht,e),e},Pi=function(i){return ar(i,Ht)?i[Ht]:{}},Es=function(i){return ar(i,Ht)}}var od={set:Ts,get:Pi,has:Es,enforce:Fc,getterFor:Vc},Hc=Is,dd=Function.prototype,Sn=dd.apply,gn=dd.call,ud=typeof Reflect=="object"&&Reflect.apply||(Hc?gn.bind(Sn):function(){return gn.apply(Sn,arguments)}),Gc=Di,Yc=Ge,ld=function(i){if(Gc(i)==="Function")return Yc(i)},ya={},cd={},hd={}.propertyIsEnumerable,fd=Object.getOwnPropertyDescriptor,qc=fd&&!hd.call({1:2},1);cd.f=qc?function(e){var t=fd(this,e);return!!t&&t.enumerable}:hd;var jc=ht,zc=Le,Wc=cd,Qc=Ns,Jc=Oi,Kc=Sa,Xc=tt,Zc=Ko,bn=Object.getOwnPropertyDescriptor;ya.f=jc?bn:function(e,t){if(e=Jc(e),t=Kc(t),Zc)try{return bn(e,t)}catch(s){}if(Xc(e,t))return Qc(!zc(Wc.f,e,t),e[t])};var eh=He,th=Te,ih=/#|\.prototype\./,xi=function(i,e){var t=rh[sh(i)];return t==nh?!0:t==ah?!1:th(e)?eh(e):!!e},sh=xi.normalize=function(i){return String(i).replace(ih,".").toLowerCase()},rh=xi.data={},ah=xi.NATIVE="N",nh=xi.POLYFILL="P",pd=xi,yn=ld,oh=Bt,dh=Is,uh=yn(yn.bind),Bs=function(i,e){return oh(i),e===void 0?i:dh?uh(i,e):function(){return i.apply(e,arguments)}},Qi=we,lh=ud,ch=ld,hh=Te,fh=ya.f,ph=pd,Gt=va,vh=Bs,Yt=Li,Tn=tt,mh=function(i){var e=function(t,s,r){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,s)}return new i(t,s,r)}return lh(i,this,arguments)};return e.prototype=i.prototype,e},We=function(i,e){var t=i.target,s=i.global,r=i.stat,a=i.proto,n=s?Qi:r?Qi[t]:(Qi[t]||{}).prototype,o=s?Gt:Gt[t]||Yt(Gt,t,{})[t],u=o.prototype,d,l,c,h,f,m,p,S,g;for(h in e)d=ph(s?h:t+(r?".":"#")+h,i.forced),l=!d&&n&&Tn(n,h),m=o[h],l&&(i.dontCallGetSet?(g=fh(n,h),p=g&&g.value):p=n[h]),f=l&&p?p:e[h],!(l&&typeof m==typeof f)&&(i.bind&&l?S=vh(f,Qi):i.wrap&&l?S=mh(f):a&&hh(f)?S=ch(f):S=f,(i.sham||f&&f.sham||m&&m.sham)&&Yt(S,"sham",!0),Yt(o,h,S),a&&(c=t+"Prototype",Tn(Gt,c)||Yt(Gt,c,{}),Yt(Gt[c],h,f),i.real&&u&&(d||!u[h])&&Yt(u,h,f)))},Wr=ht,Sh=tt,vd=Function.prototype,gh=Wr&&Object.getOwnPropertyDescriptor,Ta=Sh(vd,"name"),bh=Ta&&function(){}.name==="something",yh=Ta&&(!Wr||Wr&&gh(vd,"name").configurable),Th={EXISTS:Ta,PROPER:bh,CONFIGURABLE:yh},md={},Eh=Math.ceil,$h=Math.floor,Ah=Math.trunc||function(e){var t=+e;return(t>0?$h:Eh)(t)},_h=Ah,Ea=function(i){var e=+i;return e!==e||e===0?0:_h(e)},wh=Ea,kh=Math.max,Ph=Math.min,Rh=function(i,e){var t=wh(i);return t<0?kh(t+e,0):Ph(t,e)},Ih=Ea,Dh=Math.min,Ch=function(i){return i>0?Dh(Ih(i),9007199254740991):0},Oh=Ch,$a=function(i){return Oh(i.length)},Lh=Oi,xh=Rh,Nh=$a,En=function(i){return function(e,t,s){var r=Lh(e),a=Nh(r),n=xh(s,a),o;if(i&&t!=t){for(;a>n;)if(o=r[n++],o!=o)return!0}else for(;a>n;n++)if((i||n in r)&&r[n]===t)return i||n||0;return!i&&-1}},Bh={includes:En(!0),indexOf:En(!1)},Mh=Ge,or=tt,Uh=Oi,Fh=Bh.indexOf,Vh=ba,$n=Mh([].push),Hh=function(i,e){var t=Uh(i),s=0,r=[],a;for(a in t)!or(Vh,a)&&or(t,a)&&$n(r,a);for(;e.length>s;)or(t,a=e[s++])&&(~Fh(r,a)||$n(r,a));return r},Sd=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Gh=Hh,Yh=Sd,qh=Object.keys||function(e){return Gh(e,Yh)},jh=ht,zh=Xo,Wh=xt,Qh=ft,Jh=Oi,Kh=qh;md.f=jh&&!zh?Object.defineProperties:function(e,t){Qh(e);for(var s=Jh(t),r=Kh(t),a=r.length,n=0,o;a>n;)Wh.f(e,o=r[n++],s[o]);return e};var Xh=Nt,gd=Xh("document","documentElement"),Zh=ft,ef=md,An=Sd,tf=ba,sf=gd,rf=pa,af=ga,_n=">",wn="<",Qr="prototype",Jr="script",bd=af("IE_PROTO"),dr=function(){},yd=function(i){return wn+Jr+_n+i+wn+"/"+Jr+_n},kn=function(i){i.write(yd("")),i.close();var e=i.parentWindow.Object;return i=null,e},nf=function(){var i=rf("iframe"),e="java"+Jr+":",t;return i.style.display="none",sf.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(yd("document.F=Object")),t.close(),t.F},Ji,ps=function(){try{Ji=new ActiveXObject("htmlfile")}catch(e){}ps=typeof document!="undefined"?document.domain&&Ji?kn(Ji):nf():kn(Ji);for(var i=An.length;i--;)delete ps[Qr][An[i]];return ps()};tf[bd]=!0;var Td=Object.create||function(e,t){var s;return e!==null?(dr[Qr]=Zh(e),s=new dr,dr[Qr]=null,s[bd]=e):s=ps(),t===void 0?s:ef.f(s,t)},of=He,df=!of(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),uf=tt,lf=Te,cf=xs,hf=ga,ff=df,Pn=hf("IE_PROTO"),Kr=Object,pf=Kr.prototype,Ed=ff?Kr.getPrototypeOf:function(i){var e=cf(i);if(uf(e,Pn))return e[Pn];var t=e.constructor;return lf(t)&&e instanceof t?t.prototype:e instanceof Kr?pf:null},vf=Li,Aa=function(i,e,t,s){return s&&s.enumerable?i[e]=t:vf(i,e,t),i},mf=He,Sf=Te,gf=ct,bf=Td,Rn=Ed,yf=Aa,Tf=ke,Xr=Tf("iterator"),$d=!1,ut,ur,lr;[].keys&&(lr=[].keys(),"next"in lr?(ur=Rn(Rn(lr)),ur!==Object.prototype&&(ut=ur)):$d=!0);var Ef=!gf(ut)||mf(function(){var i={};return ut[Xr].call(i)!==i});Ef?ut={}:ut=bf(ut);Sf(ut[Xr])||yf(ut,Xr,function(){return this});var Ad={IteratorPrototype:ut,BUGGY_SAFARI_ITERATORS:$d},$f=ke,Af=$f("toStringTag"),_d={};_d[Af]="z";var _a=String(_d)==="[object z]",_f=_a,wf=Te,vs=Di,kf=ke,Pf=kf("toStringTag"),Rf=Object,If=vs(function(){return arguments}())=="Arguments",Df=function(i,e){try{return i[e]}catch(t){}},Ni=_f?vs:function(i){var e,t,s;return i===void 0?"Undefined":i===null?"Null":typeof(t=Df(e=Rf(i),Pf))=="string"?t:If?vs(e):(s=vs(e))=="Object"&&wf(e.callee)?"Arguments":s},Cf=_a,Of=Ni,Lf=Cf?{}.toString:function(){return"[object "+Of(this)+"]"},xf=_a,Nf=xt.f,Bf=Li,Mf=tt,Uf=Lf,Ff=ke,In=Ff("toStringTag"),wa=function(i,e,t,s){if(i){var r=t?i:i.prototype;Mf(r,In)||Nf(r,In,{configurable:!0,value:e}),s&&!xf&&Bf(r,"toString",Uf)}},Vf=Ad.IteratorPrototype,Hf=Td,Gf=Ns,Yf=wa,qf=ri,jf=function(){return this},zf=function(i,e,t,s){var r=e+" Iterator";return i.prototype=Hf(Vf,{next:Gf(+!s,t)}),Yf(i,r,!1,!0),qf[r]=jf,i},Wf=We,Qf=Le,wd=Th,Jf=zf,Kf=Ed,Xf=wa,Dn=Aa,Zf=ke,Cn=ri,kd=Ad,ep=wd.PROPER;wd.CONFIGURABLE;kd.IteratorPrototype;var Ki=kd.BUGGY_SAFARI_ITERATORS,cr=Zf("iterator"),On="keys",Xi="values",Ln="entries",tp=function(){return this},ip=function(i,e,t,s,r,a,n){Jf(t,e,s);var o=function(g){if(g===r&&h)return h;if(!Ki&&g in l)return l[g];switch(g){case On:return function(){return new t(this,g)};case Xi:return function(){return new t(this,g)};case Ln:return function(){return new t(this,g)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,l=i.prototype,c=l[cr]||l["@@iterator"]||r&&l[r],h=!Ki&&c||o(r),f=e=="Array"&&l.entries||c,m,p,S;if(f&&(m=Kf(f.call(new i)),m!==Object.prototype&&m.next&&(Xf(m,u,!0,!0),Cn[u]=tp)),ep&&r==Xi&&c&&c.name!==Xi&&(d=!0,h=function(){return Qf(c,this)}),r)if(p={values:o(Xi),keys:a?h:o(On),entries:o(Ln)},n)for(S in p)(Ki||d||!(S in l))&&Dn(l,S,p[S]);else Wf({target:e,proto:!0,forced:Ki||d},p);return n&&l[cr]!==h&&Dn(l,cr,h,{name:r}),Cn[e]=h,p},sp=function(i,e){return{value:i,done:e}},rp=Oi,ka=hl,xn=ri,Pd=od,ap=xt.f,np=ip,Zi=sp,op=rd,dp=ht,Rd="Array Iterator",up=Pd.set,lp=Pd.getterFor(Rd);np(Array,"Array",function(i,e){up(this,{type:Rd,target:rp(i),index:0,kind:e})},function(){var i=lp(this),e=i.target,t=i.kind,s=i.index++;return!e||s>=e.length?(i.target=void 0,Zi(void 0,!0)):t=="keys"?Zi(s,!1):t=="values"?Zi(e[s],!1):Zi([s,e[s]],!1)},"values");var Nn=xn.Arguments=xn.Array;ka();ka();ka();if(!op&&dp&&Nn.name!=="values")try{ap(Nn,"name",{value:"values"})}catch(i){}var cp=ke,hp=ri,fp=cp("iterator"),pp=Array.prototype,vp=function(i){return i!==void 0&&(hp.Array===i||pp[fp]===i)},mp=Ni,Bn=Ls,Sp=Ci,gp=ri,bp=ke,yp=bp("iterator"),Id=function(i){if(!Sp(i))return Bn(i,yp)||Bn(i,"@@iterator")||gp[mp(i)]},Tp=Le,Ep=Bt,$p=ft,Ap=Os,_p=Id,wp=TypeError,kp=function(i,e){var t=arguments.length<2?_p(i):e;if(Ep(t))return $p(Tp(t,i));throw wp(Ap(i)+" is not iterable")},Pp=Le,Mn=ft,Rp=Ls,Ip=function(i,e,t){var s,r;Mn(i);try{if(s=Rp(i,"return"),!s){if(e==="throw")throw t;return t}s=Pp(s,i)}catch(a){r=!0,s=a}if(e==="throw")throw t;if(r)throw s;return Mn(s),t},Dp=Bs,Cp=Le,Op=ft,Lp=Os,xp=vp,Np=$a,Un=Ds,Bp=kp,Mp=Id,Fn=Ip,Up=TypeError,ms=function(i,e){this.stopped=i,this.result=e},Vn=ms.prototype,Pa=function(i,e,t){var s=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=Dp(e,s),d,l,c,h,f,m,p,S=function(T){return d&&Fn(d,"normal",T),new ms(!0,T)},g=function(T){return r?(Op(T),o?u(T[0],T[1],S):u(T[0],T[1])):o?u(T,S):u(T)};if(a)d=i.iterator;else if(n)d=i;else{if(l=Mp(i),!l)throw Up(Lp(i)+" is not iterable");if(xp(l)){for(c=0,h=Np(i);h>c;c++)if(f=g(i[c]),f&&Un(Vn,f))return f;return new ms(!1)}d=Bp(i,l)}for(m=a?i.next:d.next;!(p=Cp(m,d)).done;){try{f=g(p.value)}catch(T){Fn(d,"throw",T)}if(typeof f=="object"&&f&&Un(Vn,f))return f}return new ms(!1)},Fp=Sa,Vp=xt,Hp=Ns,Gp=function(i,e,t){var s=Fp(e);s in i?Vp.f(i,s,Hp(0,t)):i[s]=t},Yp=We,qp=Pa,jp=Gp;Yp({target:"Object",stat:!0},{fromEntries:function(e){var t={};return qp(e,function(s,r){jp(t,s,r)},{AS_ENTRIES:!0}),t}});var zp=va,Wp=zp.Object.fromEntries,Qp={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},Jp=Qp,Kp=we,Xp=Ni,Zp=Li,Hn=ri,ev=ke,Gn=ev("toStringTag");for(var hr in Jp){var Yn=Kp[hr],fr=Yn&&Yn.prototype;fr&&Xp(fr)!==Gn&&Zp(fr,Gn,hr),Hn[hr]=Hn.Array}var tv=Wp,iv=tv,sv=iv,rv=sv,Bi=rv,av=Di,Ms=typeof process!="undefined"&&av(process)=="process",nv=Nt,ov=xt,dv=ke,uv=ht,qn=dv("species"),lv=function(i){var e=nv(i),t=ov.f;uv&&e&&!e[qn]&&t(e,qn,{configurable:!0,get:function(){return this}})},cv=Ds,hv=TypeError,fv=function(i,e){if(cv(e,i))return i;throw hv("Incorrect invocation")},pv=Ge,vv=Te,Zr=ma,mv=pv(Function.toString);vv(Zr.inspectSource)||(Zr.inspectSource=function(i){return mv(i)});var Dd=Zr.inspectSource,Sv=Ge,gv=He,Cd=Te,bv=Ni,yv=Nt,Tv=Dd,Od=function(){},Ev=[],Ld=yv("Reflect","construct"),Ra=/^\s*(?:class|function)\b/,$v=Sv(Ra.exec),Av=!Ra.exec(Od),gi=function(e){if(!Cd(e))return!1;try{return Ld(Od,Ev,e),!0}catch(t){return!1}},xd=function(e){if(!Cd(e))return!1;switch(bv(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Av||!!$v(Ra,Tv(e))}catch(t){return!0}};xd.sham=!0;var _v=!Ld||gv(function(){var i;return gi(gi.call)||!gi(Object)||!gi(function(){i=!0})||i})?xd:gi,wv=_v,kv=Os,Pv=TypeError,Rv=function(i){if(wv(i))return i;throw Pv(kv(i)+" is not a constructor")},jn=ft,Iv=Rv,Dv=Ci,Cv=ke,Ov=Cv("species"),Nd=function(i,e){var t=jn(i).constructor,s;return t===void 0||Dv(s=jn(t)[Ov])?e:Iv(s)},Lv=Ge,xv=Lv([].slice),Nv=TypeError,Bv=function(i,e){if(i<e)throw Nv("Not enough arguments");return i},Mv=Cs,Bd=/(?:ipad|iphone|ipod).*applewebkit/i.test(Mv),Ce=we,Uv=ud,Fv=Bs,zn=Te,Vv=tt,Md=He,Wn=gd,Hv=xv,Qn=pa,Gv=Bv,Yv=Bd,qv=Ms,ea=Ce.setImmediate,ta=Ce.clearImmediate,jv=Ce.process,pr=Ce.Dispatch,zv=Ce.Function,Jn=Ce.MessageChannel,Wv=Ce.String,vr=0,Ei={},Kn="onreadystatechange",Ri,Rt,mr,Sr;Md(function(){Ri=Ce.location});var Ia=function(i){if(Vv(Ei,i)){var e=Ei[i];delete Ei[i],e()}},gr=function(i){return function(){Ia(i)}},Xn=function(i){Ia(i.data)},Zn=function(i){Ce.postMessage(Wv(i),Ri.protocol+"//"+Ri.host)};(!ea||!ta)&&(ea=function(e){Gv(arguments.length,1);var t=zn(e)?e:zv(e),s=Hv(arguments,1);return Ei[++vr]=function(){Uv(t,void 0,s)},Rt(vr),vr},ta=function(e){delete Ei[e]},qv?Rt=function(i){jv.nextTick(gr(i))}:pr&&pr.now?Rt=function(i){pr.now(gr(i))}:Jn&&!Yv?(mr=new Jn,Sr=mr.port2,mr.port1.onmessage=Xn,Rt=Fv(Sr.postMessage,Sr)):Ce.addEventListener&&zn(Ce.postMessage)&&!Ce.importScripts&&Ri&&Ri.protocol!=="file:"&&!Md(Zn)?(Rt=Zn,Ce.addEventListener("message",Xn,!1)):Kn in Qn("script")?Rt=function(i){Wn.appendChild(Qn("script"))[Kn]=function(){Wn.removeChild(this),Ia(i)}}:Rt=function(i){setTimeout(gr(i),0)});var Ud={set:ea,clear:ta},Fd=function(){this.head=null,this.tail=null};Fd.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};var Vd=Fd,Qv=Cs,Jv=/ipad|iphone|ipod/i.test(Qv)&&typeof Pebble!="undefined",Kv=Cs,Xv=/web0s(?!.*chrome)/i.test(Kv),Lt=we,eo=Bs,Zv=ya.f,br=Ud.set,em=Vd,tm=Bd,im=Jv,sm=Xv,yr=Ms,to=Lt.MutationObserver||Lt.WebKitMutationObserver,io=Lt.document,so=Lt.process,es=Lt.Promise,ro=Zv(Lt,"queueMicrotask"),ia=ro&&ro.value,qt,Tr,Er,ts,ao;if(!ia){var is=new em,ss=function(){var i,e;for(yr&&(i=so.domain)&&i.exit();e=is.get();)try{e()}catch(t){throw is.head&&qt(),t}i&&i.enter()};!tm&&!yr&&!sm&&to&&io?(Tr=!0,Er=io.createTextNode(""),new to(ss).observe(Er,{characterData:!0}),qt=function(){Er.data=Tr=!Tr}):!im&&es&&es.resolve?(ts=es.resolve(void 0),ts.constructor=es,ao=eo(ts.then,ts),qt=function(){ao(ss)}):yr?qt=function(){so.nextTick(ss)}:(br=eo(br,Lt),qt=function(){br(ss)}),ia=function(i){is.head||qt(),is.add(i)}}var rm=ia,am=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},Da=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},nm=we,ai=nm.Promise,Hd=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",om=Hd,dm=Ms,um=!om&&!dm&&typeof window=="object"&&typeof document=="object",lm=we,$i=ai,cm=Te,hm=pd,fm=Dd,pm=ke,vm=um,mm=Hd,$r=ed,no=$i&&$i.prototype,Sm=pm("species"),sa=!1,Gd=cm(lm.PromiseRejectionEvent),gm=hm("Promise",function(){var i=fm($i),e=i!==String($i);if(!e&&$r===66||!(no.catch&&no.finally))return!0;if(!$r||$r<51||!/native code/.test(i)){var t=new $i(function(a){a(1)}),s=function(a){a(function(){},function(){})},r=t.constructor={};if(r[Sm]=s,sa=t.then(function(){})instanceof s,!sa)return!0}return!e&&(vm||mm)&&!Gd}),Mi={CONSTRUCTOR:gm,REJECTION_EVENT:Gd,SUBCLASSING:sa},ni={},oo=Bt,bm=TypeError,ym=function(i){var e,t;this.promise=new i(function(s,r){if(e!==void 0||t!==void 0)throw bm("Bad Promise constructor");e=s,t=r}),this.resolve=oo(e),this.reject=oo(t)};ni.f=function(i){return new ym(i)};var Tm=We,$s=Ms,Tt=we,Ui=Le,Em=Aa,$m=wa,Am=lv,_m=Bt,ra=Te,wm=ct,km=fv,Pm=Nd,Yd=Ud.set,Ca=rm,Rm=am,Im=Da,Dm=Vd,qd=od,aa=ai,Oa=Mi,jd=ni,Us="Promise",zd=Oa.CONSTRUCTOR,Cm=Oa.REJECTION_EVENT;Oa.SUBCLASSING;var Ar=qd.getterFor(Us),Om=qd.set,Lm=aa&&aa.prototype,Qt=aa,_r=Lm,Wd=Tt.TypeError,na=Tt.document,La=Tt.process,oa=jd.f,xm=oa,Nm=!!(na&&na.createEvent&&Tt.dispatchEvent),Qd="unhandledrejection",Bm="rejectionhandled",uo=0,Jd=1,Mm=2,xa=1,Kd=2,rs,lo,Um,Xd=function(i){var e;return wm(i)&&ra(e=i.then)?e:!1},Zd=function(i,e){var t=e.value,s=e.state==Jd,r=s?i.ok:i.fail,a=i.resolve,n=i.reject,o=i.domain,u,d,l;try{r?(s||(e.rejection===Kd&&Vm(e),e.rejection=xa),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),l=!0)),u===i.promise?n(Wd("Promise-chain cycle")):(d=Xd(u))?Ui(d,u,a,n):a(u)):n(t)}catch(c){o&&!l&&o.exit(),n(c)}},eu=function(i,e){i.notified||(i.notified=!0,Ca(function(){for(var t=i.reactions,s;s=t.get();)Zd(s,i);i.notified=!1,e&&!i.rejection&&Fm(i)}))},tu=function(i,e,t){var s,r;Nm?(s=na.createEvent("Event"),s.promise=e,s.reason=t,s.initEvent(i,!1,!0),Tt.dispatchEvent(s)):s={promise:e,reason:t},!Cm&&(r=Tt["on"+i])?r(s):i===Qd&&Rm("Unhandled promise rejection",t)},Fm=function(i){Ui(Yd,Tt,function(){var e=i.facade,t=i.value,s=co(i),r;if(s&&(r=Im(function(){$s?La.emit("unhandledRejection",t,e):tu(Qd,e,t)}),i.rejection=$s||co(i)?Kd:xa,r.error))throw r.value})},co=function(i){return i.rejection!==xa&&!i.parent},Vm=function(i){Ui(Yd,Tt,function(){var e=i.facade;$s?La.emit("rejectionHandled",e):tu(Bm,e,i.value)})},Jt=function(i,e,t){return function(s){i(e,s,t)}},Xt=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=Mm,eu(i,!0))},da=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw Wd("Promise can't be resolved itself");var s=Xd(e);s?Ca(function(){var r={done:!1};try{Ui(s,e,Jt(da,r,i),Jt(Xt,r,i))}catch(a){Xt(r,a,i)}}):(i.value=e,i.state=Jd,eu(i,!1))}catch(r){Xt({done:!1},r,i)}}};zd&&(Qt=function(e){km(this,_r),_m(e),Ui(rs,this);var t=Ar(this);try{e(Jt(da,t),Jt(Xt,t))}catch(s){Xt(t,s)}},_r=Qt.prototype,rs=function(e){Om(this,{type:Us,done:!1,notified:!1,parent:!1,reactions:new Dm,rejection:!1,state:uo,value:void 0})},rs.prototype=Em(_r,"then",function(e,t){var s=Ar(this),r=oa(Pm(this,Qt));return s.parent=!0,r.ok=ra(e)?e:!0,r.fail=ra(t)&&t,r.domain=$s?La.domain:void 0,s.state==uo?s.reactions.add(r):Ca(function(){Zd(r,s)}),r.promise}),lo=function(){var i=new rs,e=Ar(i);this.promise=i,this.resolve=Jt(da,e),this.reject=Jt(Xt,e)},jd.f=oa=function(i){return i===Qt||i===Um?new lo(i):xm(i)});Tm({global:!0,constructor:!0,wrap:!0,forced:zd},{Promise:Qt});$m(Qt,Us,!1,!0);Am(Us);var Hm=ke,iu=Hm("iterator"),su=!1;try{var Gm=0,ho={next:function(){return{done:!!Gm++}},return:function(){su=!0}};ho[iu]=function(){return this},Array.from(ho,function(){throw 2})}catch(i){}var Ym=function(i,e){if(!e&&!su)return!1;var t=!1;try{var s={};s[iu]=function(){return{next:function(){return{done:t=!0}}}},i(s)}catch(r){}return t},qm=ai,jm=Ym,zm=Mi.CONSTRUCTOR,ru=zm||!jm(function(i){qm.all(i).then(void 0,function(){})}),Wm=We,Qm=Le,Jm=Bt,Km=ni,Xm=Da,Zm=Pa,eS=ru;Wm({target:"Promise",stat:!0,forced:eS},{all:function(e){var t=this,s=Km.f(t),r=s.resolve,a=s.reject,n=Xm(function(){var o=Jm(t.resolve),u=[],d=0,l=1;Zm(e,function(c){var h=d++,f=!1;l++,Qm(o,t,c).then(function(m){f||(f=!0,u[h]=m,--l||r(u))},a)}),--l||r(u)});return n.error&&a(n.value),s.promise}});var tS=We,iS=Mi.CONSTRUCTOR,fo=ai;fo&&fo.prototype;tS({target:"Promise",proto:!0,forced:iS,real:!0},{catch:function(i){return this.then(void 0,i)}});var sS=We,rS=Le,aS=Bt,nS=ni,oS=Da,dS=Pa,uS=ru;sS({target:"Promise",stat:!0,forced:uS},{race:function(e){var t=this,s=nS.f(t),r=s.reject,a=oS(function(){var n=aS(t.resolve);dS(e,function(o){rS(n,t,o).then(s.resolve,r)})});return a.error&&r(a.value),s.promise}});var lS=We,cS=Le,hS=ni,fS=Mi.CONSTRUCTOR;lS({target:"Promise",stat:!0,forced:fS},{reject:function(e){var t=hS.f(this);return cS(t.reject,void 0,e),t.promise}});var pS=ft,vS=ct,mS=ni,au=function(i,e){if(pS(i),vS(e)&&e.constructor===i)return e;var t=mS.f(i),s=t.resolve;return s(e),t.promise},SS=We,gS=Nt,bS=rd,yS=ai,TS=Mi.CONSTRUCTOR,ES=au,$S=gS("Promise"),AS=!TS;SS({target:"Promise",stat:!0,forced:bS},{resolve:function(e){return ES(AS&&this===$S?yS:this,e)}});var _S=We,ua=ai,wS=He,kS=Nt,PS=Te,RS=Nd,po=au,IS=ua&&ua.prototype,DS=!!ua&&wS(function(){IS.finally.call({then:function(){}},function(){})});_S({target:"Promise",proto:!0,real:!0,forced:DS},{finally:function(i){var e=RS(this,kS("Promise")),t=PS(i);return this.then(t?function(s){return po(e,i()).then(function(){return s})}:i,t?function(s){return po(e,i()).then(function(){throw s})}:i)}});var CS=Nt,Na=CS,OS=Na,LS=OS("Promise","finally"),xS=LS,NS=xS,BS=NS,MS=BS,Fs=MS,Zt;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(Zt||(Zt={}));var ei=(i,e=0,t=Zt.OFFSET_P)=>{switch(t){case Zt.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Zt.PLAYBACK_SHIFT:{if(e===0)return i;const s=new URL(i);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}default:x(t)}return i},R=(i,e,t=!1)=>{const s=i.getTransition();(t||!s||s.to===e)&&i.setState(e)},ne;(function(i){i.INVARIANT="Invariant quality",i.Q_144P="144p",i.Q_240P="240p",i.Q_360P="360p",i.Q_480P="480p",i.Q_720P="720p",i.Q_1080P="1080p",i.Q_1440P="1440p",i.Q_2160P="2160p",i.Q_4320P="4320p"})(ne||(ne={}));const ze={[ne.Q_144P]:{width:256,height:144},[ne.Q_240P]:{width:428,height:240},[ne.Q_360P]:{width:640,height:360},[ne.Q_480P]:{width:856,height:480},[ne.Q_720P]:{width:1280,height:720},[ne.Q_1080P]:{width:1920,height:1080},[ne.Q_1440P]:{width:2560,height:1440},[ne.Q_2160P]:{width:3840,height:2160},[ne.Q_4320P]:{width:7680,height:4320}},Ss=(i,e)=>ze[i].height>ze[e].height,US=(i,e)=>ze[i].height>=ze[e].height,Ai=(i,e)=>ze[i].height<ze[e].height,FS=(i,e)=>ze[i].height<=ze[e].height,VS=i=>i.sort((e,t)=>e===t?0:e===ne.INVARIANT?1:t===ne.INVARIANT?-1:Ai(e,t)?1:-1)[0],HS=Object.keys(ze).sort((i,e)=>Ai(i,e)?-1:1),Mt=({width:i,height:e})=>{const t=Math.min(i,e),s=Math.max(i,e);return HS.find(r=>{const a=ze[r];return a.width>=s&&a.height>=t})},GS=i=>ze[i].height,As=i=>i===ne.INVARIANT;class le{constructor(e){this.transitionStarted$=new O,this.transitionEnded$=new O,this.transitionUpdated$=new O,this.forceChanged$=new O,this.stateChangeStarted$=L(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=L(this.transitionEnded$,this.forceChanged$),this.state=e}setState(e){const t=this.transition,s=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:s,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,s=this.state;s===e||w(t)&&t.to===e||(this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}const YS=i=>{switch(i){case b.MPEG:case b.DASH:case b.DASH_SEP:case b.DASH_ONDEMAND:case b.DASH_WEBM:case b.HLS:case b.HLS_ONDEMAND:return!1;case b.DASH_LIVE:case b.DASH_LIVE_CMAF:case b.HLS_LIVE:case b.HLS_LIVE_CMAF:case b.DASH_LIVE_WEBM:case b.WEB_RTC_LIVE:return!0;default:return x(i)}};var q;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(q||(q={}));const qS=5,jS=5,zS=500,vo=7e3;class WS{constructor(e){this.subscription=new se,this.loadMediaTimeoutSubscription=new se,this.videoState=new le(q.STOPPED),this.syncPlayback=()=>{const s=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: ${s}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${a}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(o)};`}),a===v.STOPPED){s!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==v.PAUSED&&o.state===H.Requested&&s!==q.STOPPED){this.seek(o.position/1e3);return}switch(a){case v.READY:{switch(s){case q.PLAYING:case q.PAUSED:case q.READY:break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:x(s)}break}case v.PLAYING:{switch(s){case q.PLAYING:break;case q.PAUSED:this.videoState.startTransitionTo(q.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case q.READY:this.videoState.startTransitionTo(q.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:x(s)}break}case v.PAUSED:{switch(s){case q.PLAYING:this.videoState.startTransitionTo(q.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case q.PAUSED:break;case q.READY:this.videoState.startTransitionTo(q.PAUSED),this.videoState.setState(q.PAUSED);break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:x(s)}break}default:x(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(YS(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 se;this.subscription.add(e),this.subscription.add(L(this.videoState.stateChangeStarted$.pipe($(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe($(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));const t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const r=new O;e.add(r.pipe(Ve(zS)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===H.Applying||Math.abs(o-a)>qS)&&r.next(o),a=o})),e.add(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<jS&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),R(this.params.desiredState.playbackState,v.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:x(n)}}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const s=L(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ve(0));t(s,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(q.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED)):(this.videoState.setState(q.PLAYING),R(this.params.desiredState.playbackState,v.PLAYING));const s=this.params.output.isLive$.getValue();this.params.output.duration$.next(s?0:t.duration),this.params.output.position$.next(s?0:t.currentTime),this.params.desiredState.seekState.setState({state:H.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),s=this.createLoadRequest(t);this.loadMedia(s)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===q.PAUSED||e===q.PLAYING)&&(this.videoState.setState(q.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===q.PLAYING||e===q.PAUSED)&&(this.videoState.setState(q.PLAYING),R(this.params.desiredState.playbackState,v.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===q.READY&&this.videoState.setState(q.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===v.READY&&R(this.params.desiredState.playbackState,v.READY)}handleRemoteStop(){this.videoState.getState()!==q.STOPPED&&this.videoState.setState(q.STOPPED)}handleRemoteVolumeChange(e){var t,s;const r=this.params.output.volume$.getValue(),a={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(s=e.muted)!==null&&s!==void 0?s: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:s}=this.params.connection;t.currentTime=e,s.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const s=this.params.source;let r,a,n;switch(e){case b.MPEG:{const l=s[e];P(l);const c=VS(Object.keys(l));P(c);const h=l[c];P(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case b.HLS:case b.HLS_ONDEMAND:{const l=s[e];P(l),r=l.url,a="application/x-mpegurl",n=chrome.cast.media.StreamType.BUFFERED;break}case b.DASH_SEP:case b.DASH_ONDEMAND:case b.DASH_WEBM:{const l=s[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case b.DASH_LIVE_CMAF:{const l=s[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case b.HLS_LIVE:case b.HLS_LIVE_CMAF:{const l=s[e];P(l),r=ei(l.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case b.DASH:case b.DASH_LIVE:case b.WEB_RTC_LIVE:{const l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:C.VIDEO_PIPELINE,message:l,thrown:c}),c}case b.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return x(e)}const o=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,a);o.contentUrl=r,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return w(u)&&(o.metadata.title=u),w(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const s=this.params.desiredState.seekState.getState();return s.state===H.Applying||s.state===H.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:s.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),s=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(Yu(vo).subscribe(()=>a(`timeout(${vo})`)))});Fs(Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===H.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{const a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:C.VIDEO_PIPELINE,message:a,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}class mo{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}removeEventListener(e,t){if(!(e in this.listeners))return;const s=this.listeners[e];for(let r=0,a=s.length;r<a;r++)if(s[r].callback===t){s.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let r=0,a=s.length;r<a;r++){const n=s[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 nu extends mo{constructor(){super(),this.listeners||mo.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 ou=class{constructor(){Object.defineProperty(this,"signal",{value:new nu,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 s=e;if(s===void 0)if(typeof document=="undefined")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch(r){s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(ou.prototype[Symbol.toStringTag]="AbortController",nu.prototype[Symbol.toStringTag]="AbortSignal");function du(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function QS(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!du({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(d,l){let c;l&&l.signal&&(c=l.signal,delete l.signal);const h=new t(d,l);return c&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),h},a.prototype=t.prototype);const n=e;return{fetch:(u,d)=>{const l=a&&a.prototype.isPrototypeOf(u)?u.signal:d?d.signal:void 0;if(l){let c;try{c=new DOMException("Aborted","AbortError")}catch(f){c=new Error("Aborted"),c.name="AbortError"}if(l.aborted)return Promise.reject(c);const h=new Promise((f,m)=>{l.addEventListener("abort",()=>m(c),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([h,n(u,d)])}return n(u,d)},Request:a}}const Vs=du({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),uu=Vs?QS({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ti=Vs?uu.fetch:window.fetch;Vs?uu.Request:window.Request;const Dt=Vs?ou:window.AbortController,bi=i=>i.range?i.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class _i{constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){var t;const{url:s}=e.request,r=(t=this.dashJsRequestQueue.get(s))!==null&&t!==void 0?t:[];r.push(e),this.dashJsRequestQueue.set(s,r)}executeNextRequests(){return ue(this,void 0,void 0,function*(){for(const[e,t]of this.dashJsRequestQueue.entries()){const s=this.activeRequests.get(e);if(s){t.length&&this.onBigRequestProgress(s);const r=t[0];if(!r||!r.request.range)continue;const[a,n]=bi(r.request);if(a>=s.from&&n<=s.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:s}=e,r=((t=this.dashJsRequestQueue.get(s.url))!==null&&t!==void 0?t:[]).includes(e),a=this.activeRequests.get(s.url);r&&a&&a.abortController.abort()}else for(const{abortController:s}of this.activeRequests.values())s.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const s=t.map(bi),r=s[0][0];let a=s[0][1];for(let h=1;h<s.length&&a<this.params.minDataSize;h++){const f=s[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 Dt,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,m;throw(m=(f=this.params).onError)===null||m===void 0||m.call(f,{id:"BigRequestParsing",category:C.PARSER,message:"Error parsing response data",thrown:h}),h};return ti(o,{signal:d}).then(h=>{var f,m,p;if(l.response=h,!h.ok||!h.body){this.onBigRequestError(l);return}const[S,g]=h.body.tee();(m=(f=this.params).onDownloadStream)===null||m===void 0||m.call(f,g);const T=S.getReader(),I=parseInt((p=h.headers.get("Content-Length"))!==null&&p!==void 0?p:"",10)||a-r+1;l.data=new ArrayBuffer(I);const _=new Uint8Array(l.data),A=({done:N,value:X})=>ue(this,void 0,void 0,function*(){N?this.onBigRequestProgress(l):X&&(_.set(X,l.loaded),l.loaded+=X.byteLength,this.onBigRequestProgress(l),yield T==null?void 0:T.read().then(A,_i.suppressStreamErrors).catch(c))});T==null||T.read().then(A,_i.suppressStreamErrors).catch(c)},_i.suppressAbort).catch(h=>this.onBigRequestError(l,h)),l}onBigRequestProgress({url:e,from:t,to:s,loaded:r,data:a,response:n}){var o,u,d,l,c,h,f,m;if(!this.activeRequests.has(e)||!a)return;const p=(o=this.dashJsRequestQueue.get(e))!==null&&o!==void 0?o:[];for(const S of p){const{request:g}=S,[T,I]=bi(g),_=T>=t&&I<=t+r,A=t>=T&&t+r<I,N=a.slice(T-t,Math.min(I-t+1,r));if((_||A)&&(g.requestStartDate=(u=g.requestStartDate)!==null&&u!==void 0?u:new Date,g.firstByteDate=(d=g.firstByteDate)!==null&&d!==void 0?d:new Date,g.bytesLoaded=N.byteLength,g.bytesTotal=s-t),_){g.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[]).filter(Y=>Y!==S)),(c=S.success)===null||c===void 0||c.call(S,N,"",e);const X=n?Array.from(n.headers.entries()).map(([Y,F])=>`${Y}: ${F}`).join(`\r
7
- `):"";(h=this.dashMetrics)===null||h===void 0||h.addHttpRequest(g,e,(f=n==null?void 0:n.status)!==null&&f!==void 0?f:200,X,[])}else A&&((m=S.progress)===null||m===void 0||m.call(S,{loaded:r,total:s-t,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:t,to:s},r){var a,n,o,u;if((n=(a=this.params).onError)===null||n===void 0||n.call(a,{id:"BigRequest",category:C.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]=bi(l.request);(c>=t&&c<s||h>t&&h<=s)&&((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:s}){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]=bi(o.request);(u>=t&&u<s||d>t&&d<=s)&&((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 _s{constructor(e,t,s){this.baseLoader=e,this.config=s,this.bigRequest=t,t.setMetrics(s.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(_s.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;_s.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const JS=(i,e)=>t=>({create:s=>{const r=i(t).create(s);return new _s(r,e,s)}}),KS=(i,e)=>{const t=new _i(e);return i.extend("SchemeLoaderFactory",function(){const{parent:s}=this,r=s.getLoader;return{getLoader:a=>{const n=r(a);return JS(n,t)}}},!0),()=>t.destroy()};var XS=i=>{let e,t=!1,s=!1;i.on("playbackTimeUpdated",({timeToEnd:r})=>{s=r<=3,t&&s&&(e==null||e())}),i.extend("MediaSourceController",function(){const{parent:r}=this,a=r.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>a(n),t&&s&&(e==null||e())}}},!0)},ZS=i=>{const e=new y(1/0),t=new O,s=new y(void 0),r=new y(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},u=l=>{var c,h,f,m,p;const S=Bi(l.getAllResponseHeaders().trim().split(/[\n\r]+/).map(I=>I.split(": ")));if("x-playback-duration"in S||"x-playback-duration-millis"in S){const I=parseInt((c=l.getResponseHeader("X-Playback-Duration"))!==null&&c!==void 0?c:"",10),_=parseInt((h=l.getResponseHeader("X-Playback-Duration-Millis"))!==null&&h!==void 0?h:"",10),A=(f=_!=null?_:I*1e3)!==null&&f!==void 0?f:NaN;w(A)&&!isNaN(A)&&e.next(A)}const g=(m=S["x-delivery-type"])!==null&&m!==void 0?m:ki.HTTP1,T=(p={1:!0,0:!1}[S["x-reused"]])!==null&&p!==void 0?p:void 0;s.next(g),r.next(T)},d=l=>{l.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return i.extend("XHRLoader",function(){const{parent:l}=this,c=l.load.bind(l);return{load:function(h){if(h.request.type==="MPD"){const f=h.onload,m=h.progress;h.onload=function(...p){return u(this),f(...p)},h.progress=function(...p){return d(this),m(...p)},o()}return c(h)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:s}},ii=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},eg=i=>i.extend("RequestModifier",()=>({modifyRequestURL:ii}),!0),tg=i=>{i.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:s=>{if(s.request&&s.request.range){const[r,a]=s.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(s.request.url,location.href);n.searchParams.append("bytes",`${r}-${a}`),s.request.url=n.toString(),s.request.range=void 0}t(s)}}},!0)};const et=(i,e,t,{equal:s=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=i.getState(),o=e(),u=K(r),d=new se;return r&&d.add(r.subscribe(l=>{const c=i.getState();s(l,c)&&i.setState(l)},a)),s(o,n)||(t(n),u&&i.setState(n)),d.add(i.stateChangeStarted$.subscribe(l=>{t(l.to),u&&i.setState(l.to)},a)),d},Ut=(i,e,t)=>et(e,()=>i.loop,s=>{w(s)&&(i.loop=s)},{onError:t}),pt=(i,e,t,s)=>et(e,()=>({muted:i.muted,volume:i.volume}),r=>{w(r)&&(i.muted=r.muted,i.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:s}),Et=(i,e,t,s)=>et(e,()=>i.playbackRate,r=>{w(r)&&(i.playbackRate=r)},{changed$:t,onError:s}),ig=i=>["__",i.language,i.label].join("|"),sg=(i,e)=>{if(i.id===e)return!0;const[t,s,r]=e.split("|");return i.language===s&&i.label===r};class it{constructor(){this.available$=new O,this.current$=new y(void 0),this.error$=new O,this.subscription=new se,this.externalTracks=new Map}connect(e,t,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:C.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(et(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{w(a)&&this.setExternal(a)},{equal:(a,n)=>w(a)&&w(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe($(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(et(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(et(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){P(this.video);const{textTracks:e}=this.video;this.subscription.add(U(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();this.select(s)})),this.subscription.add(L(U(e,"addtrack"),U(e,"removetrack"),Oe(["init"])).pipe($(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),me((s,r)=>s.length===r.length&&s.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(L(U(e,"change"),Oe(["init"])).pipe($(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),$(s=>s&&this.htmlTextTrackToITextTrack(s).id),me()).subscribe(this.current$));const t=s=>{var r,a;return this.applyCueSettings((a=(r=s.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(U(e,"addtrack").subscribe(s=>{var r,a;(r=s.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=s.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(U(e,"removetrack").subscribe(s=>{var r;(r=s.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const s of Array.from(e)){const r=s;w(t.align)&&(r.align=t.align),w(t.position)&&(r.position=t.position),w(t.size)&&(r.size=t.size),w(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){P(this.video);const t=[...this.video.textTracks];return e?t:t.filter(it.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:s}=e,r=e.id!==""?e.id:ig(e);return this.externalTracks.has(r)?{id:r,type:"external",language:t,label:s,url:this.externalTracks.get(r).url}:{id:r,type:"internal",language:t,label:s}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.id===""&&e.label===""&&e.language==="")}setExternal(e){e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks.keys()).filter(t=>!e.find(s=>s.id===t)).forEach(t=>this.detach(t))}select(e){P(this.video);for(const t of this.htmlTextTracksAsArray(!0))w(e)&&sg(t,e)?t.mode="showing":t.mode="disabled"}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){P(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),this.externalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){P(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),s=>s.getAttribute("id")===e);t&&this.video.removeChild(t),this.externalTracks.delete(e)}}var vt=i=>{const e=document.createElement("video");return e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i.appendChild(e),e};class Ba{constructor(){this.pausedTime=0,this.streamOffset=0,this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0}}var lu=()=>{const{userAgent:i}=window.navigator;return!/chrome/i.test(i)&&/webkit|safari|khtml/i.test(i)};const la=3;class rg{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,s=this._source.buffered.length;t<s;t++){let r=this._source.buffered.start(t);const a=this._source.buffered.end(t);r>e&&r-e<la&&(r=e),this._buffer.push({from:r,to:a,i:t})}return this._buffer.sort(function(t,s){return t.from-s.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const s=this.getNext(e);if(s&&s.from-e.to<(t||la))return s}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,s){this._buffer.forEach(({from:r,to:a})=>{const n=r>=e&&r<t,o=a>=e&&a<t;n&&o||(n?s(t,a):o?s(r,e):r<e&&a>t?(s(t,a),s(r,e)):s(r,a))})}destroy(){this._buffer=[]}}var cu=(i,e,t=la)=>{let s=0,r=0;for(let a=0;a<i.length;a++){const n=i.start(a),o=i.end(a);if(n<=e&&e<=o){if(s=n,r=o,!t)return{from:s,to:r};for(let u=a-1;u>=0;u--)i.end(u)+t>=s&&(s=i.start(u));for(let u=a+1;u<i.length;u++)i.start(u)-t<=r&&(r=i.end(u))}}return{from:s,to:r}};const ag=50,ng=i=>i.webkitAudioDecodedByteCount!==void 0?!!i.webkitAudioDecodedByteCount:i.mozHasAudio!==void 0?i.mozHasAudio:i.audioTracks?!!i.audioTracks.length:!0,mt=i=>{const e=m=>U(i,m).pipe(Ot(void 0)),s=L(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(m=>U(i,m))).pipe($(m=>m.type==="ended"?i.readyState<2:i.readyState<3),me()),r=L(U(i,"progress"),U(i,"timeupdate")).pipe($(()=>cu(i.buffered,i.currentTime))),a=lu()?dt({play:e("play").pipe(ye()),playing:e("playing")}).pipe(Ot(void 0)):e("playing"),n=U(i,"playing").pipe(Ve(ag),$(()=>ng(i))),o=U(i,"volumechange").pipe($(()=>({muted:i.muted,volume:i.volume}))),u=U(i,"ratechange").pipe($(()=>i.playbackRate)),d=U(i,"error").pipe(j(()=>Boolean(i.error||i.played.length)),$(()=>{var m;const p=i.error;return{id:p?`MediaError#${p.code}`:"HtmlVideoError",category:C.VIDEO_PIPELINE,message:p?p.message:"Error event from HTML video element",thrown:(m=i.error)!==null&&m!==void 0?m:void 0}})),l=U(i,"timeupdate").pipe($(()=>i.currentTime)),c=new O,h=.3;let f;return l.subscribe(m=>{i.loop&&w(f)&&w(m)&&f>=i.duration-h&&m<=h&&c.next(f),f=m}),{playing$:a,pause$:e("pause").pipe(j(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:U(i,"durationchange").pipe($(()=>i.duration)),isBuffering$:s,currentBuffer$:r,volumeState$:o,isAudioAvailable$:n,playbackRateState$:u}},Ma=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var og=We,dg=xs,ug=$a,lg=Ea;og({target:"Array",proto:!0},{at:function(e){var t=dg(this),s=ug(t),r=lg(e),a=r>=0?r:s+r;return a<0||a>=s?void 0:t[a]}});var cg=Na,hg=cg("Array","at"),fg=hg,pg=fg,vg=pg,mg=vg,at=mg;let Ua=!1,nt={};const Sg=i=>{Ua=i},gg=()=>{nt={}},bg=i=>{i(nt)},as=(i,e)=>{var t;Ua&&(nt.meta=(t=nt.meta)!==null&&t!==void 0?t:{},nt.meta[i]=e)};class Ze{constructor(e){this.name=e}next(e){var t,s;if(!Ua)return;nt.series=(t=nt.series)!==null&&t!==void 0?t:{};const r=(s=nt.series[this.name])!==null&&s!==void 0?s:[];r.push([Date.now(),e]),nt.series[this.name]=r}}const yg=new Ze("best_bitrate"),Tg=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class Eg{constructor(){this.history={}}recordSelection(e){this.history[e.id]=pe()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Fi=(i,{container:e,throughput:t,tuning:s,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:d})=>{var l,c,h,f;const m=s.usePixelRatio&&(l=window.devicePixelRatio)!==null&&l!==void 0?l:1,p=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*m*s.containerSizeFactor,height:e.height*m*s.containerSizeFactor},S=p&&Mt(p),g=s.considerPlaybackRate&&w(o)?o:1,T=i.filter(V=>!As(V.quality)).sort((V,B)=>Ss(V.quality,B.quality)?-1:1),I=(c=at(T,-1))===null||c===void 0?void 0:c.quality,_=(h=at(T,0))===null||h===void 0?void 0:h.quality,A=K(r)||w(r.min)&&w(r.max)&&Ai(r.max,r.min)||w(r.min)&&_&&Ss(r.min,_)||w(r.max)&&I&&Ai(r.max,I),N=g*Tg(n!=null?n:.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),Y=T.filter(V=>{const B=S?Ai(V.quality,S):!0,ie=w(t)&&isFinite(t)&&w(V.bitrate)?t-a>=V.bitrate*N:!0,ce=s.lazyQualitySwitch&&w(s.minBufferToSwitchUp)&&u&&!As(u.quality)&&(n!=null?n:0)<s.minBufferToSwitchUp&&Ss(V.quality,u.quality),Se=A||(K(r.max)||FS(V.quality,r.max))&&(K(r.min)||US(V.quality,r.min));return B&&ie&&!ce&&Se})[0];Y&&Y.bitrate&&yg.next(Y.bitrate);const F=(f=Y!=null?Y:T[Math.ceil((T.length-1)/2)])!==null&&f!==void 0?f:i[0],Z=F&&d&&d.history[F.id]&&pe()-d.history[F.id]<=s.trackCooldown&&(!d.last||F.id!==d.last.id);if(F!=null&&F.id&&d&&!Z&&d.recordSelection(F),Z&&(d!=null&&d.last)){const V=d.last;return d==null||d.recordSwitch(V),V}return d==null||d.recordSwitch(F),F};var Re=i=>new URL(i).hostname;const $g=300,ws=(i,e=$g)=>new Ii(t=>{const{width:s,height:r}=i.getBoundingClientRect();if(t.next({width:s,height:r}),!window.ResizeObserver)return;const a=new ResizeObserver(zu(n=>{const o=n[0];if(!o)return;let u,d;o.contentBoxSize&&o.contentBoxSize[0]?(d=o.contentBoxSize[0].blockSize,u=o.contentBoxSize[0].inlineSize):o.contentRect&&(u=o.contentRect.width,d=o.contentRect.height),w(u)&&w(d)&&t.next({width:u,height:d})},e));return a.observe(i),()=>a.disconnect()}),St=i=>{try{i.pause(),i.playbackRate=0,i.removeAttribute("src"),i.load(),i.remove()}catch(e){console.error(e)}},Ag=5e3,yi={};var z;(function(i){i.DOWNLOADING_LIB="downloading_lib",i.STOPPED="stopped",i.STREAM_INITIALIZED="stream_initialized",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(z||(z={}));const be=(i,e)=>new Ii(t=>{const s=r=>t.next(r);return i.on(e,s),()=>i.off(e,s)});class So{constructor(e){this.subscription=new se,this.videoState=new le(z.DOWNLOADING_LIB),this.textTracksManager=new it,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new y(void 0),this.maxSeekBackTime$=new y(1/0),this.availableFrom$=new y(void 0),this.elementSize$=new y(void 0),this.liveOffset=new Ba,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState(),n=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===z.DOWNLOADING_LIB||t===z.STREAM_INITIALIZED))switch((r==null?void 0:r.to)!==v.PAUSED&&a.state===H.Requested&&t!==z.STOPPED&&s!==v.STOPPED&&(n?this.seek(a.position-this.liveOffset.getTotalPausedTime()):this.seek(a.position)),s){case v.STOPPED:{switch(t){case z.STOPPED:break;case z.PLAYING:case z.PAUSED:case z.READY:this.stop();break;default:x(t)}break}case v.READY:{switch(t){case z.STOPPED:this.prepare();break;case z.PLAYING:case z.PAUSED:case z.READY:break;default:x(t)}break}case v.PLAYING:{switch(t){case z.PLAYING:break;case z.PAUSED:n&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case z.READY:this.play();break;case z.STOPPED:this.prepare();break;default:x(t)}break}case v.PAUSED:{switch(t){case z.PLAYING:this.pause(),this.liveOffset.pause();break;case z.PAUSED:break;case z.READY:this.videoState.setState(z.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED);break;case z.STOPPED:this.prepare();break;default:x(t)}break}default:x(s)}},this.video=vt(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(Re(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=r=>{var a;e||this.params.output.error$.next({id:r==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:C.NETWORK,message:`Dash.js failed to load: ${(a=r==null?void 0:r.toString)===null||a===void 0?void 0:a.call(r)}`,thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),Ag);Fs(import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(yi.MediaPlayer=r.MediaPlayer,yi.Debug=r.Debug,this.init())},t),()=>{window.clearTimeout(s),e=!0})}init(){P(yi.MediaPlayer,"dashjs not loaded"),P(yi.Debug,"dashjs not loaded"),this.player=yi.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?Ma(t.frameRate+""):void 0),!0)),(this.params.format===b.DASH_WEBM||this.params.format===b.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=KS(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&&tg(this.player),XS(this.player),this.params.tuning.requestQuick&&eg(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(z.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,s=p=>{e.error$.next({id:"DashIFProvider",category:C.WTF,message:"DashIFProvider internal logic error",thrown:p})},r=(p,S)=>this.subscription.add(p.subscribe(S,s));r(ws(this.video),this.elementSize$),r(be(this.player,"error").pipe($(p=>{const S=typeof p.error=="object"?p.error.code:p.error,g=typeof p.error=="object"?p.error.message:void 0;return{id:`DashJS#${S}`,message:g}})),e.error$),r(be(this.player,"playbackError").pipe($(p=>({id:"DashJSPlayback",message:p.error}))),e.error$);const a=be(this.player,"qualityChangeRendered").pipe(j(({mediaType:p})=>p==="video"),$(({newQuality:p})=>{var S;return(S=this.videoTracks.find(({bitrateInfo:g})=>g.qualityIndex===p))===null||S===void 0?void 0:S.track}));a.pipe(j(w)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(j(({to:p})=>p===z.STREAM_INITIALIZED),ye()).subscribe(()=>{this.subscription.add(et(t.videoTrack,()=>{var p,S;const g=this.player.getQualityFor("video");return(S=(p=this.videoTracks.find(({bitrateInfo:T})=>T.qualityIndex===g))===null||p===void 0?void 0:p.track)===null||S===void 0?void 0:S.id},p=>{var S;if(K(p))return;const g=(S=this.videoTracks.find(({track:T})=>T.id===p))===null||S===void 0?void 0:S.bitrateInfo;g&&this.player.setQualityFor("video",g.qualityIndex)},{changed$:a.pipe($(p=>p==null?void 0:p.id)),onError:s}))},s)),this.subscription.add(et(t.autoVideoTrackSwitching,()=>{var p,S,g;return(g=(S=(p=this.player.getSettings().streaming)===null||p===void 0?void 0:p.abr)===null||S===void 0?void 0:S.autoSwitchBitrate)===null||g===void 0?void 0:g.video},p=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:p}}}}),{onError:s})),r(be(this.player,"bufferStateChanged").pipe(j(({mediaType:p})=>p==="video"),$(({state:p})=>p==="bufferStalled")),e.isBuffering$),r(be(this.player,"fragmentLoadingStarted"),({mediaType:p,request:{url:S}})=>{var g,T;const I=this.player.getDashMetrics(),_=I.getLatestFragmentRequestHeaderValueByID(p,"X-Reused"),A=(g=I.getLatestFragmentRequestHeaderValueByID(p,"X-Delivery-Type"))!==null&&g!==void 0?g:ki.HTTP1,N=(T={1:!0,0:!1}[_])!==null&&T!==void 0?T:void 0;this.params.output.httpConnectionType$.next(A),this.params.output.httpConnectionReused$.next(N),e.hostname$.next(Re(S))}),r(be(this.player,"streamInitialized"),({streamInfo:{duration:p,manifestInfo:{isDynamic:S,availableFrom:g}}})=>{this.isLive$.next(S),this.availableFrom$.next(g.getTime()),S||e.duration$.next(p),this.videoTracks=[];const T=this.player.getQualityFor("video");let I;for(const _ of this.player.getBitrateInfoListFor("video")){const A=_.qualityIndex.toString(10),N=Mt(_),X=_.bitrate/1e3,Y={width:_.width,height:_.height},F=this.frameRatesByFrameHeight[_.height];if(N){const Z={id:A,quality:N,bitrate:X,size:Y,fps:F};this.videoTracks.push({track:Z,bitrateInfo:_}),_.qualityIndex===T&&(I=Z)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:_})=>_)),I&&e.currentVideoTrack$.next(I),this.videoState.setState(z.STREAM_INITIALIZED),this.videoState.startTransitionTo(z.READY)}),r(be(this.player,"fragmentLoadingCompleted"),({request:p})=>{if(!p.requestEndDate||!p.firstByteDate||!p.bytesLoaded)return;const S=p.requestEndDate.getTime()-p.firstByteDate.getTime(),g=p.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(g,S)}),r(L(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const p=this.params.dependencies.throughputEstimator.throughput$.getValue(),S=Fi(this.videoTracks.map(({track:T})=>T),{container:this.elementSize$.getValue(),throughput:p,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),g=this.videoTracks.find(({track:T})=>T===S);g!=null&&g.bitrateInfo&&this.player.setQualityFor("video",g==null?void 0:g.bitrateInfo.qualityIndex,!1)}),r(dt({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(j(w))}).pipe(j(({isLive:p})=>p),$(({maxSeekBackTime:p})=>-p/1e3)),this.params.output.duration$);const n=be(this.player,"playbackTimeUpdated").pipe($(({time:p})=>p!=null?p:0));r(dt({availableFrom:this.availableFrom$.pipe(j(w)),currentTime:n}),({availableFrom:p,currentTime:S})=>this.params.output.liveTime$.next(p+S*1e3)),r(n.pipe(j(()=>this.isLive$.getValue()===!1)),e.position$),r(be(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),r(be(this.player,"playbackEnded"),e.endedEvent$),r(be(this.player,"playbackProgress").pipe($(()=>cu(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(be(this.player,"playbackPlaying"),()=>{this.videoState.setState(z.PLAYING),R(t.playbackState,v.PLAYING)}),r(be(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(z.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(be(this.player,"playbackPaused"),()=>{this.videoState.setState(z.PAUSED),R(t.playbackState,v.PAUSED)}),r(be(this.player,"canPlay"),()=>{var p;((p=this.videoState.getTransition())===null||p===void 0?void 0:p.to)===z.READY&&this.videoState.setState(z.READY)}),r(this.isLive$,e.isLive$),r(ws(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=L(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ve(0));r(o,this.syncPlayback);const{playbackDuration$:u,ping$:d,connectionType$:l,connectionReused$:c}=ZS(this.player);r(l,this.params.output.httpConnectionType$),r(c,this.params.output.httpConnectionReused$),r(u,this.maxSeekBackTime$),r(d.pipe(ye()),e.firstBytesEvent$),r(be(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(dt({isLive:this.isLive$,isShort:e.duration$.pipe($(p=>p<60))}),({isLive:p,isShort:S})=>{const g=!p&&S;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:g}}})}),r(n.pipe(j(p=>p>this.params.tuning.insufficientBufferRuleMargin),ye()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(be(this.player,"manifestLoaded").pipe(ye()).subscribe(()=>{this.subscription.add(be(this.player,"playbackPlaying").pipe(ye(),Ot(void 0)).subscribe(e.firstFrameEvent$,s))},s)),this.subscription.add(Ut(this.video,t.isLooped,s));const{volumeState$:h,looped$:f,playbackRateState$:m}=mt(this.video);this.subscription.add(pt(this.video,t.volume,h,s)),this.subscription.add(h.subscribe(e.volume$,s)),this.subscription.add(f.subscribe(e.loopedEvent$)),this.subscription.add(Et(this.video,t.playbackRate,m,s))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(z.STOPPED),R(this.params.desiredState.playbackState,v.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(z.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3);const r=ei(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Zt.PLAYBACK_SHIFT);this.player.attachSource(r)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(z.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(z.PAUSED),this.video.pause()}destroy(){var e,t;this.subscription.unsubscribe(),this.textTracksManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(s){}St(this.video),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var Vi=i=>{switch(i){case"mobile":return ne.Q_144P;case"lowest":return ne.Q_240P;case"low":return ne.Q_360P;case"sd":case"medium":return ne.Q_480P;case"hd":case"high":return ne.Q_720P;case"fullhd":case"full":return ne.Q_1080P;case"quadhd":case"quad":return ne.Q_1440P;case"ultrahd":case"ultra":return ne.Q_2160P}},$t=i=>ue(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(t instanceof DOMException&&(t.code===20||t.name==="AbortError"))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(s){return i.muted=!1,console.warn(s),!1}}return!0});function Ae(){return pe()}function hu(i){return Ae()-i}function go(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),s=/^([a-z]+:)?\/\//i,r=n=>s.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 _g(i,e,t){const s=(...r)=>{t.apply(null,r),i.removeEventListener(e,s)};i.addEventListener(e,s)}function gs(i,e,t,s){const r=window.XMLHttpRequest;let a,n,o,u=!1,d=0,l,c,h=!1,f="arraybuffer",m=7e3,p=2e3,S=()=>{if(u)return;P(l);const B=hu(l);let ie;if(B<p){ie=p-B,setTimeout(S,ie);return}p*=2,p>m&&(p=m),n&&n.abort(),n=new r,N()};const g=B=>(a=B,V),T=B=>(c=B,V),I=()=>(f="json",V),_=()=>{if(!u){if(--d>=0){S(),s&&s();return}u=!0,c&&c(),t&&t()}},A=B=>(h=B,V),N=()=>{l=Ae(),n=new r,n.open("get",i);let B=0,ie,ce=0;const Se=()=>(P(l),Math.max(l,Math.max(ie||0,ce||0)));if(a&&n.addEventListener("progress",k=>{const G=Ae();a.updateChunk&&k.loaded>B&&(a.updateChunk(Se(),k.loaded-B),B=k.loaded,ie=G)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>_())),n.addEventListener("load",()=>{if(u)return;P(n);const k=n.status;if(k>=200&&k<300){if(n.response.byteLength&&a){const G=n.response.byteLength-B;G&&a.updateChunk&&a.updateChunk(Se(),G)}c&&c(),n&&e(n.response)}else _()}),n.addEventListener("error",()=>{_()}),h){const k=()=>{P(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ce=Ae(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=f,n.send(),V},V={withBitrateReporting:g,withParallel:A,withJSONResponse:I,withRetryCount:B=>(d=B,V),withRetryInterval:(B,ie)=>(w(B)&&(p=B),w(ie)&&(m=ie),V),withTimeout:B=>(o=B,V),withFinally:T,send:N,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return V}const wg=100,kg=2e3,Pg=500;let Rg=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,s){return{start:e,end:t,bytes:s}}_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-Pg;if(t-e>kg){let s=0,r=0;for(;this.intervals.length>0;){const a=this.intervals[0];if(a.end<=t)s+=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;s+=n;const u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&s>0){const a=r*8/(s/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(s)} 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,s){return this.intervals.push(this._createInterval(e,t,s)),this._joinIntervals(),this.intervals.length>wg&&(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 Ig{constructor(e,t,s,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=s,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 s=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()-s,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=gs(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 s=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),s>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),s),!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,s,r){const a={};return a.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=s,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}`),s(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=s,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 ns=1e4,os=3,Dg=300,Cg=2e3,Og=6e4,Lg=10,xg=1,Ng=500;class Bg{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 Rg(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=go(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let s=0;s<this.manifest.length;++s)if(t=this.manifest[s],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=go(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 s=e.buffered.length;return s!==0&&(t=e.buffered.end(s-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 s;Boolean(e.error)&&!this.destroyed&&(t(`Video element error: ${(s=e.error)===null||s===void 0?void 0:s.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const s=this._getBufferSizeSec();!this.paused&&s<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(s+.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,s=t.buffered.length;let r;s!==0&&(r=t.buffered.start(s-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let s,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):(!s||s.bitrate>a.bitrate)&&(s=a));return r||s}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||w(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:s,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,s("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=()=>{_g(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 Ig(os,ns,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:s,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,N)=>{u&&u.abort(),u=gs(this.urlResolver.resolve(_,!1),A,N,()=>this._retryCallback()).withTimeout(ns).withBitrateReporting(this.bitrateSwitcher).withRetryCount(os).withFinally(()=>{u=null}).send()},f=(_,A,N)=>{P(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(_,!1),A,N,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=_=>{const A=s.playbackRate;s.playbackRate!==_&&(t(`Playback rate switch: ${A}=>${_}`),s.playbackRate=_)},p=_=>{this.lowLatency=_,t(`lowLatency changed to ${_}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let _=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}const N=Ae()-1e4;let X=0;for(let F=0;F<this.bufferStates.length;F++){const Z=this.bufferStates[F];_=Math.min(_,Z.buf),Z.ts<N&&X++}this.bufferStates.splice(0,X),t(`update playback rate; minBuffer=${_} drop=${X} jitter=${this.sourceJitter}`);let Y=_-xg;this.sourceJitter>=0?Y-=this.sourceJitter/2:this.sourceJitter-=1,Y>3?m(1.15):Y>1?m(1.1):Y>.3?m(1.05):m(1)}},g=_=>{let A;const N=()=>A&&A.start?A.start.length:0,X=k=>A.start[k]/1e3,Y=k=>A.dur[k]/1e3,F=k=>A.fragIndex+k,Z=(k,G)=>({chunkIdx:F(k),startTS:X(k),dur:Y(k),discontinuity:G}),V=()=>{let k=0;if(A&&A.dur){let G=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,oe=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ve=G;this.sourceJitter>1&&(ve+=this.sourceJitter-1);let ge=A.dur.length-1;for(;ge>=0&&(ve-=A.dur[ge],!(ve<=0));--ge);k=Math.min(ge,A.dur.length-1-oe),k=Math.max(k,0)}return Z(k,!0)},B=k=>{const G=N();if(!(G<=0)){if(w(k)){for(let oe=0;oe<G;oe++)if(X(oe)>k)return Z(oe)}return V()}},ie=k=>{const G=N(),oe=k?k.chunkIdx+1:0,ve=oe-A.fragIndex;if(!(G<=0)){if(!k||ve<0||ve-G>Lg)return t(`Resync: offset=${ve} bChunks=${G} chunk=`+JSON.stringify(k)),V();if(!(ve>=G))return Z(oe-A.fragIndex,!1)}},ce=(k,G,oe)=>{d&&d.abort(),d=gs(this.urlResolver.resolve(k,!0,this.lowLatency),G,oe,()=>this._retryCallback()).withTimeout(ns).withRetryCount(os).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(k,G)=>{ce(_,oe=>{if(!c())return;A=oe;const ve=Boolean(A.lowLatency);ve!==this.lowLatency&&p(ve);let ge=0;for(let Ie=0;Ie<A.dur.length;++Ie)ge+=A.dur[Ie];ge>0&&(P(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,k(B(G))},()=>this._handleNetworkError())},nextChunk:ie}},T=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),P(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:_=>{const{videoElement:A,logger:N}=this.params;let X=g(e.jidxUrl),Y,F,Z,V,B=0,ie,ce,Se;const k=()=>{ie&&(clearTimeout(ie),ie=void 0);const ee=Math.max(Ng,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ee=B+ee,Pe=Ae(),xe=Math.min(1e4,Ee-Pe);B=Pe;const At=()=>{d||c()&&X.seek(()=>{c()&&(B=Ae(),G(),k())})};xe>0?ie=window.setTimeout(()=>{this.paused?k():At()},xe):At()},G=()=>{let ee;for(;ee=X.nextChunk(V);)V=ee,Qe(ee);const Ee=X.nextChunk(Z);if(Ee){if(Z&&Ee.discontinuity){N("Detected discontinuity; restarting playback"),this.paused?k():(T(),this._initPlayerWith(e));return}Ie(Ee)}else k()},oe=(ee,Ee)=>{if(!c()||!this.sourceBuffer)return;let Pe,xe,At;const Je=gt=>{window.setTimeout(()=>{c()&&oe(ee,Ee)},gt)};if(this.sourceBuffer.updating)N("Source buffer is updating; delaying appendBuffer"),Je(100);else{const gt=Ae(),_t=A.currentTime;!this.paused&&A.buffered.length>1&&ce===_t&&gt-Se>500&&(N("Stall suspected; trying to fix"),this._fixupStall()),ce!==_t&&(ce=_t,Se=gt);const di=this._getBufferSizeSec();if(di>30)N(`Buffered ${di} seconds; delaying appendBuffer`),Je(2e3);else try{this.sourceBuffer.appendBuffer(ee),this.videoPlayStarted?(this.bufferStates.push({ts:gt,buf:di}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ee&&Ee()}catch(Ft){if(Ft.name==="QuotaExceededError")N("QuotaExceededError; delaying appendBuffer"),At=this.sourceBuffer.buffered.length,At!==0&&(Pe=this.sourceBuffer.buffered.start(0),xe=_t,xe-Pe>4&&this.sourceBuffer.remove(Pe,xe-3)),Je(1e3);else throw Ft}}},ve=()=>{F&&Y&&(N([`Appending chunk, sz=${F.byteLength}:`,JSON.stringify(Z)]),oe(F,function(){F=null,G()}))},ge=ee=>e.fragUrlTemplate.replace("%%id%%",ee.chunkIdx),Ie=ee=>{c()&&f(ge(ee),(Ee,Pe)=>{if(c()){if(Pe/=1e3,F=Ee,Z=ee,n=ee.startTS,Pe){const xe=Math.min(10,ee.dur/Pe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*xe:xe}ve()}},()=>this._handleNetworkError())},Qe=ee=>{c()&&(P(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ge(ee),!1)))},oi=ee=>{c()&&(e.cachedHeader=ee,oe(ee,()=>{Y=!0,ve()}))};a=!0,X.seek(ee=>{if(c()){if(B=Ae(),!ee){k();return}V=ee,!K(_)||ee.startTS>_?Ie(ee):(Z=ee,G())}},_),e.cachedHeader?oi(e.cachedHeader):h(e.headerUrl,oi,()=>this._handleNetworkError())},stop:T,getTimestampSec:()=>n},l}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),w(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,P(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),s({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return w(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=c=>{if(!this.autoQuality)return;let h,f,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(f=this._getBufferSizeSec(),m=c/this.bitrate,f>10&&m>.8||f>15&&m>.5||f>20&&m>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},a=(()=>({updateChunk:(h,f)=>{const m=Ae();if(this.chunkRateEstimator.addInterval(h,m,f)){const S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:m-h,speed:S}),!0}},get:()=>{const h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}}))();let n=-1/0,o,u=!0;const d=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&hu(n)<3e4)return;s(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,s){this.manifestRequest=gs(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(ns).withRetryCount(os).withRetryInterval(Dg,Cg).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;$t(t).then(s=>{s||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,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}`),s({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))},Og))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var W;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(W||(W={}));const Mg=[W.PAUSED,W.PLAYING,W.READY],Ug=[W.PAUSED,W.PLAYING,W.READY];class Fg{constructor(e){this.subscription=new se,this.videoState=new le(W.STOPPED),this.representations$=new y([]),this.textTracksManager=new it,this.maxSeekBackTime$=new y(1/0),this.zeroTime$=new y(void 0),this.liveOffset=new Ba,this._dashCb=r=>{var a,n,o,u;switch(r.name){case"buffering":{const d=r.isBuffering;this.params.output.isBuffering$.next(d);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:C.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const d=r.manifest,l=[];for(const c of d){const h=(a=c.name)!==null&&a!==void 0?a:c.index.toString(10),f=(n=Vi(c.name))!==null&&n!==void 0?n:Mt(c.video),m=c.bitrate/1e3,p=Object.assign({},c.video);if(!f)continue;const S={id:h,quality:f,bitrate:m,size:p};l.push({track:S,representation:c})}this.representations$.next(l),this.params.output.availableVideoTracks$.next(l.map(({track:c})=>c)),((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===W.MANIFEST_READY&&this.videoState.setState(W.MANIFEST_READY);break}case"qualitySwitch":{const d=r.quality,l=(u=this.representations$.getValue().find(({representation:c})=>c===d))===null||u===void 0?void 0:u.track;this.params.output.hostname$.next(new URL(d.headerUrl,this.params.source.url).hostname),w(l)&&this.params.output.currentVideoTrack$.next(l);break}case"bandwidth":{const{size:d,duration:l}=r;this.params.dependencies.throughputEstimator.addRawSpeed(d,l);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{var r;const a=this.videoState.getState(),n=this.videoState.getTransition(),o=this.params.desiredState.playbackState.getState(),u=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${a}; videoTransition: ${JSON.stringify(n)}; desiredPlaybackState: ${o}; seekState: ${JSON.stringify(d)};`}),o===v.STOPPED){a!==W.STOPPED&&(this.videoState.startTransitionTo(W.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(W.STOPPED));return}if(!n){if(Ug.includes(a)){const l=(r=this.params.desiredState.videoTrack.getTransition())===null||r===void 0?void 0:r.to;w(l)&&this.setVideoTrack(l);const c=this.params.desiredState.autoVideoTrackSwitching.getTransition();c&&this.setAutoQuality(c.to)}if((u==null?void 0:u.to)!==v.PAUSED&&d.state===H.Requested&&Mg.includes(a)){this.seek(d.position-this.liveOffset.getTotalPausedTime());return}switch(a){case W.STOPPED:this.videoState.startTransitionTo(W.MANIFEST_READY),this.dash.attachSource(ei(this.params.source.url));return;case W.MANIFEST_READY:this.videoState.startTransitionTo(W.READY),this.prepare();break;case W.READY:if(o===v.PAUSED)this.videoState.setState(W.PAUSED);else if(o===v.PLAYING){this.videoState.startTransitionTo(W.PLAYING);const l=u==null?void 0:u.from;l&&l===v.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(W.PAUSED)})}return;case W.PLAYING:o===v.PAUSED&&(this.videoState.startTransitionTo(W.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case W.PAUSED:o===v.PLAYING&&(this.videoState.startTransitionTo(W.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(W.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return x(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:C.WTF,message:"DashLiveProvider internal logic error",thrown:r})};L(this.videoState.stateChangeStarted$.pipe($(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe($(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=vt(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(Re(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 s=mt(this.video);this.subscription.add(s.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===W.READY&&this.videoState.setState(W.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===H.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(W.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(me(),$(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(dt({zeroTime:this.zeroTime$.pipe(j(w)),position:s.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Ut(this.video,this.params.desiredState.isLooped,t)).add(pt(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(Et(this.video,this.params.desiredState.playbackRate,s.playbackRateState$,t)).add(s.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(s.playing$.subscribe(this.params.output.firstFrameEvent$)).add(s.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:r}})=>{const a=r&&GS(r);this.dash.setMaxAutoQuality(a)})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case W.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(v.STOPPED);break;case W.MANIFEST_READY:case W.READY:((a=this.params.desiredState.playbackState.getTransition())===null||a===void 0?void 0:a.to)===v.READY&&this.params.desiredState.playbackState.setState(v.READY);break;case W.PAUSED:this.params.desiredState.playbackState.setState(v.PAUSED);break;case W.PLAYING:this.params.desiredState.playbackState.setState(v.PLAYING);break;default:return x(r.to)}},t)).add(L(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ve(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),St(this.video)}createLiveDashPlayer(){const e=new Bg({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,s,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=(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||s===void 0?void 0:s.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),l=!d&&w(u)?u:(a=Fi(o.map(({track:h})=>h),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState()}))===null||a===void 0?void 0:a.id,c=(n=o.find(({track:h})=>h.id===l))===null||n===void 0?void 0:n.representation;P(c,"Representations missing"),this.dash.startPlay(c,d),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(l),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(d)}setVideoTrack(e){var t;const s=(t=this.representations$.getValue().find(({track:r})=>r.id===e))===null||t===void 0?void 0:t.representation;P(s,`No such representation ${e}`),this.dash.switchByName(s.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=-e,s=t<=this.maxSeekBackTime$.getValue()?t:0;this.params.output.position$.next(e/1e3),this.liveOffset.resetTo(s),this.dash.reinit(ei(this.params.source.url,s))}}var fu=i=>{var e,t;const s=i.get("X-Delivery-Type"),r=i.get("X-Reused"),a=s===null?ki.HTTP1:(e=s)!==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}},It=(i,e)=>{let t=0;for(let s=0;s<i.length;s++){const r=i.start(s)*1e3,a=i.end(s)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};const Vg=i=>{const e=document.createElement("a");return e.href=i,e.origin},Hg=i=>{const e=document.createElement("a");return e.href=i,e.host};class pu{constructor(e,t=[],s,r,a,n){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=s,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,s,r,a,n,o,u,d;if(P(this._xhr),((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(s=this._errorCb)===null||s===void 0||s.call(this,`Http${(r=this._xhr)===null||r===void 0?void 0:r.status}`,`XHR response code ${(a=this._xhr)===null||a===void 0?void 0:a.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const l=Bi(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(c=>c.split(":").map(h=>h.trim())));(n=this._headersCb)===null||n===void 0||n.call(this,new Headers(l))}else this._xhr.readyState===4?(o=this._completeCb)===null||o===void 0||o.call(this,this._xhr.response):this._xhr.readyState===3&&((u=this._progressCb)===null||u===void 0||u.call(this,this._xhr.response))}catch(l){throw(d=this._errorCb)===null||d===void 0||d.call(this,"XHR2CallbackError",`xhr2 callback threw ${String(l)}`,l),l}},this._xhr.onerror=()=>{var t;(t=this._xhr)===null||t===void 0||t.abort(),this._retryTimeout=window.setTimeout(()=>{var s;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(s=this._errorCb)===null||s===void 0||s.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(Hg(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 ks{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(s){if(s.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",s),s}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,s,r,a,n,o){this.abort(()=>{let u=0;const d=Date.now();let l=0,c=0,h=0;const f=p=>{r(ks._str2ua(p.substr(u))),u=p.length};let m=e.baseURL+"&bytes="+t+"-"+s;this._params.requestQuic&&(m=ii(m)),this._lastXhr=new pu(m,e.failoverHosts,p=>{this._lastXhr=void 0,f(p);const S=Date.now()-d;this._params.onBandwidthChange({size:p.length,duration:S,speed:8*p.length/(S/1e3)}),this._onDashCallback("loading",{size:p.length,done:!0}),a==null||a()},p=>{if(p.length-u>o&&f(p),c===0){c=Date.now();return}h=p.length-l;const S=Date.now()-c;h>=100*1024&&S>=1e3&&(this._params.onBandwidthChange({size:h,duration:S,speed:8*h/(S/1e3)}),h=0,l=p.length,c=Date.now()),this._onDashCallback("loading",{size:p.length,done:!1})},n,(p,S,g)=>this._params.onError(p,S,g))})}abort(e){var t;(t=this._lastXhr)===null||t===void 0||t.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e==null||e()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(s){throw this._params.onError("SourceBuffer","Source Buffer update error",s),s}};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=ks._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 s=new Uint8Array(e.byteLength+t.byteLength);return s.set(e,0),s.set(t,e.byteLength),s}static _str2ua(e){const t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);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 Gg{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)?)?$/,s=(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:s(r==null?void 0:r[2],a),months:s(r==null?void 0:r[3],a),weeks:s(r==null?void 0:r[4],a),days:s(r==null?void 0:r[5],a),hours:s(r==null?void 0:r[6],a),minutes:s(r==null?void 0:r[7],a),seconds:s(r==null?void 0:r[8],a)};return n.hours*3600+n.minutes*60+n.seconds}getRepresentations(){return this._representations}attachSource(e,t){let s=e;this._config.REQUEST_QUIC&&(s=ii(s)),new pu(s,t,r=>{this.attachManifest(r,t,Vg(s))},void 0,r=>{this._params.onResponseHeaders(r)},(r,a,n)=>this._params.onError(r,a,n))}attachManifest(e,t,s){const a=new DOMParser().parseFromString(e,"text/xml").documentElement,n=(d,l)=>{const c=d.attributes.getNamedItem(l);return c?c.value:null};this._duration=this._parseDurationFromISO8601(String(n(a,"mediaPresentationDuration")));const o=[],u=[];if(Array.prototype.forEach.call(a.getElementsByTagName("Representation"),d=>{var l,c,h,f,m,p,S,g,T,I,_,A,N,X,Y,F,Z,V,B;const ie=d.getElementsByTagName("SegmentBase")[0],ce=ie&&n(ie,"indexRange").split("-"),Se=ie&&ie.getElementsByTagName("Initialization")[0],k=Se&&n(Se,"range").split("-");if(!k||!ce){const Qe=d.parentElement;if((Qe==null?void 0:Qe.getAttribute("contentType"))==="text"){const oi=(l=d.getAttribute("id"))!==null&&l!==void 0?l:void 0,ee=(s?s+"/":"")+((m=(f=(h=(c=d.getElementsByTagName("BaseURL"))===null||c===void 0?void 0:c[0])===null||h===void 0?void 0:h.childNodes)===null||f===void 0?void 0:f[0])===null||m===void 0?void 0:m.data),Ee=(p=Qe.getAttribute("lang"))!==null&&p!==void 0?p:void 0;ee&&u.push({id:oi,url:ee,language:Ee})}return}const G=.1,oe=Number((S=d.attributes.getNamedItem("bandwidth"))===null||S===void 0?void 0:S.value),ve=(s?s+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ge;const Ie=(T=(g=d.attributes.getNamedItem("frameRate"))===null||g===void 0?void 0:g.value)!==null&&T!==void 0?T:void 0;ge=Ie?Ma(Ie):void 0,o.push({width:Number((I=d.attributes.getNamedItem("width"))===null||I===void 0?void 0:I.value),height:Number((_=d.attributes.getNamedItem("height"))===null||_===void 0?void 0:_.value),bandwidth:oe,baseURL:ve,failoverHosts:t,indexFrom:Number(ce[0]),indexTo:Number(ce[1]),initFrom:Number(k[0]),initTo:Number(k[1]),codecs:(N=(A=d.attributes.getNamedItem("codecs"))===null||A===void 0?void 0:A.value)!==null&&N!==void 0?N:void 0,mimeType:(Y=(X=d.attributes.getNamedItem("mimeType"))===null||X===void 0?void 0:X.value)!==null&&Y!==void 0?Y:void 0,fps:ge,bufferSize:G*oe/8,bufferLength:G,name:(Z=(F=d.attributes.getNamedItem("okQuality"))===null||F===void 0?void 0:F.value)!==null&&Z!==void 0?Z:void 0,id:(B=(V=d.attributes.getNamedItem("id"))===null||V===void 0?void 0:V.value)!==null&&B!==void 0?B:void 0})}),o.length)this._representations=o;else{this._onDashCallback("error");return}u.forEach(({id:d,language:l,url:c})=>{const h=document.createElement("track");h.setAttribute("src",c),d&&h.setAttribute("id",d),l&&h.setAttribute("srclang",l),this._video.appendChild(h)}),this._representations.sort((d,l)=>l.bandwidth-d.bandwidth),this._params.onManifestReady(this._representations)}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const s=Date.now();this._stream.load(e,e.initFrom,e.indexTo,r=>{let a=e.initTo-e.initFrom+1;if(!r.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(r.buffer,0,a);const n=new DataView(r.buffer);a+=12;const o=n.getUint32(a+4,!1);a+=8;let u=n.getUint32(a,!1),d=n.getUint32(a+4,!1)+(e.indexTo+1);a+=8;const l=n.getUint16(a+2,!1);a+=4,e.refs=[];for(let h=0;h<l;h+=1){const f=d+(n.getUint32(a,!1)&2147483647),m=u+n.getUint32(a+4,!1);a+=12,e.refs.push({fromTime:u/o,toTime:m/o,fromOffset:d,toOffset:f-1}),d=f,u=m}const c=e.refs[e.refs.length-1];c.toTime-c.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,r=>{this._params.onResponseHeaders(r),this._params.onIdxRequestPing(Date.now()-s)},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 s=new t;let r,a;const n=()=>{const d=this._findRef(this._video.currentTime);if(!d||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const f=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),f)}const l=this._appendVector[String(d.fromTime)];l!==r&&(r=l,this._params.onRepresentationPlay(l));let c;if(this._findRef(d.toTime)){const f=this._buffer.getByTime(this._video.currentTime);if(!f){this._onDashCallback("buffering");return}c=f.to-this._video.currentTime,c<e.bufferLength&&(this._onDashCallback("buffering"),a!==f.to&&(a=f.to,window.setTimeout(()=>{try{const m=this._buffer.getNextWithGap(f);m&&(this._video.currentTime=m.from)}catch(m){throw this._params.onError("GapSyncError",`Seek Error ${String(m)}`,m),m}},c*1e3)))}},o=()=>{this._loopTimeout=window.setTimeout(()=>{try{n()}catch(d){throw this._params.onError("LoopError",`Dash Loop exception ${String(d)}`,d),d}o()},250)},u=()=>{if(!this._stream)try{const d=s.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new ks({mediaSource:s,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),s.duration||(s.duration=this._duration),this._loopTimeout||o(),s.removeEventListener("sourceopen",u),s.removeEventListener("webkitsourceopen",u)};s.addEventListener("sourceopen",u,!1),s.addEventListener("webkitsourceopen",u,!1),this._video&&(this._video.src=window.URL.createObjectURL(s),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,s=!1,r=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const a=this._findRef(t);if(a){if(s){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 s=this._buffer.getByTime(this._video.currentTime),r=this._findRef(this._video.currentTime);if(!s||!r){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const a=.1;if(r.toTime<s.to+a){const n=this._findRef(r.toTime);n&&n.toTime<s.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||K(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const s=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!s)return;if(Array.isArray(s)&&s.length===0){this._params.onError("emptyrefs","Empty refs");return}let r;for(let a=0;a<s.length;a++){const n=s[a];if(n.fromTime<=e&&n.toTime>e)return n;n.fromTime>e&&(!r||n.fromTime<r.fromTime)&&(r=n)}if(!r){const a=s[s.length-1];if(e>a.toTime)return a}return r}_isLastRef(e){var t;const s=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!s)return!1;const r=s[s.length-1];return e.fromTime===r.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const s=this._video.buffered.start(t),r=this._video.buffered.end(t);if(e>s&&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(i){i.STOPPED="stopped",i.MANIFEST_LOADED="manifest-loaded",i.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",i.METADATA_LOADED="metadata-loaded",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(Q||(Q={}));const Yg=[Q.PAUSED,Q.PLAYING];class qg{constructor(e){this.videoState=new le(Q.STOPPED),this.subscription=new se,this.representations$=new y([]),this.currentRepresentation$=new y(void 0),this.textTracksManager=new it,this.elementSize$=new y(void 0),this.dashLiteEvents={idxRequestPing$:new O,responseHeaders$:new O,manifestReady$:new O,representationPlay$:new O,error$:new O},this.handleManifestReady=t=>{var s,r,a;const n=[];for(const o of t){const u=(r=(s=o.name)!==null&&s!==void 0?s:o.id)!==null&&r!==void 0?r:o.height.toString(10),d=(a=o.name&&Vi(o.name))!==null&&a!==void 0?a:Mt(o),l=o.bandwidth/1e3,c={width:o.width,height:o.height},h=o.fps;if(!d)continue;const f={id:u,quality:d,bitrate:l,size:c,fps:h};n.push({track:f,representation:o})}this.representations$.next(n),this.params.output.availableVideoTracks$.next(n.map(({track:o})=>o)),this.videoState.setState(Q.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var s;const r=(s=this.representations$.getValue().find(({representation:a})=>a===t))===null||s===void 0?void 0:s.track;r&&(this.params.output.currentVideoTrack$.next(r),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(r.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return P(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),s=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(s)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(n)};`}),r===v.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),R(this.params.desiredState.playbackState,v.STOPPED,!0));return}if(!s)switch((a==null?void 0:a.to)!==v.PAUSED&&n.state===H.Requested&&Yg.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===v.READY?R(this.params.desiredState.playbackState,v.READY):r===v.PAUSED?(this.videoState.setState(Q.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED)):r===v.PLAYING&&(this.videoState.startTransitionTo(Q.PLAYING),this.playIfAllowed());return;case Q.PLAYING:r===v.PAUSED?(this.videoState.startTransitionTo(Q.PAUSED),this.video.pause()):(a==null?void 0:a.to)===v.PLAYING&&R(this.params.desiredState.playbackState,v.PLAYING);return;case Q.PAUSED:r===v.PLAYING?(this.videoState.startTransitionTo(Q.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===v.PAUSED&&R(this.params.desiredState.playbackState,v.PAUSED);return;default:return x(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),L(this.videoState.stateChangeStarted$.pipe($(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe($(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(t)}`})}),this.video=vt(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(Re(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new rg(this.video),this.dash=new Gg({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:t=>this.dashLiteEvents.manifestReady$.next(t),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,s,r)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:s,thrown:r,category:C.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"DashProvider",category:C.WTF,message:"DashProvider internal logic error",thrown:o})},r=()=>{const o=this.params.desiredState.autoVideoTrackSwitching.getState(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();return u?u.to:o},a=mt(this.video),n=(o,u)=>this.subscription.add(o.subscribe(u,s));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(a.seeking$.subscribe(()=>{K(this.params.desiredState.seekState.getState().state!==H.Applying)&&(this.videoState.getState()===Q.PLAYING||this.videoState.getState()===Q.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(Ut(this.video,t.isLooped,s)),this.subscription.add(pt(this.video,t.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Et(this.video,t.playbackRate,a.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),n(ws(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)},s)).add(a.pause$.subscribe(()=>{this.videoState.setState(Q.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED)})).add(a.playing$.subscribe(()=>{this.videoState.setState(Q.PLAYING),R(this.params.desiredState.playbackState,v.PLAYING)},s)).add(a.loadedMetadata$.subscribe(()=>{this.videoState.setState(Q.METADATA_LOADED)},s)).add(a.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},s)).add(this.dashLiteEvents.error$.pipe($(({id:o,message:u,thrown:d})=>({id:`DashLite_${o}`,category:C.WTF,message:u,thrown:d}))).subscribe(this.params.output.error$)).add(L(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$,this.params.output.element$,this.elementSize$,U(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(),m=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),p=this.elementSize$.getValue(),S=r();h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to);let g;if(!S&&w(f))g=f;else{const T=It(this.video.buffered,this.video.currentTime*1e3),I=S?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,_=Math.min(T/I,1);g=(u=Fi(c.map(({track:A})=>A),{container:p,throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:_,playbackRate:this.video.playbackRate,current:(o=c.find(({representation:A})=>A===l))===null||o===void 0?void 0:o.track}))===null||u===void 0?void 0:u.id}return w(g)?(d=c.find(({track:T})=>T.id===g))===null||d===void 0?void 0:d.representation:void 0}),me()).subscribe(this.currentRepresentation$,s)).add(dt({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(j(o=>o.to===Q.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(j(w))}).pipe(ye()).subscribe(()=>this.videoState.setState(Q.INITIAL_REPRESENTATION_SELECTED),s)).add(this.currentRepresentation$.pipe(j(w),me((o,u)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?o.height<=u.height:o===u)).subscribe(o=>{const u=It(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(Re(o.baseURL)))},s)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:u,reused:d}=fu(o);this.params.output.httpConnectionType$.next(u),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(ye(),Ot(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,s)).add(this.dashLiteEvents.representationPlay$.pipe(j(w)).subscribe(this.handleRepresentationPlay,s)).add(L(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ve(0)).subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),St(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 x(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){$t(this.video).then(e=>{e||(this.videoState.setState(Q.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED,!0))})}}var Me;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(Me||(Me={}));var Ps;(function(i){i.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",i.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Ps||(Ps={}));var Ue;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(Ue||(Ue={}));var te;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(te||(te={}));var si;(function(i){i.MP4="mp4",i.WEBM="webm"})(si||(si={}));var ca=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};const jg=(i,e={})=>{const s=e.timeout||1,r=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-r-1>s},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},zg=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",bo=zg?jg:window.requestIdleCallback;var wr,kr;let vu=!1;try{vu=lu()&&parseInt((kr=(wr=navigator.userAgent.match(/Version\/(\d+)/))===null||wr===void 0?void 0:wr[1])!==null&&kr!==void 0?kr:"",10)<16}catch(i){console.error(i)}class Wg{constructor(e){this.bufferFull$=new O,this.error$=new O,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const s=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!s),this.currentTask=null}this.queue.length&&this.pull()}catch(s){this.error$.next({id:"BufferTaskQueueUnknown",category:C.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:s})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return ue(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(s=>{const r={operation:"append",data:e,signal:t,callback:s};this.queue.push(r),this.pull()})})}remove(e,t,s){return ue(this,void 0,void 0,function*(){return s&&s.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:s,callback:r};this.queue.unshift(a),this.pull()})})}abort(e){return ue(this,void 0,void 0,function*(){return new Promise(t=>{let s;vu&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);s&&(this.queue=[s]),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:s}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&s==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"&&s==="remove"||this.error$.next({id:`BufferTaskQueue:${s}`,category:C.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:x(t)}}}var yo=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};const mu=new TextDecoder("ascii"),Su=i=>{let e=0,t=i.getUint32(e);e+=4;const s=new DataView(i.buffer,i.byteOffset+e,4),r=mu.decode(s);e+=4,t===0?t=1/0:t===1&&(e+=8,t=1/0);const a=Math.min(t,i.byteLength)-e,n=new DataView(i.buffer,i.byteOffset+e,a);return{id:r,size:t,contents:n}},Qg=i=>mu.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",Jg=(i,e,t)=>{const s=Su(i),r=[];let a=0;const n=()=>{const p=s.contents.getUint32(a);return a+=4,p};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,m=(t?t.to+1:i.byteOffset+i.byteLength)+c;for(let p=0;p<h;p++){const S=n(),g=S>>>31,T=S<<1>>>1,I=n();if(n(),g!==0)throw new Error("Unsupported multilevel sidx");const _=I/d*1e3;r.push({status:te.NONE,time:{from:f,to:f+_},byte:{from:m,to:m+T-1}}),f+=_,m+=T}return r},Kg=i=>{let e=0,t=!1,s=!1;for(;e<=i.byteLength&&!t;){const r=new DataView(i.buffer,i.byteOffset+e);try{const a=Su(r);if(s||(s=a.id==="mdat"),e+a.size<=i.byteLength)e+=a.size;else break}catch(a){t=!0}}return e>0&&e<=i.byteLength&&s?new DataView(i.buffer,i.byteOffset,e):null},Xg={validateData:Qg,parseInit:()=>null,getIndexRange:()=>{},parseSegments:Jg,parseFeedableSegmentChunk:Kg};var E;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.Chapters=272869232]="Chapters",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.SilentTracks=22612]="SilentTracks",i[i.SilentTrackNumber=22743]="SilentTrackNumber",i[i.Position=167]="Position",i[i.PrevSize=171]="PrevSize",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.EncryptedBlock=175]="EncryptedBlock",i[i.Attachments=423732329]="Attachments",i[i.Tags=307544935]="Tags",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.CueRelativePosition=240]="CueRelativePosition",i[i.CueDuration=178]="CueDuration",i[i.CueBlockNumber=21368]="CueBlockNumber",i[i.CueCodecState=234]="CueCodecState",i[i.CueReference=219]="CueReference",i[i.CueRefTime=150]="CueRefTime"})(E||(E={}));var D;(function(i){i.SignedInteger="int",i.UnsignedInteger="uint",i.Float="float",i.String="string",i.UTF8="utf8",i.Date="date",i.Master="master",i.Binary="binary"})(D||(D={}));const To={[E.EBML]:{type:D.Master},[E.EBMLVersion]:{type:D.UnsignedInteger},[E.EBMLReadVersion]:{type:D.UnsignedInteger},[E.EBMLMaxIDLength]:{type:D.UnsignedInteger},[E.EBMLMaxSizeLength]:{type:D.UnsignedInteger},[E.DocType]:{type:D.String},[E.DocTypeVersion]:{type:D.UnsignedInteger},[E.DocTypeReadVersion]:{type:D.UnsignedInteger},[E.Void]:{type:D.Binary},[E.Segment]:{type:D.Master},[E.SeekHead]:{type:D.Master},[E.Seek]:{type:D.Master},[E.SeekID]:{type:D.Binary},[E.SeekPosition]:{type:D.UnsignedInteger},[E.Info]:{type:D.Master},[E.TimestampScale]:{type:D.UnsignedInteger},[E.Duration]:{type:D.Float},[E.Tracks]:{type:D.Master},[E.Chapters]:{type:D.Master},[E.Cluster]:{type:D.Master},[E.Timestamp]:{type:D.UnsignedInteger},[E.SilentTracks]:{type:D.Master},[E.SilentTrackNumber]:{type:D.UnsignedInteger},[E.Position]:{type:D.UnsignedInteger},[E.PrevSize]:{type:D.UnsignedInteger},[E.SimpleBlock]:{type:D.Binary},[E.BlockGroup]:{type:D.Master},[E.EncryptedBlock]:{type:D.Binary},[E.Attachments]:{type:D.Master},[E.Tags]:{type:D.Master},[E.Cues]:{type:D.Master},[E.CuePoint]:{type:D.Master},[E.CueTime]:{type:D.UnsignedInteger},[E.CueTrackPositions]:{type:D.Master},[E.CueTrack]:{type:D.UnsignedInteger},[E.CueClusterPosition]:{type:D.UnsignedInteger},[E.CueRelativePosition]:{type:D.UnsignedInteger},[E.CueDuration]:{type:D.UnsignedInteger},[E.CueBlockNumber]:{type:D.UnsignedInteger},[E.CueCodecState]:{type:D.UnsignedInteger},[E.CueReference]:{type:D.Master},[E.CueRefTime]:{type:D.UnsignedInteger}},gu=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const s=Rs(i,t),r=s in To,a=r?To[s].type:D.Binary,n=i.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(i.buffer,i.byteOffset+t+1,o-1),d=n&255>>o,l=Rs(u),c=d*Math.pow(2,(o-1)*8)+l,h=t+o;let f;return h+c>i.byteLength?f=new DataView(i.buffer,i.byteOffset+h):f=new DataView(i.buffer,i.byteOffset+h,c),{tag:r?s:"0x"+s.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:f,valueSize:c}},Rs=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*Math.pow(2,16)+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*Math.pow(2,32)+i.getUint32(1);case 6:return i.getUint16(0)*Math.pow(2,32)+i.getUint32(2);case 7:{const t=i.getUint8(0)*Math.pow(2,48)+i.getUint16(1)*Math.pow(2,32)+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ot=(i,e)=>{switch(e){case D.SignedInteger:return i.getInt8(0);case D.UnsignedInteger:return Rs(i);case D.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case D.String:return new TextDecoder("ascii").decode(i);case D.UTF8:return new TextDecoder("utf-8").decode(i);case D.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case D.Master:return i;case D.Binary:return i;default:x(e)}},Hi=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),r=gu(s);if(!e(r))return;r.type===D.Master&&Hi(r.value,e),t=r.value.byteOffset-i.byteOffset+r.valueSize}},Zg=i=>{if(i.getUint32(0)!==E.EBML)return!1;let e,t,s;const r=gu(i);return Hi(r.value,({tag:a,type:n,value:o})=>(a===E.EBMLReadVersion?e=ot(o,n):a===E.DocType?t=ot(o,n):a===E.DocTypeReadVersion&&(s=ot(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},bu=[E.Info,E.SeekHead,E.Tracks,E.Chapters,E.Cluster,E.Cues,E.Attachments,E.Tags],eb=[E.Timestamp,E.SilentTracks,E.SilentTrackNumber,E.Position,E.PrevSize,E.SimpleBlock,E.BlockGroup,E.EncryptedBlock],tb=i=>{let e,t,s,r,a=!1,n=!1,o=!1,u,d;return Hi(i,({tag:l,type:c,value:h,valueSize:f})=>{if(l===E.SeekID){const m=ot(h,c);d=Rs(m)}else l!==E.SeekPosition&&(d=void 0);return l===E.Segment?(e=h.byteOffset,t=h.byteOffset+f):l===E.Info?a=!0:l===E.SeekHead?n=!0:l===E.TimestampScale?s=ot(h,c):l===E.Duration?r=ot(h,c):l===E.SeekPosition&&d===E.Cues?u=ot(h,c):a&&n&&bu.includes(l)&&(o=!0),!o}),P(e,"Failed to parse webm Segment start"),P(t,"Failed to parse webm Segment end"),P(r,"Failed to parse webm Segment duration"),s=s!=null?s:1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(t/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(r/1e9*s*1e3),cuesSeekPosition:u}},ib=i=>{if(K(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},sb=(i,e)=>{let t=!1,s=!1;const r=o=>w(o.time)&&w(o.position),a=[];let n;return Hi(i,({tag:o,type:u,value:d})=>{switch(o){case E.Cues:t=!0;break;case E.CuePoint:n&&r(n)&&a.push(n),n={};break;case E.CueTime:n&&(n.time=ot(d,u));break;case E.CueTrackPositions:break;case E.CueClusterPosition:n&&(n.position=ot(d,u));break;default:t&&bu.includes(o)&&(s=!0)}return!(t&&s)}),n&&r(n)&&a.push(n),a.map((o,u)=>{const{time:d,position:l}=o,c=a[u+1];return{status:te.NONE,time:{from:d,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},rb=i=>{let e=0,t=!1;try{Hi(i,s=>s.tag===E.Cluster?s.tagSize<=i.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):eb.includes(s.tag)?(e+s.tagSize<=i.byteLength&&(e+=s.tagSize,t||(t=[E.SimpleBlock,E.BlockGroup,E.EncryptedBlock].includes(s.tag))),!0):!1)}catch(s){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},ab={validateData:Zg,parseInit:tb,getIndexRange:ib,parseSegments:sb,parseFeedableSegmentChunk:rb};class Eo{constructor(e,t,s,r,{fetcher:a,tuning:n,getCurrentPosition:o,compatibilityMode:u=!1}){switch(this.onLastSegment$=new y(!1),this.fullyBuffered$=new y(!1),this.playingRepresentation$=new y(void 0),this.error$=new O,this.gaps=[],this.subscription=new se,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new Dt,this.destroyAbortController=new Dt,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=qe(this.destroyAbortController.signal,function(d){return je(this,arguments,function*(){const l=this.representations.get(d);P(l,`Cannot find representation ${d}`),this.playingRepresentationId=d,this.downloadingRepresentationId=d,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${l.mime}; codecs="${l.codecs}"`),this.sourceBufferTaskQueue=new Wg(this.sourceBuffer),this.subscription.add(U(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},m=>this.error$.next({id:"SegmentEjection",category:C.WTF,message:"Error when trying to clear segments ejected by browser",thrown:m}))),this.subscription.add(U(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:C.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(m=>{if(!this.sourceBuffer)return;const p=Math.min(this.bufferLimit,yo(this.sourceBuffer.buffered)*.8);this.bufferLimit=p,this.pruneBuffer(this.getCurrentPosition(),m)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(m=>this.error$.next(m))),yield yield M(this.loadInit(l,"high",!0));const c=this.initData.get(l.id),h=this.segments.get(l.id);if(P(c,"No init buffer for starting representation"),P(h,"No segments for starting representation"),!(c instanceof ArrayBuffer))return yield M(void 0);let f=0;for(const m of h)m.time.from-f>0&&this.gaps.push({representation:l.id,from:f,to:m.time.from}),f=m.time.to;w(l.duration)&&l.duration-f>0&&this.gaps.push({representation:l.id,from:f,to:l.duration}),yield yield M(this.sourceBufferTaskQueue.append(c,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId)})}.bind(this)),this.switchTo=qe(this.destroyAbortController.signal,function(d){return je(this,arguments,function*(){if(d===this.downloadingRepresentationId||d===this.switchingToRepresentationId)return yield M(void 0);this.switchingToRepresentationId=d;const l=this.representations.get(d);P(l,`No such representation ${d}`);let c=this.initData.get(d);if(K(c)?yield yield M(this.loadInit(l,"high",!1)):c instanceof Promise&&(yield yield M(c)),c=this.initData.get(d),!c||!(c instanceof ArrayBuffer)||!this.sourceBuffer)return yield M(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=d,this.abort(),yield yield M(this.sourceBufferTaskQueue.append(c,this.downloadAbortController.signal));const h=this.getCurrentPosition();w(h)&&this.maintain(h)})}.bind(this)),this.fetcher=a,this.tuning=n,this.compatibilityMode=u,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.container=s,s){case si.MP4:this.containerParser=Xg;break;case si.WEBM:this.containerParser=ab;break;default:x(s)}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 Dt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(K(e)||K(this.downloadingRepresentationId)||K(this.playingRepresentationId)||K(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(P(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const r=s.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const l=It(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)&&yo(this.sourceBuffer.buffered)>=this.bufferLimit){const d=It(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(s,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{const l=at(o,0);l&&l.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===te.FED&&!o.length&&It(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const u=at(s,-1);u&&u.status===te.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===u))}findSegmentStartTime(e){var t,s,r;const a=(s=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&s!==void 0?s:this.playingRepresentationId;if(!a)return;const n=this.segments.get(a);if(!n)return;const o=n.find(u=>u.time.from<=e&&u.time.to>=e);return(r=o==null?void 0:o.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;this.initData.clear(),this.segments.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer&&(this.mediaSource.readyState==="open"&&this.abortBuffer(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,s){const r=e.findIndex(({status:c,time:{from:h,to:f}},m)=>{const p=h<=s&&f>=s,S=h>s||p||m===0&&s===0,g=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&h<=s+g||f<=s+g;return(c===te.NONE||c===te.PARTIALLY_EJECTED&&S&&T&&this.sourceBuffer&&!ca(this.sourceBuffer.buffered,s))&&S&&T});if(r===-1)return[];if(t!==Ue.BYTE_RANGE)return e.slice(r,r+1);const a=e;let n=0,o=0;const u=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=d||o<=l);c++){const h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status===te.NONE||h.status===te.PARTIALLY_EJECTED)u.push(h);else break}return u}loadSegments(e,t,s="auto"){return ue(this,void 0,void 0,function*(){if(!e.length)return;let r,a,n=e;const{type:o}=t.segmentReference;switch(o){case Ue.BYTE_RANGE:{r=t.segmentReference.url,a={from:at(e,0).byte.from,to:at(e,-1).byte.to};break}case Ue.TEMPLATE:{const d=at(e,0);r=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:x(o)}for(const d of n)d.status=te.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:u}=this.downloadAbortController;if(this.failedDownloads&&(yield qe(u,function(){return je(this,arguments,function*(){const d=Ja(this.failedDownloads,this.tuning.downloadBackoff);yield yield M(new Promise(l=>setTimeout(l,d)))})}.bind(this))(),u.aborted))for(const d of this.activeSegments)e.includes(d.segment)&&this.abortSegment(d.segment);return void this.fetcher.fetch(r,{range:a,onProgress:(d,l)=>{if(!u.aborted)try{this.onSomeDataLoaded(d,t.id,a?a.from:0,l,u)}catch(c){this.error$.next({id:"SegmentFeeding",category:C.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}},signal:u,priority:s}).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 s=!1;const r=this.getCurrentPosition();this.sourceBuffer&&w(r)&&(s=It((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,s||this.error$.next({id:"SegmentDownload",category:C.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,s,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=te.FED,"size"in c.segment&&(c.segment.size=c.fedBytes);for(const f of this.representations.values())if(f.id!==t)for(const m of(h=this.segments.get(f.id))!==null&&h!==void 0?h:[])m.status===te.FED&&m.time.from===c.segment.time.from&&m.time.to===c.segment.time.to&&(m.status=te.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===Ue.BYTE_RANGE,m=f?h.byte.to-h.byte.from+1:l;if(c.representationId!==t||!(!f||h.byte.from>=s&&h.byte.to<s+e.byteLength))continue;if(a.aborted){n();continue}const S=f?h.byte.from-s:0,g=f?h.byte.to-s:e.byteLength,T=S<r,I=g<=r;if(h.status===te.DOWNLOADING&&T&&I){h.status=te.DOWNLOADED,this.activeSegments.delete(c);const _=new DataView(e.buffer,e.byteOffset+S,m);this.sourceBufferTaskQueue.append(_,a).then(A=>A&&!a.aborted?o(c):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&T&&(c.loadedBytes=Math.min(m,r-S),c.loadedBytes>c.feedingBytes)){const _=new DataView(e.buffer,e.byteOffset+S+c.feedingBytes,c.loadedBytes-c.feedingBytes),A=c.loadedBytes===m?_:this.containerParser.parseFeedableSegmentChunk(_);A!=null&&A.byteLength&&(h.status=te.PARTIALLY_FED,c.feedingBytes+=A.byteLength,this.sourceBufferTaskQueue.append(A,a).then(N=>{if(a.aborted)n();else if(N)c.fedBytes+=A.byteLength,c.fedBytes===m&&o(c);else{if(c.feedingBytes<m)return;n()}}))}}}abortSegment(e){e.status===te.PARTIALLY_FED||e.status===te.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=te.NONE),e.status=te.PARTIALLY_EJECTED):e.status=te.NONE;for(const 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 s=this.representations.get(e);s&&(this.initLoadIdleCallback=bo(()=>Fs(this.loadInit(s,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",s=!1){return ue(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!s&&this.failedDownloads>0?qe(this.destroyAbortController.signal,function(){return je(this,arguments,function*(){const o=Ja(this.failedDownloads,this.tuning.downloadBackoff);yield yield M(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),s&&this.error$.next({id:"LoadInits",category:C.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}pruneBuffer(e,t,s=!1){return ue(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||K(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===te.FED&&u(l)}if(o=isFinite(a)&&isFinite(n),!o){r=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const l of d){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;l.status===te.FED&&u(l)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const l=this.sourceBuffer.buffered.start(d)*1e3,c=this.sourceBuffer.buffered.end(d)*1e3;for(const h of this.segments.values())for(const f of h)if(f.status===te.NONE&&Math.round(f.time.from)<=Math.round(l)&&Math.round(f.time.to)>=Math.round(c)){a=l,n=c;break}}if(o=isFinite(a)&&isFinite(n),!o&&s){r=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const l of this.segments.values())for(const c of l)c.time.from>e+d&&c.status===te.FED&&u(c)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}detectGaps(e,t){if(this.sourceBuffer)for(const s of t){let r={representation:e,from:s.time.from,to:s.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<=s.time.from||n>=s.time.to)){if(n<=s.time.from&&o>=s.time.to){r=void 0;break}o>s.time.from&&o<s.time.to&&(r.from=o),n<s.time.to&&n>s.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=bo(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:C.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(K(this.sourceBuffer)||K(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const r=Math.round(this.sourceBuffer.buffered.start(s)*1e3),a=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:r,to:a})}const t=1;for(const s of this.segments.values())for(const r of s){const{status:a}=r;if(a!==te.FED&&a!==te.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(l=>l.from-t<=n&&l.to+t>=o),d=e.filter(l=>n>=l.from-t&&n<=l.to+t||o>=l.from-t&&o<=l.to+t);u||(d.length===1?r.status=te.PARTIALLY_EJECTED:r.status=te.NONE)}}}var Kt;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(Kt||(Kt={}));class nb{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.lastConnectionType$=new y(void 0),this.lastConnectionReused$=new y(void 0),this.lastRequestFirstBytes$=new y(void 0),this.abortAllController=new Dt,this.subscription=new se,this.fetchManifest=qe(this.abortAllController.signal,function(r){return je(this,arguments,function*(){let a=r;this.requestQuic&&(a=ii(a));const n=yield yield M(ti(a,{signal:this.abortAllController.signal}).catch(Ti));return n?(this.onHeadersReceived(n.headers),yield M(n.text())):yield M(null)})}.bind(this)),this.fetch=qe(this.abortAllController.signal,function(r,{rangeMethod:a=this.compatibilityMode?Kt.HEADER:Kt.PARAM,range:n,onProgress:o,priority:u="auto",signal:d,measureThroughput:l=!0}={}){var c,h,f,m;return je(this,arguments,function*(){let p=r;const S=new Headers;if(n)switch(a){case Kt.HEADER:{S.append("Range",`bytes=${n.from}-${n.to}`);break}case Kt.PARAM:{const k=new URL(p,location.href);k.searchParams.append("bytes",`${n.from}-${n.to}`),p=k.toString();break}default:x(a)}this.requestQuic&&(p=ii(p));let g=this.abortAllController.signal;if(d){const k=new Dt;if(this.subscription.add(L(U(this.abortAllController.signal,"abort"),U(d,"abort")).subscribe(()=>{try{k.abort()}catch(G){Ti(G)}})),this.abortAllController.signal.aborted||d.aborted)try{k.abort()}catch(G){Ti(G)}g=k.signal}const T=pe(),I=yield yield M(ti(p,{priority:u,headers:S,signal:g}).catch(Ti)),_=pe();if((c=this.throughputEstimator)===null||c===void 0||c.addRawRtt(_-T),!I)return yield M(null);if(!I.ok||!I.body)return yield M(Promise.reject(new Error(`Fetch error ${I.status}: ${I.statusText}`)));this.onHeadersReceived(I.headers);const A=parseInt((h=I.headers.get("Content-Length"))!==null&&h!==void 0?h:"",10)||n&&n.to-n.from+1||NaN;if(!A){const k=yield yield M(I.arrayBuffer());return(f=this.throughputEstimator)===null||f===void 0||f.addRawSpeed(k.byteLength,pe()-_),o==null||o(new DataView(k),k.byteLength),yield M(k)}if(!o&&!l)return yield M(I.arrayBuffer());const[N,X]=I.body.tee(),Y=N.getReader();l&&((m=this.throughputEstimator)===null||m===void 0||m.trackStream(X));let F=0;const Z=new ArrayBuffer(A),V=new Uint8Array(Z),B=new DataView(Z);let ie=!1;const ce=k=>{ie=!0,Ti(k)},Se=qe(g,function({done:k,value:G}){return je(this,arguments,function*(){if(F===0&&this.lastRequestFirstBytes$.next(pe()-T),g.aborted)return yield M(void 0);k?o==null||o(B,F):G&&(V.set(G,F),F+=G.byteLength,o==null||o(B,F),yield yield M(Y==null?void 0:Y.read().then(Se,ce)))})}.bind(this));return yield yield M(Y==null?void 0:Y.read().then(Se,ce)),yield M(ie?null:Z)})}.bind(this)),this.fetchByteRangeRepresentation=qe(this.abortAllController.signal,function(r,a,n){var o;return je(this,arguments,function*(){if(r.type!==Ue.BYTE_RANGE)return yield M(null);const{from:u,to:d}=r.initRange;let l=u,c=d,h=!1,f,m;r.indexRange&&(f=r.indexRange.from,m=r.indexRange.to,h=d+1===f,h&&(l=Math.min(f,u),c=Math.max(m,d))),l=Math.min(l,0);const p=yield yield M(this.fetch(r.url,{range:{from:l,to:c},priority:n,measureThroughput:!1}));if(!p)return yield M(null);const S=new DataView(p,u-l,d-l+1);if(!a.validateData(S))throw new Error("Invalid media file");const g=a.parseInit(S),T=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(g);if(!T)throw new ReferenceError("No way to load representation index");let I;if(h)I=new DataView(p,T.from-l,T.to-T.from+1);else{const A=yield yield M(this.fetch(r.url,{range:T,priority:n,measureThroughput:!1}));if(!A)return yield M(null);I=new DataView(A)}const _=a.parseSegments(I,g,T);return yield M({dataView:new DataView(p),segments:_})})}.bind(this)),this.fetchTemplateRepresentation=qe(this.abortAllController.signal,function(r,a){return je(this,arguments,function*(){if(r.type!==Ue.TEMPLATE)return yield M(null);const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield yield M(this.fetch(n,{priority:a,measureThroughput:!1}));if(!o)return yield M(null);const u=r.segments.map(d=>Object.assign(Object.assign({},d),{status:te.NONE,size:void 0}));return yield M({segments:u,dataView:new DataView(o)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=fu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchRepresentation(e,t,s="auto"){var r,a;return ue(this,void 0,void 0,function*(){const{type:n}=e;switch(n){case Ue.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,s))!==null&&r!==void 0?r:null;case Ue.TEMPLATE:return(a=yield this.fetchTemplateRepresentation(e,s))!==null&&a!==void 0?a:null;default:x(n)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Ti=i=>{if(!(i instanceof DOMException)||!(i.name==="AbortError"||i.code===20))throw i};var ob=ct,db=Di,ub=ke,lb=ub("match"),cb=function(i){var e;return ob(i)&&((e=i[lb])!==void 0?!!e:db(i)=="RegExp")},hb=Ni,fb=String,pb=function(i){if(hb(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return fb(i)},vb=ft,mb=function(){var i=vb(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e},Sb=Le,gb=tt,bb=Ds,yb=mb,$o=RegExp.prototype,Tb=function(i){var e=i.flags;return e===void 0&&!("flags"in $o)&&!gb(i,"flags")&&bb($o,i)?Sb(yb,i):e},Fa=Ge,Eb=xs,$b=Math.floor,Pr=Fa("".charAt),Ab=Fa("".replace),Rr=Fa("".slice),_b=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,wb=/\$([$&'`]|\d{1,2})/g,kb=function(i,e,t,s,r,a){var n=t+i.length,o=s.length,u=wb;return r!==void 0&&(r=Eb(r),u=_b),Ab(a,u,function(d,l){var c;switch(Pr(l,0)){case"$":return"$";case"&":return i;case"`":return Rr(e,0,t);case"'":return Rr(e,n);case"<":c=r[Rr(l,1,-1)];break;default:var h=+l;if(h===0)return d;if(h>o){var f=$b(h/10);return f===0?d:f<=o?s[f-1]===void 0?Pr(l,1):s[f-1]+Pr(l,1):d}c=s[h-1]}return c===void 0?"":c})},Pb=We,Rb=Le,Va=Ge,Ao=fa,Ib=Te,Db=Ci,Cb=cb,jt=pb,Ob=Ls,Lb=Tb,xb=kb,Nb=ke,Bb=Nb("replace"),Mb=TypeError,yu=Va("".indexOf),Ub=Va("".replace),_o=Va("".slice),Fb=Math.max,wo=function(i,e,t){return t>i.length?-1:e===""?t:yu(i,e,t)};Pb({target:"String",proto:!0},{replaceAll:function(e,t){var s=Ao(this),r,a,n,o,u,d,l,c,h,f=0,m=0,p="";if(!Db(e)){if(r=Cb(e),r&&(a=jt(Ao(Lb(e))),!~yu(a,"g")))throw Mb("`.replaceAll` does not allow non-global regexes");if(n=Ob(e,Bb),n)return Rb(n,e,s,t);if(r)return Ub(jt(s),e,t)}for(o=jt(s),u=jt(e),d=Ib(t),d||(t=jt(t)),l=u.length,c=Fb(1,l),f=wo(o,u,0);f!==-1;)h=d?jt(t(u,f,o)):xb(u,o,f,[],void 0,t),p+=_o(o,m,f)+h,m=f+l,f=wo(o,u,f+c);return m<o.length&&(p+=_o(o,m)),p}});var Vb=Na,Hb=Vb("String","replaceAll"),Gb=Hb,Yb=Gb,qb=Yb,jb=qb,ko=jb;const Po=i=>{if(!i.startsWith("P"))return;const e=(n,o)=>{const u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},s=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),r=(s==null?void 0:s[1])==="-"?-1:1,a={days:e(s==null?void 0:s[5],r),hours:e(s==null?void 0:s[6],r),minutes:e(s==null?void 0:s[7],r),seconds:e(s==null?void 0:s[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},Ir=(i,e)=>{let t=i;t=ko(t,"$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,a]of Object.entries(s)){const n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=ko(t,n,(o,u)=>K(a)?o:K(u)?a:a.padStart(parseInt(u,10),"0"))}return t},zb=(i,e)=>{var t,s,r,a,n,o,u,d,l,c,h,f,m,p,S,g,T,I,_,A,N,X,Y,F,Z,V,B,ie,ce,Se,k,G,oe,ve,ge,Ie,Qe;const ee=new DOMParser().parseFromString(i,"application/xml"),Ee={video:[],audio:[],text:[]},Pe=ee.children[0],xe=Pe.getElementsByTagName("Period")[0],At=xe.children;let Je;const gt=Pe.getAttribute("mediaPresentationDuration"),_t=xe.getAttribute("duration");if(gt)Je=Po(gt);else if(_t){const Ke=Po(_t);w(Ke)&&(Je=Ke)}let di=0;const Ft=(s=(t=Pe.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&s!==void 0?s:[],wu=Ft.includes(Ps.WEBM_AS_IN_FFMPEG)||Ft.includes(Ps.WEBM_AS_IN_SPEC)?si.WEBM:si.MP4;for(const Ke of At){const Gi=Ke.getAttribute("mimeType"),ku=Ke.getAttribute("codecs"),Ha=(r=Ke.getAttribute("contentType"))!==null&&r!==void 0?r:Gi==null?void 0:Gi.split("/")[0],Pu=(n=(a=Ke.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],Ru=Ke.querySelectorAll("Representation"),Iu=Ke.querySelector("SegmentTemplate");if(Ha!=="text")for(const $e of Ru){const ui=(o=$e.getAttribute("mimeType"))!==null&&o!==void 0?o:Gi,Ga=(d=(u=$e.getAttribute("codecs"))!==null&&u!==void 0?u:ku)!==null&&d!==void 0?d:"",Yi=(c=(l=$e.getAttribute("contentType"))!==null&&l!==void 0?l:ui==null?void 0:ui.split("/")[0])!==null&&c!==void 0?c:Ha,Du=(f=(h=Ke.getAttribute("profiles"))===null||h===void 0?void 0:h.split(","))!==null&&f!==void 0?f:[],Cu=parseInt((m=$e.getAttribute("width"))!==null&&m!==void 0?m:"",10),Ya=parseInt((p=$e.getAttribute("height"))!==null&&p!==void 0?p:"",10),qa=parseInt((S=$e.getAttribute("bandwidth"))!==null&&S!==void 0?S:"",10)/1e3,ja=(g=$e.getAttribute("frameRate"))!==null&&g!==void 0?g:"",Ou=(T=$e.getAttribute("quality"))!==null&&T!==void 0?T:void 0,Lu=ja?Ma(ja):void 0,xu=(I=$e.getAttribute("id"))!==null&&I!==void 0?I:(di++).toString(10),Nu=Yi==="video"?`${Ya}p`:Yi==="audio"?`${qa}Kbps`:Ga,Bu=`${xu}@${Nu}`,Mu=(N=(A=(_=$e.querySelector("BaseURL"))===null||_===void 0?void 0:_.textContent)===null||A===void 0?void 0:A.trim())!==null&&N!==void 0?N:"",za=new URL(Mu,e).toString(),Uu=[...Ft,...Pu,...Du];let Gs;const Fu=$e.querySelector("SegmentBase"),wt=(X=$e.querySelector("SegmentTemplate"))!==null&&X!==void 0?X:Iu;if(Fu){const li=(F=(Y=$e.querySelector("SegmentBase Initialization"))===null||Y===void 0?void 0:Y.getAttribute("range"))!==null&&F!==void 0?F:"",[ci,qs]=li.split("-").map(kt=>parseInt(kt,10)),hi={from:ci,to:qs},fi=(Z=$e.querySelector("SegmentBase"))===null||Z===void 0?void 0:Z.getAttribute("indexRange"),[js,qi]=fi?fi.split("-").map(kt=>parseInt(kt,10)):[],pi=fi?{from:js,to:qi}:void 0;Gs={type:Ue.BYTE_RANGE,url:za,initRange:hi,indexRange:pi}}else if(wt){const li={representationId:(V=$e.getAttribute("id"))!==null&&V!==void 0?V:void 0,bandwidth:(B=$e.getAttribute("bandwidth"))!==null&&B!==void 0?B:void 0},ci=parseInt((ie=wt.getAttribute("timescale"))!==null&&ie!==void 0?ie:"",10),qs=(ce=wt.getAttribute("initialization"))!==null&&ce!==void 0?ce:"",hi=wt.getAttribute("media"),fi=(k=parseInt((Se=wt.getAttribute("startNumber"))!==null&&Se!==void 0?Se:"",10))!==null&&k!==void 0?k:1,js=Ir(qs,li);if(!hi)throw new ReferenceError("No media attribute in SegmentTemplate");const qi=(G=wt.querySelectorAll("SegmentTimeline S"))!==null&&G!==void 0?G:[],pi=[];if(qi.length){let kt=fi,Pt=0;for(const vi of qi){const Vt=parseInt((oe=vi.getAttribute("d"))!==null&&oe!==void 0?oe:"",10)*1e3,mi=parseInt((ve=vi.getAttribute("r"))!==null&&ve!==void 0?ve:"",10)||0,Si=(Ie=parseInt((ge=vi.getAttribute("t"))!==null&&ge!==void 0?ge:"",10))!==null&&Ie!==void 0?Ie:void 0;for(let Wa=0;Wa<mi+1;Wa++){const Vu=Ir(hi,Object.assign(Object.assign({},li),{segmentNumber:kt.toString(10),segmentTime:Si.toString(10)})),Hu=Si?Si/ci:Pt;Pt+=Vt/ci;const Gu=Pt;kt++,pi.push({time:{from:Hu,to:Gu},url:Vu})}}}else if(w(Je)){const Pt=parseInt((Qe=wt.getAttribute("duration"))!==null&&Qe!==void 0?Qe:"",10)/ci*1e3,vi=Math.ceil(Je/Pt);let Vt=0;for(let mi=1;mi<vi;mi++){const Si=Ir(hi,Object.assign(Object.assign({},li),{segmentNumber:mi.toString(10),segmentTime:Vt.toString(10)}));pi.push({time:{from:Vt,to:Vt+Pt},url:Si}),Vt+=Pt}}Gs={type:Ue.TEMPLATE,baseUrl:za,initUrl:js,segments:pi}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Yi||!ui)continue;const Ys={video:Me.VIDEO,audio:Me.AUDIO,text:Me.TEXT}[Yi];Ys&&Ee[Ys].push({id:Bu,kind:Ys,segmentReference:Gs,profiles:Uu,duration:Je,bitrate:qa,mime:ui,codecs:Ga,width:Cu,height:Ya,fps:Lu,quality:Ou})}}return{duration:Je,container:wu,representations:Ee}},Wb=["timeupdate","progress","play","seeked","stalled","waiting"];var Be;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(Be||(Be={}));let Qb=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new se,this.state$=new le(Be.NONE),this.currentVideoRepresentation$=new y(void 0),this.error$=new O,this.lastConnectionType$=new y(void 0),this.lastConnectionReused$=new y(void 0),this.lastRequestFirstBytes$=new y(void 0),this.forceEnded$=new O,this.gapWatchdogStarted=!1,this.destroyController=new Dt,this.initManifest=qe(this.destroyController.signal,function(t,s){return je(this,arguments,function*(){this.element=t,this.state$.startTransitionTo(Be.MANIFEST_READY);const r=yield yield M(this.fetcher.fetchManifest(s).catch(o=>this.error$.next({id:"LoadManifest",category:C.NETWORK,message:"Failed to load manifest",thrown:o})));if(!r)return yield M(void 0);let a;try{a=zb(r!=null?r:"",s)}catch(o){this.error$.next({id:"ManifestParsing",category:C.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!a)return yield M(void 0);const n=({mime:o,codecs:u})=>{var d,l,c;return Boolean(((d=t.canPlayType)===null||d===void 0?void 0:d.call(t,o))&&((c=(l=window.MediaSource)===null||l===void 0?void 0:l.isTypeSupported)===null||c===void 0?void 0:c.call(l,`${o}; codecs="${u}"`)))};this.manifest=Object.assign(Object.assign({},a),{representations:Bi(Object.entries(a.representations).map(([o,u])=>[o,u.filter(n)]))}),this.manifest.representations.video.length?this.state$.setState(Be.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:C.PARSER,message:"No playable video representations"})})}.bind(this)),this.initRepresentations=qe(this.destroyController.signal,function(t,s){return je(this,arguments,function*(){P(this.manifest),P(this.element),this.state$.startTransitionTo(Be.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 Eo(Me.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],w(s)&&(this.audioBufferManager=new Eo(Me.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,r),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));const a=L(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe($(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=L(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe($(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.subscription.add(L(this.forceEnded$,dt({allBuffersFull:a,someBufferEnded:n}).pipe(j(({allBuffersFull:o,someBufferEnded:u})=>o&&u))).subscribe(()=>{var o;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(u=>!u.updating))try{(o=this.source)===null||o===void 0||o.endOfStream()}catch(u){this.error$.next({id:"EndOfStream",category:C.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:u})}})),this.subscription.add(L(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.source.readyState!=="open"&&(yield yield M(new Promise(o=>{var u;return(u=this.source)===null||u===void 0?void 0:u.addEventListener("sourceopen",o)}))),w(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&w(s)?yield yield M(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)])):yield yield M(this.videoBufferManager.startWith(t)),this.state$.setState(Be.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,s;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||!((s=this.audioBufferManager)===null||s===void 0)&&s.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=qu(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),a=>{this.error$.next({id:"GapWatchdog",category:C.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new nb({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initBuffer(){P(this.element),this.state$.setState(Be.RUNNING),this.subscription.add(L(...Wb.map(e=>U(this.element,e)),U(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:C.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(U(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(U(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&ca(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}switchRepresentation(e,t){return ue(this,void 0,void 0,function*(){const s={[Me.VIDEO]:this.videoBufferManager,[Me.AUDIO]:this.audioBufferManager,[Me.TEXT]:null}[e];return s==null?void 0:s.switchTo(t)})}seek(e,t){var s,r,a,n,o;P(this.element),P(this.videoBufferManager);let u;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?u=e:u=Math.max((s=this.videoBufferManager.findSegmentStartTime(e))!==null&&s!==void 0?s:e,(a=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&a!==void 0?a:e),ca(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(Be.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 s of this.bufferManagers)for(const r of s.gaps)s.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 s=Math.max(...t);s===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=s/1e3}}};var he;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(he||(he={}));const Jb=({id:i,width:e,height:t,bitrate:s,fps:r,quality:a})=>{var n;const o=(n=a?Vi(a):void 0)!==null&&n!==void 0?n:Mt({width:e,height:t});return o&&{id:i,quality:o,bitrate:s,size:{width:e,height:t},fps:r}},Kb=({id:i,bitrate:e})=>({id:i,bitrate:e}),Xb=(i,e,t)=>{var s;const r=e.indexOf(t);return(s=at(i,Math.round(i.length*r/e.length)))!==null&&s!==void 0?s:at(i,-1)};class Zb{constructor(e){this.subscription=new se,this.videoState=new le(he.STOPPED),this.elementSize$=new y(void 0),this.textTracksManager=new it,this.videoTracks=[],this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Eg,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state===H.Requested&&(r==null?void 0:r.to)!==v.PAUSED&&t!==he.STOPPED&&s!==v.STOPPED&&this.seek(a.position,a.forcePrecise),s===v.STOPPED){t!==he.STOPPED&&(this.videoState.startTransitionTo(he.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(he.STOPPED),R(this.params.desiredState.playbackState,v.STOPPED,!0));return}switch(t){case he.STOPPED:this.videoState.startTransitionTo(he.READY),this.prepare();return;case he.READY:s===v.PAUSED?(this.videoState.setState(he.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED)):s===v.PLAYING?(this.videoState.startTransitionTo(he.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===v.READY&&R(this.params.desiredState.playbackState,v.READY);return;case he.PLAYING:s===v.PAUSED?(this.videoState.startTransitionTo(he.PAUSED),this.video.pause()):(r==null?void 0:r.to)===v.PLAYING&&R(this.params.desiredState.playbackState,v.PLAYING);return;case he.PAUSED:s===v.PLAYING?(this.videoState.startTransitionTo(he.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===v.PAUSED&&R(this.params.desiredState.playbackState,v.PAUSED);return;default:return x(t)}}},this.params=e,this.video=vt(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Re(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Qb({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=mt(this.video),r=d=>{e.error$.next({id:"DashVKProvider",category:C.WTF,message:"DashVKProvider internal logic error",thrown:d})},a=(d,l)=>this.subscription.add(d.subscribe(l,r));a(s.timeUpdate$,e.position$),a(s.durationChange$,e.duration$),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.playing$,e.firstFrameEvent$),a(s.canplay$,e.canplay$),a(s.isAudioAvailable$,e.isAudioAvailable$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.lastRequestFirstBytes$.pipe(j(w),ye(),Ot(void 0)),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Ut(this.video,t.isLooped,r)),this.subscription.add(pt(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Et(this.video,t.playbackRate,s.playbackRateState$,r)),a(ws(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(he.PLAYING),R(t.playbackState,v.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(he.PAUSED),R(t.playbackState,v.PAUSED)},r)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===he.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d===Be.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[];const c=this.player.getRepresentations();P(c,"Manifest not loaded or empty");const h=Array.from(c.audio).sort((p,S)=>S.bitrate-p.bitrate),f=Array.from(c.video).sort((p,S)=>S.bitrate-p.bitrate);if(!this.params.tuning.isAudioDisabled)for(const p of h){const S=Kb(p);S&&this.audioTracks.push({track:S,representation:p})}for(const p of f){const S=Jb(p);if(S){this.videoTracks.push({track:S,representation:p});const g=!this.params.tuning.isAudioDisabled&&Xb(h,f,p);g&&this.audioRepresentations.set(p.id,g)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:p})=>p)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:p})=>p)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length);const m=this.selectVideoRepresentation();P(m),this.player.initRepresentations(m.id,(l=this.audioRepresentations.get(m.id))===null||l===void 0?void 0:l.id)}else d===Be.REPRESENTATIOS_READY&&(this.videoState.setState(he.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:C.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(L(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,U(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!==Be.RUNNING||l||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation();if(c){this.player.switchRepresentation(Me.VIDEO,c.id).catch(n);const h=this.audioRepresentations.get(c.id);h&&this.player.switchRepresentation(Me.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===v.READY),me());this.subscription.add(L(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===v.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(L(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===v.READY)));const u=L(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ve(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,s,r,a,n;const o=this.params.desiredState.autoVideoTrackSwitching.getState(),u=this.params.desiredState.videoTrack.getState(),d=(e=this.videoTracks.find(({track:{id:g}})=>g===u))===null||e===void 0?void 0:e.track,l=this.params.output.currentVideoTrack$.getValue(),c=It(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),m=Math.max(d&&!o&&(s=(t=this.audioRepresentations.get(d.id))===null||t===void 0?void 0:t.bitrate)!==null&&s!==void 0?s:0,l&&(a=(r=this.audioRepresentations.get(l.id))===null||r===void 0?void 0:r.bitrate)!==null&&a!==void 0?a:0),p=Fi(this.videoTracks.map(({track:g})=>g),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:m,forwardBufferHealth:f,current:l,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),S=o?p!=null?p:d:d!=null?d:p;return S&&((n=this.videoTracks.find(({track:g})=>g===S))===null||n===void 0?void 0:n.representation)}prepare(){return ue(this,void 0,void 0,function*(){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),St(this.video)}playIfAllowed(){$t(this.video).then(e=>{e||(this.videoState.setState(he.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED,!0))})}}const ey=5e3,st={};var J;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(J||(J={}));const ds=(i,e)=>new Ii(t=>{const s=(r,a)=>t.next(a);return i.on(e,s),()=>i.off(e,s)});class ty{constructor(e){this.subscription=new se,this.videoState=new le(J.INITIALIZING),this.textTracksManager=new it,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(t!==J.INITIALIZING)switch((r==null?void 0:r.to)!==v.PAUSED&&a.state===H.Requested&&this.seek(a.position),s){case v.STOPPED:switch(t){case J.STOPPED:break;case J.READY:case J.PLAYING:case J.PAUSED:this.stop();break;default:x(t)}break;case v.READY:switch(t){case J.STOPPED:this.prepare();break;case J.READY:case J.PLAYING:case J.PAUSED:break;default:x(t)}break;case v.PLAYING:switch(t){case J.PLAYING:break;case J.STOPPED:this.prepare();break;case J.READY:case J.PAUSED:this.playIfAllowed();break;default:x(t)}break;case v.PAUSED:switch(t){case J.PAUSED:break;case J.STOPPED:this.prepare();break;case J.READY:this.videoState.setState(J.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED);break;case J.PLAYING:this.pause();break;default:x(t)}break;default:x(s)}},this.video=vt(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(Re(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),St(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:C.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),ey);Fs(import("hls.js").then(r=>{e||(st.Hls=r.default,st.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(s),e=!0})}init(){P(st.Hls,"hls.js not loaded"),this.hls=new st.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(J.STOPPED)}subscribe(){P(st.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=d=>{t.error$.next({id:"HlsJsProvider",category:C.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=mt(this.video),a=(d,l)=>this.subscription.add(d.subscribe(l,s));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.isAudioAvailable$,t.isAudioAvailable$),this.subscription.add(Ut(this.video,e.isLooped,s)),this.subscription.add(pt(this.video,e.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Et(this.video,e.playbackRate,r.playbackRateState$,s)),this.subscription.add(ds(this.hls,st.Events.ERROR).subscribe(d=>{var l;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:C.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(J.PLAYING),R(e.playbackState,v.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED),R(e.playbackState,v.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())===null||d===void 0?void 0:d.to)===J.READY&&this.videoState.setState(J.READY),this.videoState.getState()===J.PLAYING&&this.playIfAllowed()},s)),a(ds(this.hls,st.Events.MANIFEST_PARSED).pipe($(({levels:d})=>d.reduce((l,c)=>{var h,f;const m=c.name||c.height.toString(10),{width:p,height:S}=c,g=(f=Vi((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:Mt({width:p,height:S});if(!g)return l;const T=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,I={id:m.toString(),quality:g,bitrate:c.bitrate/1e3,size:{width:p,height:S},fps:T};return this.trackLevels.set(m,{track:I,level:c}),l.push(I),l},[]))),t.availableVideoTracks$),a(ds(this.hls,st.Events.LEVEL_LOADING).pipe($(({url:d})=>Re(d))),t.hostname$),this.subscription.add(et(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:s}));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=ds(this.hls,st.Events.LEVEL_SWITCHED).pipe($(({level:d})=>n(this.hls.levels[d])));o.pipe(j(w)).subscribe(t.currentVideoTrack$,s),this.subscription.add(et(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(K(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,m=this.hls.levels[f];!m||c.bitrate>m.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o.pipe($(d=>d==null?void 0:d.id)),onError:s})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const u=L(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ve(0));this.subscription.add(u.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(J.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return ue(this,void 0,void 0,function*(){this.videoState.startTransitionTo(J.PLAYING),(yield $t(this.video))||(this.videoState.setState(J.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(J.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(J.STOPPED),R(this.params.desiredState.playbackState,v.STOPPED,!0)}}const Ro="X-Playback-Duration";var Io=i=>ue(void 0,void 0,void 0,function*(){const e=yield ti(i,{method:"HEAD"});return e.headers.has(Ro)?parseInt(e.headers.get(Ro),10):void 0});const iy=i=>{let e=null;if(i.QUALITY&&(e=Vi(i.QUALITY)),!e&&i.RESOLUTION){const[t,s]=i.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Mt({width:t,height:s})}return e!=null?e:null},Tu=(i,e=i)=>ue(void 0,void 0,void 0,function*(){var t;const a=(yield(yield ti(i)).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=Bi(d[1].split(",").map(g=>g.split("="))),c=(t=l.QUALITY)!==null&&t!==void 0?t:`stream-${l.BANDWIDTH}`,h=iy(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 m=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0;let p;if(l.RESOLUTION){const[g,T]=l.RESOLUTION.split("x").map(I=>parseInt(I,10));g&&T&&(p={width:g,height:T})}const S=new URL(a[++o],e).toString();h&&n.push({id:c,quality:h,url:S,bandwidth:f,size:p,fps:m})}return n});var re;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(re||(re={}));class sy{constructor(e){var t;this.subscription=new se,this.videoState=new le(re.STOPPED),this.textTracksManager=new it,this.manifests$=new y([]),this.liveOffset=new Ba,this.manifestStartTime$=new y(void 0),this.syncPlayback=()=>{const r=this.videoState.getState(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a===v.STOPPED){r!==re.STOPPED&&(this.videoState.startTransitionTo(re.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(re.STOPPED),R(this.params.desiredState.playbackState,v.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(r===re.STOPPED){this.videoState.startTransitionTo(re.READY),this.prepare();return}if(o||u){const c=this.videoState.getState();this.videoState.setState(re.CHANGING_MANIFEST),this.videoState.startTransitionTo(c),this.prepare(),l.state===H.None&&this.params.desiredState.seekState.setState({state:H.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==v.PAUSED&&l.state===H.Requested){this.videoState.startTransitionTo(re.READY),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case re.READY:a===v.READY?R(this.params.desiredState.playbackState,v.READY):a===v.PAUSED?(this.videoState.setState(re.PAUSED),this.liveOffset.pause(),R(this.params.desiredState.playbackState,v.PAUSED)):a===v.PLAYING&&(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed());return;case re.PLAYING:a===v.PAUSED?(this.videoState.startTransitionTo(re.PAUSED),this.liveOffset.pause(),this.video.pause()):(n==null?void 0:n.to)===v.PLAYING&&R(this.params.desiredState.playbackState,v.PLAYING);return;case re.PAUSED:a===v.PLAYING?(this.videoState.startTransitionTo(re.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)===v.PAUSED&&(R(this.params.desiredState.playbackState,v.PAUSED),this.liveOffset.pause());return;case re.CHANGING_MANIFEST:break;default:return x(r)}},this.params=e,this.video=vt(e.container),this.params.output.element$.next(this.video);const s={id:"master",quality:ne.INVARIANT,url:this.params.source.url};this.manifests$.next([s]),Tu(ei(this.params.source.url),this.params.source.url).then(r=>{this.manifests$.next([s,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:C.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(Re(this.params.source.url)),this.maxSeekBackTime$=new y((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:s,videoTrack:r}=this.params.desiredState,a=s.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,s=o=>{e.error$.next({id:"HlsLiveProvider",category:C.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=mt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,s));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(pt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Et(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(re.PLAYING),R(t.playbackState,v.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(re.PAUSED),R(t.playbackState,v.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===re.READY&&this.videoState.setState(re.READY),this.videoState.getState()===re.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.maxSeekBackTime$.pipe(me(),$(o=>-o/1e3)).subscribe(this.params.output.duration$,s)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&w(d.to)){const c=d.to;this.params.desiredState.videoTrack.setState(c);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Re(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===re.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===H.Requested&&this.seek(o.position)},s)),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)},s)),this.subscription.add(dt({startTime:this.manifestStartTime$.pipe(j(w)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),s)),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$,s));const n=L(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,Oe(["init"])).pipe(Ve(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),St(this.video)}prepare(){const e=this.selectManifest();if(K(e))return;const t=ei(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),Io(t).then(s=>{var r;if(!K(s))this.maxSeekBackTime$.next(s);else{const a=(r=this.params.source.maxSeekBackTime)!==null&&r!==void 0?r:this.maxSeekBackTime$.getValue();if(K(a)||!isFinite(a))try{ti(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();Io(d).then(l=>{K(l)||this.maxSeekBackTime$.next(l)})}})}catch(n){}}})}playIfAllowed(){$t(this.video).then(e=>{e||(this.videoState.setState(re.PAUSED),this.liveOffset.pause(),R(this.params.desiredState.playbackState,v.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next();const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3),this.params.output.seekedEvent$.next()}}var de;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(de||(de={}));class ry{constructor(e){this.subscription=new se,this.videoState=new le(de.STOPPED),this.textTracksManager=new it,this.manifests$=new y([]),this.syncPlayback=()=>{const s=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===v.STOPPED){s!==de.STOPPED&&(this.videoState.startTransitionTo(de.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(de.STOPPED),R(this.params.desiredState.playbackState,v.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.seekState.getState();if(s===de.STOPPED){this.videoState.startTransitionTo(de.READY),this.prepare();return}if(n||o){const l=this.videoState.getState();this.videoState.setState(de.CHANGING_MANIFEST),this.videoState.startTransitionTo(l);const{currentTime:c}=this.video;this.prepare(),d.state===H.None&&this.params.desiredState.seekState.setState({state:H.Requested,position:c*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==v.PAUSED&&d.state===H.Requested&&this.seek(d.position),s){case de.READY:r===v.READY?R(this.params.desiredState.playbackState,v.READY):r===v.PAUSED?(this.videoState.setState(de.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED)):r===v.PLAYING&&(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed());return;case de.PLAYING:r===v.PAUSED?(this.videoState.startTransitionTo(de.PAUSED),this.video.pause()):(a==null?void 0:a.to)===v.PLAYING&&R(this.params.desiredState.playbackState,v.PLAYING);return;case de.PAUSED:r===v.PLAYING?(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===v.PAUSED&&R(this.params.desiredState.playbackState,v.PAUSED);return;case de.CHANGING_MANIFEST:break;default:return x(s)}},this.params=e,this.video=vt(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:ne.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(Re(this.params.source.url)),Tu(this.params.source.url).then(s=>{this.manifests$.next([t,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:C.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:s,videoTrack:r}=this.params.desiredState,a=s.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,s=o=>{e.error$.next({id:"HlsProvider",category:C.WTF,message:"HlsProvider internal logic error",thrown:o})},r=mt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(Ut(this.video,t.isLooped,s)),this.subscription.add(pt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Et(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(de.PLAYING),R(t.playbackState,v.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED),R(t.playbackState,v.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===de.READY&&this.videoState.setState(de.READY),this.videoState.getState()===de.PLAYING&&this.playIfAllowed()},s).add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&w(d.to)){const c=d.to;this.params.desiredState.videoTrack.setState(c);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Re(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===de.CHANGING_MANIFEST&&this.videoState.setState(u.to),o.state===H.Requested&&this.seek(o.position)},s))),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$,s));const n=L(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ve(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),St(this.video)}prepare(){const e=this.selectManifest();K(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){$t(this.video).then(e=>{e||(this.videoState.setState(de.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var fe;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(fe||(fe={}));class ay{constructor(e){this.subscription=new se,this.videoState=new le(fe.STOPPED),this.trackUrls={},this.textTracksManager=new it,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(s===v.STOPPED){t!==fe.STOPPED&&(this.videoState.startTransitionTo(fe.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(fe.STOPPED),R(this.params.desiredState.playbackState,v.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(t===fe.STOPPED){this.videoState.startTransitionTo(fe.READY),this.prepare();return}if(n){const{currentTime:u}=this.video;this.prepare(),o.state===H.None&&this.params.desiredState.seekState.setState({state:H.Requested,position:u*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!==v.PAUSED&&o.state===H.Requested&&this.seek(o.position),t){case fe.READY:s===v.READY?R(this.params.desiredState.playbackState,v.READY):s===v.PAUSED?(this.videoState.setState(fe.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED)):s===v.PLAYING&&(this.videoState.startTransitionTo(fe.PLAYING),this.playIfAllowed());return;case fe.PLAYING:s===v.PAUSED?(this.videoState.startTransitionTo(fe.PAUSED),this.video.pause()):(r==null?void 0:r.to)===v.PLAYING&&R(this.params.desiredState.playbackState,v.PLAYING);return;case fe.PAUSED:s===v.PLAYING?(this.videoState.startTransitionTo(fe.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===v.PAUSED&&R(this.params.desiredState.playbackState,v.PAUSED);return;default:return x(t)}},this.params=e,this.video=vt(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach(([t,s],r)=>{const a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:s}}),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,s=o=>{e.error$.next({id:"MpegProvider",category:C.WTF,message:"MpegProvider internal logic error",thrown:o})},r=mt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,s));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(Ut(this.video,t.isLooped,s)),this.subscription.add(pt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Et(this.video,t.playbackRate,r.playbackRateState$,s)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(fe.PLAYING),R(t.playbackState,v.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(fe.PAUSED),R(t.playbackState,v.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===fe.READY&&this.videoState.setState(fe.READY);const u=this.params.desiredState.videoTrack.getTransition();u&&w(u.to)&&(this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to].track)),this.videoState.getState()===fe.PLAYING&&this.playIfAllowed()},s)),this.textTracksManager.connect(this.video,t,e);const n=L(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ve(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),St(this.video)}prepare(){var e,t;const s=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState();P(s,"MpegProvider: track is not selected");let{url:r}=this.trackUrls[s];P(r,`MpegProvider: No url for ${s}`),this.params.tuning.requestQuick&&(r=ii(r)),this.video.setAttribute("src",r),this.video.load(),this.params.output.hostname$.next(Re(r))}playIfAllowed(){$t(this.video).then(e=>{e||(this.videoState.setState(fe.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}const Do=["stun:videostun.mycdn.me:80"],ny=1e3,oy=3,Dr=()=>null;class dy{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=Dr,this.externalStopCallback=Dr,this.externalErrorCallback=Dr,this.options=this.normalizeOptions(t);const s=e.split("/");this.serverUrl=s.slice(0,s.length-1).join("/"),this.streamKey=s[s.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return ue(this,void 0,void 0,function*(){try{const t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return ue(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:Do}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return ue(this,void 0,void 0,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return ue(this,void 0,void 0,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:C.WTF,message:e.message})}onPeerConnectionStream(e){return ue(this,void 0,void 0,function*(){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return ue(this,void 0,void 0,function*(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=yield this.peerConnection.createOffer(e),s=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(s))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),ny)}normalizeOptions(e={}){const t={stunServerList:Do,maxRetryNumber:oy,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var ae;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(ae||(ae={}));class uy{constructor(e){this.videoState=new le(ae.STOPPED),this.maxSeekBackTime$=new y(0),this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(s===v.STOPPED){t!==ae.STOPPED&&(this.videoState.startTransitionTo(ae.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(ae.STOPPED),R(this.params.desiredState.playbackState,v.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===ae.STOPPED){this.videoState.startTransitionTo(ae.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case ae.READY:s===v.PAUSED?(this.videoState.setState(ae.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED)):s===v.PLAYING&&(this.videoState.startTransitionTo(ae.PLAYING),this.playIfAllowed());return;case ae.PLAYING:s===v.PAUSED?(this.videoState.startTransitionTo(ae.PAUSED),this.video.pause()):(r==null?void 0:r.to)===v.PLAYING&&R(this.params.desiredState.playbackState,v.PLAYING);return;case ae.PAUSED:s===v.PLAYING?(this.videoState.startTransitionTo(ae.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===v.PAUSED&&R(this.params.desiredState.playbackState,v.PAUSED);return;default:return x(t)}},this.subscription=new se,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=vt(e.container),this.liveStreamClient=new dy(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),St(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,s=n=>{e.error$.next({id:"WebRTCLiveProvider",category:C.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};L(this.videoState.stateChangeStarted$.pipe($(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe($(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const r=mt(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,s));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)===ae.READY&&this.videoState.setState(ae.READY)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(ae.PAUSED)},s)).add(r.playing$.subscribe(()=>{this.videoState.setState(ae.PLAYING)},s)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(pt(this.video,t.volume,r.volumeState$,s)).add(r.volumeState$.subscribe(e.volume$,s)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case ae.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(v.STOPPED);break;case ae.READY:break;case ae.PAUSED:t.playbackState.setState(v.PAUSED);break;case ae.PLAYING:t.playbackState.setState(v.PLAYING);break;default:return x(n.to)}},s)).add(L(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ve(0)).subscribe(this.syncPlayback.bind(this),s)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),s))}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(Re(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:ne.INVARIANT}),this.video.srcObject=e,R(this.params.desiredState.playbackState,v.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(ae.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:C.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){$t(this.video).then(e=>{e||(this.videoState.setState(ae.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED,!0))})}prepare(){this.liveStreamClient.connect()}}class Co{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 ly=()=>{var i,e;const t=window.navigator;return t.userAgentData?((e=(i=t.userAgentData)===null||i===void 0?void 0:i.platform)===null||e===void 0?void 0:e.toLowerCase())==="android":window.navigator.userAgent.toLowerCase().includes("android")},Cr,Or,Lr,xr,Nr,Br,us,Mr,ls,Ur,cs,Fr,hs,Vr,fs,Hr;const Eu=ly(),bt=document.createElement("video"),rt={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&((Or=(Cr=window.SourceBuffer)===null||Cr===void 0?void 0:Cr.prototype)===null||Or===void 0?void 0:Or.appendBuffer)),hls:Boolean(((Lr=bt.canPlayType)===null||Lr===void 0?void 0:Lr.call(bt,"application/x-mpegurl"))||((xr=bt.canPlayType)===null||xr===void 0?void 0:xr.call(bt,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection)},Ne={mp4:Boolean((Nr=bt.canPlayType)===null||Nr===void 0?void 0:Nr.call(bt,"video/mp4")),webm:Boolean((Br=bt.canPlayType)===null||Br===void 0?void 0:Br.call(bt,"video/webm")),cmaf:!0},yt={h264:Boolean((Mr=(us=window.MediaSource)===null||us===void 0?void 0:us.isTypeSupported)===null||Mr===void 0?void 0:Mr.call(us,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean((Ur=(ls=window.MediaSource)===null||ls===void 0?void 0:ls.isTypeSupported)===null||Ur===void 0?void 0:Ur.call(ls,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean((Fr=(cs=window.MediaSource)===null||cs===void 0?void 0:cs.isTypeSupported)===null||Fr===void 0?void 0:Fr.call(cs,'video/webm; codecs="vp9"')),aac:Boolean((Vr=(hs=window.MediaSource)===null||hs===void 0?void 0:hs.isTypeSupported)===null||Vr===void 0?void 0:Vr.call(hs,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean((Hr=(fs=window.MediaSource)===null||fs===void 0?void 0:fs.isTypeSupported)===null||Hr===void 0?void 0:Hr.call(fs,'audio/webm; codecs="opus"'))},zt=(yt.h264||yt.h265)&&yt.aac,Hs=rt.hls&&Ne.mp4,cy=Boolean(window.WebSocket),hy=()=>Object.keys(yt).filter(i=>yt[i]),fy=(i,e=!1)=>i.filter(t=>{switch(t){case b.DASH:return rt.mse&&Ne.mp4&&zt;case b.DASH_SEP:return rt.mse&&Ne.mp4&&zt;case b.DASH_WEBM:return rt.mse&&Ne.webm&&yt.vp9&&yt.opus;case b.DASH_LIVE:return rt.mse&&Ne.mp4&&zt;case b.DASH_LIVE_CMAF:return rt.mse&&Ne.mp4&&zt&&Ne.cmaf;case b.DASH_ONDEMAND:return rt.mse&&Ne.mp4&&zt;case b.HLS:case b.HLS_LIVE:case b.HLS_LIVE_CMAF:case b.HLS_ONDEMAND:return Hs||e&&rt.mse&&Ne.mp4&&zt;case b.MPEG:return Ne.mp4;case b.DASH_LIVE_WEBM:return!1;case b.WEB_RTC_LIVE:return rt.webrtc&&cy&&yt.h264&&(Ne.mp4||Ne.webm);default:return x(t)}}),py=()=>Eu?[b.MPEG,b.DASH_WEBM,b.DASH_SEP,b.DASH,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND]:Hs?[b.DASH_WEBM,b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG,b.DASH]:[b.DASH_WEBM,b.DASH_SEP,b.DASH,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG],vy=()=>Eu?[b.HLS_LIVE,b.HLS_LIVE_CMAF,b.WEB_RTC_LIVE,b.DASH_LIVE,b.DASH_LIVE_CMAF]:Hs?[b.WEB_RTC_LIVE,b.HLS_LIVE,b.HLS_LIVE_CMAF,b.DASH_LIVE,b.DASH_LIVE_CMAF]:[b.WEB_RTC_LIVE,b.DASH_LIVE,b.DASH_LIVE_CMAF,b.HLS_LIVE,b.HLS_LIVE_CMAF],Oo=i=>i?[b.HLS_LIVE]:[b.DASH_WEBM,b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG];var my=i=>new Ii(e=>{const t=new se,s=i.desiredPlaybackState$.stateChangeStarted$.pipe($(({from:d,to:l})=>`${d}-${l}`)),r=i.desiredPlaybackState$.stateChangeEnded$,a=i.providerChanged$,n=new O;let o=0,u="unknown";return t.add(s.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>n.next(d),i.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="provider change",o=0})),t.add(a.subscribe(()=>{o&&(window.clearTimeout(o),o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const Lo={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},Sy={cacheDuration:12e4},gy={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},by={maxPausedTime:3e4},xo={maxPausedTime:3e4};class yy{constructor(e){this.current$=new y({type:void 0}),this.providerError$=new O,this.noAvailableProvidersError$=new O,this.providerOutput={position$:new y(0),duration$:new y(1/0),volume$:new y({muted:!1,volume:1}),currentVideoTrack$:new y(void 0),availableVideoTracks$:new y([]),availableAudioTracks$:new y([]),isAudioAvailable$:new y(!0),autoVideoTrackLimitingAvailable$:new y(!1),currentBuffer$:new y(void 0),isBuffering$:new y(!0),error$:new O,willSeekEvent$:new O,seekedEvent$:new O,loopedEvent$:new O,endedEvent$:new O,firstBytesEvent$:new O,firstFrameEvent$:new O,canplay$:new O,isLive$:new y(void 0),liveTime$:new y(void 0),availableTextTracks$:new y([]),currentTextTrack$:new y(void 0),hostname$:new y(void 0),httpConnectionType$:new y(void 0),httpConnectionReused$:new y(void 0),element$:new y(void 0)},this.subscription=new se,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=fy([...vy(),...py()],this.params.tuning.useHlsJs).filter(n=>w(e.sources[n])),{formatsToAvoid:s}=this.params.tuning,r=s.length?[...t.filter(n=>!s.includes(n)),...t.filter(n=>s.includes(n))]:t;this.screenFormatsIterator=new Co(r);const a=[...Oo(!0),...Oo(!1)];this.chromecastFormatsIterator=new Co(a.filter(n=>w(e.sources[n])))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(K(t)){this.handleNoFormatsError(e);return}let s;try{s=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:C.WTF,message:"Failed to create provider",thrown:r})}s?this.current$.next({type:t,provider:s,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const e=this.current$.getValue().destination;P(e,"No current provider"),this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,s=this.params.desiredState.seekState.getState(),r=s.state!==H.None;this.params.desiredState.seekState.setState({state:H.Requested,position:r?s.position:t,forcePrecise:r?s.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 De.SCREEN:return this.createScreenProvider(t);case De.CHROMECAST:return this.createChromecastProvider(t);default:return x(e)}}createScreenProvider(e){const{sources:t,container:s,desiredState:r}=this.params,a=this.providerOutput,n={container:s,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case b.DASH:{const o=this.applyFailoverHost(t[e]);return P(o),new qg(Object.assign(Object.assign({},n),{source:o,config:Sy}))}case b.DASH_SEP:case b.DASH_WEBM:case b.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),this.params.tuning.useDashJs?new So(Object.assign(Object.assign({},n),{source:o,format:e,config:xo})):new Zb(Object.assign(Object.assign({},n),{source:o}))}case b.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new So(Object.assign(Object.assign({},n),{source:o,format:e,config:xo}))}case b.HLS:case b.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),Hs||!this.params.tuning.useHlsJs?new ry(Object.assign(Object.assign({},n),{source:o})):new ty(Object.assign(Object.assign({},n),{source:o}))}case b.HLS_LIVE:case b.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new sy(Object.assign(Object.assign({},n),{source:o,config:by}))}case b.MPEG:{const o=this.applyFailoverHost(t[e]);return P(o),new ay(Object.assign(Object.assign({},n),{source:o}))}case b.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new Fg(Object.assign(Object.assign({},n),{source:o,config:gy}))}case b.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new uy({container:s,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case b.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return x(e)}}createChromecastProvider(e){const{sources:t,container:s,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return P(o),new WS({connection:o,meta:a,container:s,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?De.CHROMECAST:De.SCREEN}chooseFormat(e){switch(e){case De.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case De.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return x(e)}}skipFormat(e){switch(e){case De.SCREEN:return this.screenFormatsIterator.next();case De.CHROMECAST:return this.chromecastFormatsIterator.next();default:return x(e)}}handleNoFormatsError(e){switch(e){case De.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case De.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return x(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const s=r=>{const a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return Object.assign(Object.assign({},e),{url:s(e.url)})}return Bi(Object.entries(e).map(([r,a])=>[r,s(a)]))}initProviderErrorHandling(){const e=new se;let t=!1,s=0;return e.add(L(this.providerOutput.error$,my({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:Lo.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(j(({type:r})=>r!==void 0))}).pipe($(r=>({id:`ProviderHangup:${r}`,category:C.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(j(({to:a})=>a===v.PLAYING),ye()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{if(this.current$.getValue().destination===De.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const a=r.category===C.NETWORK,n=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),o=s<Lo.providerErrorLimit;n&&(a&&t||!o)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):o?(s++,this.reinitProvider()):this.switchToNextProvider()}})),e}}var Fe;(function(i){i[i.LOCAL_STORAGE=0]="LOCAL_STORAGE",i[i.SESSION_STORAGE=1]="SESSION_STORAGE",i[i.RUNTIME=2]="RUNTIME"})(Fe||(Fe={}));const $u=new Map;let Ct=Fe.RUNTIME;const Gr=`vk-videoplayer-dummy-key-${Math.random()}`,Ty=()=>{try{localStorage.setItem(Gr,"test"),localStorage.removeItem(Gr),Ct=Fe.LOCAL_STORAGE}catch(i){if(i instanceof DOMException||i instanceof TypeError)try{sessionStorage.getItem(Gr),Ct=Fe.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)Ct=Fe.RUNTIME;else throw e}else throw i}};Ty();const Ey=i=>{var e,t;switch(Ct){case Fe.LOCAL_STORAGE:return(e=localStorage.getItem(i))!==null&&e!==void 0?e:void 0;case Fe.SESSION_STORAGE:return(t=sessionStorage.getItem(i))!==null&&t!==void 0?t:void 0;case Fe.RUNTIME:return $u.get(i);default:x(Ct)}},No=(i,e)=>{switch(Ct){case Fe.LOCAL_STORAGE:try{localStorage.setItem(i,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Fe.SESSION_STORAGE:try{sessionStorage.setItem(i,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Fe.RUNTIME:return void $u.set(i,e);default:x(Ct)}},ha=(i,e,t)=>t*e+(1-t)*i,Au=(i,e)=>i.reduce((t,s)=>t+s,0)/e,$y=(i,e,t,s)=>{let r=0,a=t;const n=Au(i,e),o=e<s?e:s;for(let u=0;u<o;u++)i[a]>n?r++:r--,a=(i.length+a-1)%i.length;return Math.abs(r)===o};class _u{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new y(e.initial),this.debounced$=new y(e.initial);const s=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ze(`raw_${s}`),this.smoothedSeries$=new Ze(`smoothed_${s}`),this.reportedSeries$=new Ze(`reported_${s}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,s=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=Math.pow(this.pastMeasures[o]-this.smoothed,2),s++);this.takenMeasures=s,t/=s;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)&&(K(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 Ay extends _u{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ha(this.slow,e,this.params.emaAlphaSlow),this.fast=ha(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class _y extends _u{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Au(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ha(this.emaSmoothed,e,this.params.emaAlpha);const s=$y(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class Bo{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new Ay({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new _y({initial:e,emaAlpha:s.emaAlpha,basisTrendChangeCount:s.basisTrendChangeCount,changeThreshold:s.changeThreshold,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"})}}const wy=5e3,Mo="one_video_throughput",Uo="one_video_rtt",lt=window.navigator.connection,Fo=()=>{const i=lt==null?void 0:lt.downlink;if(w(i)&&i!==10)return i*1e3},Vo=()=>{const i=lt==null?void 0:lt.rtt;if(w(i)&&i!==3e3)return i},Ho=(i,e,t)=>{const s=t*8,r=s/i;return s/(r+e)};class wi{constructor(e){var t,s;this.subscription=new se,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=wi.load(Mo)||(e.useBrowserEstimation?Fo():void 0)||wy,a=(s=(t=wi.load(Uo))!==null&&t!==void 0?t:e.useBrowserEstimation?Vo():void 0)!==null&&s!==void 0?s:0;if(this.throughput$=new y(r),this.rtt$=new y(a),this.rttAdjustedThroughput$=new y(Ho(r,a,e.rttPenaltyRequestSize)),this.throughput=Bo.getSmoothedValue(r,-1,e),this.rtt=Bo.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const u=Fo();u&&this.throughput.next(u);const d=Vo();w(d)&&this.rtt.next(d)};lt&&"onchange"in lt&&this.subscription.add(U(lt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{No(Mo,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{No(Uo,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(dt({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe($(({throughput:n,rtt:o})=>Ho(n,o,e.rttPenaltyRequestSize)),j(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,s=pe();const r=new se;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(U(e,"progress").pipe(ye()).subscribe(a=>{t=a.loaded,s=pe()}));break;case 1:case 0:r.add(U(e,"loadstart").subscribe(()=>{t=0,s=pe()}));break}r.add(U(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=pe(),u=n-t,d=o-s;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 s=0;const r=pe();let a=0,n=pe();const o=d=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},u=({done:d,value:l})=>ue(this,void 0,void 0,function*(){d?(this.addRawSpeed(s,pe()-r,1),this.concurrentDownloads.delete(e)):l&&(s+=l.byteLength,a+=l.byteLength,a>=this.tuningConfig.streamMinSampleSize&&pe()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,pe()-n,this.concurrentDownloads.size),a=0,n=pe()),yield t==null?void 0:t.read().then(u,o))});this.concurrentDownloads.add(e),t==null||t.read().then(u,o)}addRawSpeed(e,t,s=1){if(wi.sanityCheck(e,t)){const r=e*8/t;this.throughput.next(r*s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const s=e*8/t;return!(!s||!isFinite(s)||s>1e6||s<30||e<10*1024||t<=20)}static load(e){var t;const s=Ey(e);if(w(s))return(t=parseInt(s,10))!==null&&t!==void 0?t:void 0}}const Go={throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useHlsJs:!0,isAudioDisabled:!1,webrtc:{connectionRetryMaxNumber:3}},ky=i=>{const e={};for(const t of Object.keys(Go)){const s=Go[t],r=i[t];Array.isArray(s)&&Array.isArray(r)?e[t]=r:typeof s=="object"&&typeof r=="object"?e[t]=Object.assign(Object.assign({},s),r):e[t]=r!=null?r:s}return e};var Py=({seekState:i,position$:e})=>L(i.stateChangeEnded$.pipe($(({to:t})=>{var s;return t.state===H.None?void 0:((s=t.position)!==null&&s!==void 0?s:NaN)/1e3}),j(w)),e.pipe(j(()=>i.getState().state===H.None))),Ry=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return P(e,`Wrong container or containerId {${i.container}}`),e};const Yo=({playbackState:i,seekState:e,playbackAbort$:t,looped$:s,position$:r})=>new Ii(a=>{let n;const o=i.transitionEnded$.pipe(j(f=>(f.from===v.PAUSED||f.from===v.STOPPED)&&f.to===v.PLAYING)),u=i.stateChangeEnded$.pipe(j(f=>f.from===v.PLAYING&&f.to===v.PAUSED)),d=e.stateChangeEnded$.pipe(j(({to:f})=>{var m,p;return f.state===H.Requested&&((p=(m=i.getTransition())===null||m===void 0?void 0:m.from)!==null&&p!==void 0?p:i.getState())===v.PLAYING})),l=e.stateChangeEnded$.pipe(j(({from:f,to:m})=>{var p,S;return f.state===H.Applying&&m.state===H.None&&((S=(p=i.getTransition())===null||p===void 0?void 0:p.from)!==null&&S!==void 0?S:i.getState())===v.PLAYING})),c=L(o,l).pipe($(()=>r.getValue()),j(w)),h=L(L(u,d,t),s).pipe($(()=>r.getValue()),j(w));return new se().add(c.subscribe(f=>{n=f})).add(h.subscribe(f=>{if(K(n)||n===f)return;const m={from:n,to:f};n=void 0,a.next(m)}))});class xy{constructor(e={}){if(this.subscription=new se,this.logger=new ju,this.isPlaybackStarted=!1,this.desiredState={playbackState:new le(v.STOPPED),seekState:new le({state:H.None}),volume:new le({volume:1,muted:!1}),videoTrack:new le(void 0),autoVideoTrackSwitching:new le(!0),autoVideoTrackLimits:new le({}),isLooped:new le(!1),playbackRate:new le(1),externalTextTracks:new le([]),currentTextTrack:new le(void 0),textTrackCuesSettings:new le({})},this.info={playbackState$:new y(v.STOPPED),position$:new y(0),duration$:new y(1/0),muted$:new y(!1),volume$:new y(1),availableQualities$:new y([]),availableQualitiesFps$:new y({}),availableAudioTracks$:new y([]),isAudioAvailable$:new y(!0),currentQuality$:new y(void 0),isAutoQualityEnabled$:new y(!0),autoQualityLimitingAvailable$:new y(!1),autoQualityLimits$:new y({}),currentPlaybackRate$:new y(1),currentBuffer$:new y({start:0,end:0}),isBuffering$:new y(!0),isStalled$:new y(!1),isEnded$:new y(!1),isLooped$:new y(!1),isLive$:new y(void 0),liveTime$:new y(void 0),currentFormat$:new y(void 0),availableTextTracks$:new y([]),currentTextTrack$:new y(void 0),throughputEstimation$:new y(void 0),rttEstimation$:new y(void 0),videoBitrate$:new y(void 0),hostname$:new y(void 0),httpConnectionType$:new y(void 0),httpConnectionReused$:new y(void 0),chromecastState$:new y(_e.NOT_AVAILABLE),chromecastDeviceName$:new y(void 0),intrinsicVideoSize$:new y(void 0)},this.events={inited$:new O,started$:new O,willPause$:new O,willResume$:new O,willDestruct$:new O,watchCoverageRecord$:new O,watchCoverageLive$:new O,managedError$:new O,fatalError$:new O,ended$:new O,looped$:new O,seeked$:new O,willSeek$:new O,firstBytes$:new O,firstFrame$:new O,canplay$:new O,log$:new O},this.experimental={element$:new y(void 0),enableDebugTelemetry$:new y(!1),dumpTelemetry:bg},this.initLogs(),this.tuning=ky(e),this.chromecastInitializer=new Ku({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new wi(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,s,r)=>{const a=Reflect.get(t,s,r);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const u=n.map(c=>JSON.stringify(c,(h,f)=>{const m=typeof f;return["number","string","boolean"].includes(m)?f:f===null?null:`<${m}>`})),d=`Player.${String(s)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:C.WTF,message:l,thrown:o}),o}}}})}initVideo(e){var t,s,r;return this.config=e,this.domContainer=Ry(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new yy({sources:e.sources,meta:(s=e.meta)!==null&&s!==void 0?s:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.events.willDestruct$.next(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===v.STOPPED&&e.startTransitionTo(v.READY),this}play(){const e=this.desiredState.playbackState;return e.getState()!==v.PLAYING&&e.startTransitionTo(v.PLAYING),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==v.PAUSED&&e.startTransitionTo(v.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==v.STOPPED&&e.startTransitionTo(v.STOPPED),this}seekTime(e,t=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:H.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()===_e.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()===_e.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){P(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const s=t.find(r=>r.quality===e);return s&&this.desiredState.videoTrack.startTransitionTo(s.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.setState(e),this}setPlaybackRate(e){var t;P(this.providerContainer);const s=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return s&&(this.desiredState.playbackRate.setState(e),s.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>Object.assign({type:"external"},t))),this}selectTextTrack(e){var t;return(e===void 0||!((t=this.providerContainer)===null||t===void 0)&&t.providerOutput.availableTextTracks$.getValue().find(s=>s.id===e))&&this.desiredState.currentTextTrack.startTransitionTo(e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){P(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(K(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),s=t.state===H.None?void 0:t.position;return w(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}setIntrinsicVideoSize(...e){const t={width:e.reduce((s,{width:r})=>s||r||0,0),height:e.reduce((s,{height:r})=>s||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(L(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe($(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(j(({from:e})=>e===v.STOPPED),ye()).subscribe(()=>{this.initedAt=pe(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.pipe(j(()=>!this.isPlaybackStarted),j(e=>e.to===v.PLAYING)).subscribe(()=>{this.isPlaybackStarted=!0,this.events.started$.next()})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case v.PAUSED:this.events.willPause$.next();break;case v.PLAYING:this.isPlaybackStarted&&this.events.willResume$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const u=this.desiredState.seekState.getState();u.state===H.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},u),{state:H.Applying})):this.events.managedError$.next({id:`WillSeekIn${u.state}`,category:C.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===H.Applying&&(this.desiredState.seekState.setState({state:H.None}),this.events.seeked$.next())})).add(e.current$.pipe($(u=>u.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe($(u=>u.destination),me()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe($(u=>u.map(({quality:d})=>d).sort((d,l)=>As(d)?1:As(l)?-1:Ss(l,d)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(u=>{const d={};for(const l of u)l.fps&&(d[l.quality]=l.fps);this.info.availableQualitiesFps$.next(d)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(u=>{this.info.currentQuality$.next(u==null?void 0:u.quality),this.info.videoBitrate$.next(u==null?void 0:u.bitrate)})).add(e.providerOutput.hostname$.pipe(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($(u=>u?{start:u.from,end:u.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe($(u=>u.muted),me()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe($(u=>u.volume),me()).subscribe(this.info.volume$)).add(Py({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(L(e.providerOutput.endedEvent$.pipe(Ot(!0)),e.providerOutput.seekedEvent$.pipe(Ot(!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($(u=>({id:"NoProviders",category:C.VIDEO_PIPELINE,message:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(ye(),$(()=>pe()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(ye(),$(()=>pe()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ye(),$(()=>pe()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const t=new y(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const s=new y(!0);this.subscription.add(e.current$.subscribe(()=>s.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(j(({to:u})=>u===v.PLAYING),ye()).subscribe(()=>s.next(!1)));let r=0;const a=L(e.providerOutput.isBuffering$,t,s).pipe($(()=>{const u=e.providerOutput.isBuffering$.getValue(),d=t.getValue()||s.getValue();return u&&!d}),me());this.subscription.add(a.subscribe(u=>{u?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))}));const n=new se;this.subscription.add(n);const o=L(U(window,"beforeunload"),this.events.willDestruct$,e.current$.pipe(j(u=>Boolean(u==null?void 0:u.provider))));e.providerOutput.isLive$.pipe(me()).subscribe(u=>{switch(P(this.providerContainer),n.unsubscribe(),u){case!0:{const d=new y(void 0);n.add(this.providerContainer.providerOutput.liveTime$.subscribe(l=>d.next(l&&Math.floor(l/1e3)))),n.add(Yo({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:o,looped$:this.events.looped$,position$:d}).pipe($(({from:l,to:c})=>({start:l,end:c}))).subscribe(this.events.watchCoverageLive$));break}case!1:n.add(Yo({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:o,position$:this.providerContainer.providerOutput.position$}).pipe($(({from:d,to:l})=>({start:d,end:l}))).subscribe(this.events.watchCoverageRecord$));break}}),this.subscription.add(L(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:u==null?void 0:u.videoWidth,height:u==null?void 0:u.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(u=>{var d,l;const c=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(d=u==null?void 0:u.size)===null||d===void 0?void 0:d.width,height:(l=u==null?void 0:u.size)===null||l===void 0?void 0:l.height},{width:c==null?void 0:c.videoWidth,height:c==null?void 0:c.videoHeight})}))}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 se;this.subscription.add(t),this.subscription.add(e.current$.pipe(me((s,r)=>s.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(j(s=>s.length>0),ye()).subscribe(s=>{this.setStartingVideoTrack(s)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:s})=>s===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=Fi(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0})),this.desiredState.videoTrack.startTransitionTo(t.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(L(this.desiredState.videoTrack.stateChangeStarted$.pipe($(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe($(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe($(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe($(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe($(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe($(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe($(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe($(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe($(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;P(this.providerContainer),P(t),gg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(s=>Sg(s)),this.providerContainer.current$.subscribe(({type:s})=>as("provider",s)),t.duration$.subscribe(s=>as("duration",s)),t.availableVideoTracks$.pipe(j(s=>!!s.length),ye()).subscribe(s=>as("tracks",s)),this.events.fatalError$.subscribe(new Ze("fatalError")),this.events.managedError$.subscribe(new Ze("managedError")),t.position$.subscribe(new Ze("position")),t.currentVideoTrack$.pipe($(s=>s==null?void 0:s.quality)).subscribe(new Ze("quality")),this.info.currentBuffer$.subscribe(new Ze("buffer")),t.isBuffering$.subscribe(new Ze("isBuffering"))].forEach(s=>this.subscription.add(s)),as("codecs",hy())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},s=()=>ue(this,void 0,void 0,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:C.DOM,message:String(r)})})});this.subscription.add(L(U(document,"visibilitychange"),U(document,"fullscreenchange"),this.desiredState.playbackState.transitionEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===v.PLAYING,n=Boolean(e)&&!(e!=null&&e.released);r&&a?n||s():t()})).add(this.events.willDestruct$.subscribe(t))}}const Ny=`${Qu}@${Wu}`;export{_e as ChromecastState,ki as HttpConnectionType,Uy as Observable,v as PlaybackState,xy as Player,Ny as SDK_VERSION,Fy as Subject,Vy as Subscription,Hy as ValueSubject,b as VideoFormat,ne as VideoQuality};
6
+ import{ValueSubject as y,Subject as O,Subscription as se,isNonNullable as _,ErrorCategory as D,isNullable as K,fromEvent as U,assertNever as x,merge as L,tap as Qa,map as $,observableFrom as Oe,filterChanged as me,assertNonNullable as P,debounce as Ve,timeout as qu,combine as dt,once as ye,mapTo as Ot,filter as j,now as pe,Observable as Ii,abortable as qe,getExponentialDelay as Ja,interval as ju,Logger as zu}from"@vkontakte/videoplayer-shared/es2015.esm.js";import{Observable as Fy,Subject as Vy,Subscription as Hy,ValueSubject as Gy}from"@vkontakte/videoplayer-shared/es2015.esm.js";import Wu from"lodash/debounce.js";const Qu="2.0.86",Ju="es2015.esm.js";var v;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(v||(v={}));var b;(function(i){i.MPEG="MPEG",i.DASH="DASH",i.DASH_SEP="DASH_SEP",i.DASH_SEP_VK="DASH_SEP",i.DASH_WEBM="DASH_WEBM",i.DASH_WEBM_VK="DASH_WEBM",i.DASH_ONDEMAND="DASH_ONDEMAND",i.DASH_ONDEMAND_VK="DASH_ONDEMAND",i.DASH_LIVE="DASH_LIVE",i.DASH_LIVE_CMAF="DASH_LIVE_CMAF",i.DASH_LIVE_WEBM="DASH_LIVE_WEBM",i.HLS="HLS",i.HLS_ONDEMAND="HLS_ONDEMAND",i.HLS_JS="HLS",i.HLS_LIVE="HLS_LIVE",i.HLS_LIVE_CMAF="HLS_LIVE_CMAF",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(b||(b={}));var De;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(De||(De={}));var we;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(we||(we={}));var ki;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(ki||(ki={}));var H;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(H||(H={}));function ue(i,e,t,s){function r(a){return a instanceof t?a:new t(function(n){n(a)})}return new(t||(t=Promise))(function(a,n){function o(l){try{d(s.next(l))}catch(c){n(c)}}function u(l){try{d(s.throw(l))}catch(c){n(c)}}function d(l){l.done?a(l.value):r(l.value).then(o,u)}d((s=s.apply(i,e||[])).next())})}function M(i){return this instanceof M?(this.v=i,this):new M(i)}function je(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=t.apply(i,e||[]),r,a=[];return r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r;function n(h){s[h]&&(r[h]=function(f){return new Promise(function(m,p){a.push([h,f,m,p])>1||o(h,f)})})}function o(h,f){try{u(s[h](f))}catch(m){c(a[0][3],m)}}function u(h){h.value instanceof M?Promise.resolve(h.value.v).then(d,l):c(a[0][2],h)}function d(h){o("next",h)}function l(h){o("throw",h)}function c(h,f){h(f),a.shift(),a.length&&o(a[0][0],a[0][1])}}var Ku=i=>new Promise((e,t)=>{const s=document.createElement("script");s.setAttribute("src",i),s.onload=()=>e,s.onerror=()=>t,document.body.appendChild(s)});class Xu{constructor(e){var t;this.connection$=new y(void 0),this.castState$=new y(we.NOT_AVAILABLE),this.errorEvent$=new O,this.realCastState$=new y(we.NOT_AVAILABLE),this.subscription=new se,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const s="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)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||Ku("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 s,r,a;(a=(r=(s=cast.framework.CastContext.getInstance())===null||s===void 0?void 0:s.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();K(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();K(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),s=cast.framework.CastContext.getInstance();this.subscription.add(U(s,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=s.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 x(r.sessionState)}})).add(L(U(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(Qa(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),$(r=>r.castState)),Oe([s.getCastState()])).pipe(me(),$(Zu),Qa(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===we.CONNECTED,o=_(this.connection$.getValue());if(n&&!o){const u=s.getCurrentSession();P(u);const d=u.getCastDevice(),l=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(K(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===we.CONNECTED?_(this.connection$.getValue())?we.CONNECTED:we.AVAILABLE:r)}))}initializeCastApi(){var e;let t,s,r;try{t=cast.framework.CastContext.getInstance(),s=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:s,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:D.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const Zu=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return we.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return we.AVAILABLE;case cast.framework.CastState.CONNECTING:return we.CONNECTING;case cast.framework.CastState.CONNECTED:return we.CONNECTED;default:return x(i)}};var Ka=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},He=function(i){try{return!!i()}catch(e){return!0}},el=He,Is=!el(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),jo=Is,zo=Function.prototype,Yr=zo.call,tl=jo&&zo.bind.bind(Yr,Yr),Ge=jo?tl:function(i){return function(){return Yr.apply(i,arguments)}},Wo=Ge,il=Wo({}.toString),sl=Wo("".slice),Di=function(i){return sl(il(i),8,-1)},rl=Ge,al=He,nl=Di,zs=Object,ol=rl("".split),dl=al(function(){return!zs("z").propertyIsEnumerable(0)})?function(i){return nl(i)=="String"?ol(i,""):zs(i)}:zs,Ci=function(i){return i==null},ul=Ci,ll=TypeError,fa=function(i){if(ul(i))throw ll("Can't call method on "+i);return i},cl=dl,hl=fa,Oi=function(i){return cl(hl(i))},fl=function(){},ri={},ji=function(i){return i&&i.Math==Math&&i},_e=ji(typeof globalThis=="object"&&globalThis)||ji(typeof window=="object"&&window)||ji(typeof self=="object"&&self)||ji(typeof Ka=="object"&&Ka)||function(){return this}()||Function("return this")(),qr=typeof document=="object"&&document.all,pl=typeof qr=="undefined"&&qr!==void 0,Qo={all:qr,IS_HTMLDDA:pl},Jo=Qo,vl=Jo.all,Te=Jo.IS_HTMLDDA?function(i){return typeof i=="function"||i===vl}:function(i){return typeof i=="function"},ml=_e,Sl=Te,Xa=ml.WeakMap,gl=Sl(Xa)&&/native code/.test(String(Xa)),Za=Te,Ko=Qo,bl=Ko.all,ct=Ko.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:Za(i)||i===bl}:function(i){return typeof i=="object"?i!==null:Za(i)},yl=He,ht=!yl(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),xt={},Tl=_e,en=ct,jr=Tl.document,El=en(jr)&&en(jr.createElement),pa=function(i){return El?jr.createElement(i):{}},$l=ht,Al=He,wl=pa,Xo=!$l&&!Al(function(){return Object.defineProperty(wl("div"),"a",{get:function(){return 7}}).a!=7}),_l=ht,kl=He,Zo=_l&&kl(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Pl=ct,Rl=String,Il=TypeError,ft=function(i){if(Pl(i))return i;throw Il(Rl(i)+" is not an object")},Dl=Is,zi=Function.prototype.call,Le=Dl?zi.bind(zi):function(){return zi.apply(zi,arguments)},va={},Ws=va,Qs=_e,Cl=Te,tn=function(i){return Cl(i)?i:void 0},Nt=function(i,e){return arguments.length<2?tn(Ws[i])||tn(Qs[i]):Ws[i]&&Ws[i][e]||Qs[i]&&Qs[i][e]},Ol=Ge,Ds=Ol({}.isPrototypeOf),Cs=typeof navigator!="undefined"&&String(navigator.userAgent)||"",ed=_e,Js=Cs,sn=ed.process,rn=ed.Deno,an=sn&&sn.versions||rn&&rn.version,nn=an&&an.v8,Ye,bs;nn&&(Ye=nn.split("."),bs=Ye[0]>0&&Ye[0]<4?1:+(Ye[0]+Ye[1]));!bs&&Js&&(Ye=Js.match(/Edge\/(\d+)/),(!Ye||Ye[1]>=74)&&(Ye=Js.match(/Chrome\/(\d+)/),Ye&&(bs=+Ye[1])));var td=bs,on=td,Ll=He,id=!!Object.getOwnPropertySymbols&&!Ll(function(){var i=Symbol();return!String(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&on&&on<41}),xl=id,sd=xl&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Nl=Nt,Bl=Te,Ml=Ds,Ul=sd,Fl=Object,rd=Ul?function(i){return typeof i=="symbol"}:function(i){var e=Nl("Symbol");return Bl(e)&&Ml(e.prototype,Fl(i))},Vl=String,Os=function(i){try{return Vl(i)}catch(e){return"Object"}},Hl=Te,Gl=Os,Yl=TypeError,Bt=function(i){if(Hl(i))return i;throw Yl(Gl(i)+" is not a function")},ql=Bt,jl=Ci,Ls=function(i,e){var t=i[e];return jl(t)?void 0:ql(t)},Ks=Le,Xs=Te,Zs=ct,zl=TypeError,Wl=function(i,e){var t,s;if(e==="string"&&Xs(t=i.toString)&&!Zs(s=Ks(t,i))||Xs(t=i.valueOf)&&!Zs(s=Ks(t,i))||e!=="string"&&Xs(t=i.toString)&&!Zs(s=Ks(t,i)))return s;throw zl("Can't convert object to primitive value")},ys={},Ql={get exports(){return ys},set exports(i){ys=i}},ad=!0,dn=_e,Jl=Object.defineProperty,Kl=function(i,e){try{Jl(dn,i,{value:e,configurable:!0,writable:!0})}catch(t){dn[i]=e}return e},Xl=_e,Zl=Kl,un="__core-js_shared__",ec=Xl[un]||Zl(un,{}),ma=ec,ln=ma;(Ql.exports=function(i,e){return ln[i]||(ln[i]=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 tc=fa,ic=Object,xs=function(i){return ic(tc(i))},sc=Ge,rc=xs,ac=sc({}.hasOwnProperty),tt=Object.hasOwn||function(e,t){return ac(rc(e),t)},nc=Ge,oc=0,dc=Math.random(),uc=nc(1 .toString),nd=function(i){return"Symbol("+(i===void 0?"":i)+")_"+uc(++oc+dc,36)},lc=_e,cc=ys,cn=tt,hc=nd,fc=id,pc=sd,Wt=lc.Symbol,er=cc("wks"),vc=pc?Wt.for||Wt:Wt&&Wt.withoutSetter||hc,ke=function(i){return cn(er,i)||(er[i]=fc&&cn(Wt,i)?Wt[i]:vc("Symbol."+i)),er[i]},mc=Le,hn=ct,fn=rd,Sc=Ls,gc=Wl,bc=ke,yc=TypeError,Tc=bc("toPrimitive"),Ec=function(i,e){if(!hn(i)||fn(i))return i;var t=Sc(i,Tc),s;if(t){if(e===void 0&&(e="default"),s=mc(t,i,e),!hn(s)||fn(s))return s;throw yc("Can't convert object to primitive value")}return e===void 0&&(e="number"),gc(i,e)},$c=Ec,Ac=rd,Sa=function(i){var e=$c(i,"string");return Ac(e)?e:e+""},wc=ht,_c=Xo,kc=Zo,Wi=ft,pn=Sa,Pc=TypeError,tr=Object.defineProperty,Rc=Object.getOwnPropertyDescriptor,ir="enumerable",sr="configurable",rr="writable";xt.f=wc?kc?function(e,t,s){if(Wi(e),t=pn(t),Wi(s),typeof e=="function"&&t==="prototype"&&"value"in s&&rr in s&&!s[rr]){var r=Rc(e,t);r&&r[rr]&&(e[t]=s.value,s={configurable:sr in s?s[sr]:r[sr],enumerable:ir in s?s[ir]:r[ir],writable:!1})}return tr(e,t,s)}:tr:function(e,t,s){if(Wi(e),t=pn(t),Wi(s),_c)try{return tr(e,t,s)}catch(r){}if("get"in s||"set"in s)throw Pc("Accessors not supported");return"value"in s&&(e[t]=s.value),e};var Ns=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},Ic=ht,Dc=xt,Cc=Ns,Li=Ic?function(i,e,t){return Dc.f(i,e,Cc(1,t))}:function(i,e,t){return i[e]=t,i},Oc=ys,Lc=nd,vn=Oc("keys"),ga=function(i){return vn[i]||(vn[i]=Lc(i))},ba={},xc=gl,od=_e,Nc=ct,Bc=Li,ar=tt,nr=ma,Mc=ga,Uc=ba,mn="Object already initialized",zr=od.TypeError,Fc=od.WeakMap,Ts,Pi,Es,Vc=function(i){return Es(i)?Pi(i):Ts(i,{})},Hc=function(i){return function(e){var t;if(!Nc(e)||(t=Pi(e)).type!==i)throw zr("Incompatible receiver, "+i+" required");return t}};if(xc||nr.state){var Xe=nr.state||(nr.state=new Fc);Xe.get=Xe.get,Xe.has=Xe.has,Xe.set=Xe.set,Ts=function(i,e){if(Xe.has(i))throw zr(mn);return e.facade=i,Xe.set(i,e),e},Pi=function(i){return Xe.get(i)||{}},Es=function(i){return Xe.has(i)}}else{var Ht=Mc("state");Uc[Ht]=!0,Ts=function(i,e){if(ar(i,Ht))throw zr(mn);return e.facade=i,Bc(i,Ht,e),e},Pi=function(i){return ar(i,Ht)?i[Ht]:{}},Es=function(i){return ar(i,Ht)}}var dd={set:Ts,get:Pi,has:Es,enforce:Vc,getterFor:Hc},Gc=Is,ud=Function.prototype,Sn=ud.apply,gn=ud.call,ld=typeof Reflect=="object"&&Reflect.apply||(Gc?gn.bind(Sn):function(){return gn.apply(Sn,arguments)}),Yc=Di,qc=Ge,cd=function(i){if(Yc(i)==="Function")return qc(i)},ya={},hd={},fd={}.propertyIsEnumerable,pd=Object.getOwnPropertyDescriptor,jc=pd&&!fd.call({1:2},1);hd.f=jc?function(e){var t=pd(this,e);return!!t&&t.enumerable}:fd;var zc=ht,Wc=Le,Qc=hd,Jc=Ns,Kc=Oi,Xc=Sa,Zc=tt,eh=Xo,bn=Object.getOwnPropertyDescriptor;ya.f=zc?bn:function(e,t){if(e=Kc(e),t=Xc(t),eh)try{return bn(e,t)}catch(s){}if(Zc(e,t))return Jc(!Wc(Qc.f,e,t),e[t])};var th=He,ih=Te,sh=/#|\.prototype\./,xi=function(i,e){var t=ah[rh(i)];return t==oh?!0:t==nh?!1:ih(e)?th(e):!!e},rh=xi.normalize=function(i){return String(i).replace(sh,".").toLowerCase()},ah=xi.data={},nh=xi.NATIVE="N",oh=xi.POLYFILL="P",vd=xi,yn=cd,dh=Bt,uh=Is,lh=yn(yn.bind),Bs=function(i,e){return dh(i),e===void 0?i:uh?lh(i,e):function(){return i.apply(e,arguments)}},Qi=_e,ch=ld,hh=cd,fh=Te,ph=ya.f,vh=vd,Gt=va,mh=Bs,Yt=Li,Tn=tt,Sh=function(i){var e=function(t,s,r){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,s)}return new i(t,s,r)}return ch(i,this,arguments)};return e.prototype=i.prototype,e},We=function(i,e){var t=i.target,s=i.global,r=i.stat,a=i.proto,n=s?Qi:r?Qi[t]:(Qi[t]||{}).prototype,o=s?Gt:Gt[t]||Yt(Gt,t,{})[t],u=o.prototype,d,l,c,h,f,m,p,S,g;for(h in e)d=vh(s?h:t+(r?".":"#")+h,i.forced),l=!d&&n&&Tn(n,h),m=o[h],l&&(i.dontCallGetSet?(g=ph(n,h),p=g&&g.value):p=n[h]),f=l&&p?p:e[h],!(l&&typeof m==typeof f)&&(i.bind&&l?S=mh(f,Qi):i.wrap&&l?S=Sh(f):a&&fh(f)?S=hh(f):S=f,(i.sham||f&&f.sham||m&&m.sham)&&Yt(S,"sham",!0),Yt(o,h,S),a&&(c=t+"Prototype",Tn(Gt,c)||Yt(Gt,c,{}),Yt(Gt[c],h,f),i.real&&u&&(d||!u[h])&&Yt(u,h,f)))},Wr=ht,gh=tt,md=Function.prototype,bh=Wr&&Object.getOwnPropertyDescriptor,Ta=gh(md,"name"),yh=Ta&&function(){}.name==="something",Th=Ta&&(!Wr||Wr&&bh(md,"name").configurable),Eh={EXISTS:Ta,PROPER:yh,CONFIGURABLE:Th},Sd={},$h=Math.ceil,Ah=Math.floor,wh=Math.trunc||function(e){var t=+e;return(t>0?Ah:$h)(t)},_h=wh,Ea=function(i){var e=+i;return e!==e||e===0?0:_h(e)},kh=Ea,Ph=Math.max,Rh=Math.min,Ih=function(i,e){var t=kh(i);return t<0?Ph(t+e,0):Rh(t,e)},Dh=Ea,Ch=Math.min,Oh=function(i){return i>0?Ch(Dh(i),9007199254740991):0},Lh=Oh,$a=function(i){return Lh(i.length)},xh=Oi,Nh=Ih,Bh=$a,En=function(i){return function(e,t,s){var r=xh(e),a=Bh(r),n=Nh(s,a),o;if(i&&t!=t){for(;a>n;)if(o=r[n++],o!=o)return!0}else for(;a>n;n++)if((i||n in r)&&r[n]===t)return i||n||0;return!i&&-1}},Mh={includes:En(!0),indexOf:En(!1)},Uh=Ge,or=tt,Fh=Oi,Vh=Mh.indexOf,Hh=ba,$n=Uh([].push),Gh=function(i,e){var t=Fh(i),s=0,r=[],a;for(a in t)!or(Hh,a)&&or(t,a)&&$n(r,a);for(;e.length>s;)or(t,a=e[s++])&&(~Vh(r,a)||$n(r,a));return r},gd=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Yh=Gh,qh=gd,jh=Object.keys||function(e){return Yh(e,qh)},zh=ht,Wh=Zo,Qh=xt,Jh=ft,Kh=Oi,Xh=jh;Sd.f=zh&&!Wh?Object.defineProperties:function(e,t){Jh(e);for(var s=Kh(t),r=Xh(t),a=r.length,n=0,o;a>n;)Qh.f(e,o=r[n++],s[o]);return e};var Zh=Nt,bd=Zh("document","documentElement"),ef=ft,tf=Sd,An=gd,sf=ba,rf=bd,af=pa,nf=ga,wn=">",_n="<",Qr="prototype",Jr="script",yd=nf("IE_PROTO"),dr=function(){},Td=function(i){return _n+Jr+wn+i+_n+"/"+Jr+wn},kn=function(i){i.write(Td("")),i.close();var e=i.parentWindow.Object;return i=null,e},of=function(){var i=af("iframe"),e="java"+Jr+":",t;return i.style.display="none",rf.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Td("document.F=Object")),t.close(),t.F},Ji,ps=function(){try{Ji=new ActiveXObject("htmlfile")}catch(e){}ps=typeof document!="undefined"?document.domain&&Ji?kn(Ji):of():kn(Ji);for(var i=An.length;i--;)delete ps[Qr][An[i]];return ps()};sf[yd]=!0;var Ed=Object.create||function(e,t){var s;return e!==null?(dr[Qr]=ef(e),s=new dr,dr[Qr]=null,s[yd]=e):s=ps(),t===void 0?s:tf.f(s,t)},df=He,uf=!df(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),lf=tt,cf=Te,hf=xs,ff=ga,pf=uf,Pn=ff("IE_PROTO"),Kr=Object,vf=Kr.prototype,$d=pf?Kr.getPrototypeOf:function(i){var e=hf(i);if(lf(e,Pn))return e[Pn];var t=e.constructor;return cf(t)&&e instanceof t?t.prototype:e instanceof Kr?vf:null},mf=Li,Aa=function(i,e,t,s){return s&&s.enumerable?i[e]=t:mf(i,e,t),i},Sf=He,gf=Te,bf=ct,yf=Ed,Rn=$d,Tf=Aa,Ef=ke,Xr=Ef("iterator"),Ad=!1,ut,ur,lr;[].keys&&(lr=[].keys(),"next"in lr?(ur=Rn(Rn(lr)),ur!==Object.prototype&&(ut=ur)):Ad=!0);var $f=!bf(ut)||Sf(function(){var i={};return ut[Xr].call(i)!==i});$f?ut={}:ut=yf(ut);gf(ut[Xr])||Tf(ut,Xr,function(){return this});var wd={IteratorPrototype:ut,BUGGY_SAFARI_ITERATORS:Ad},Af=ke,wf=Af("toStringTag"),_d={};_d[wf]="z";var wa=String(_d)==="[object z]",_f=wa,kf=Te,vs=Di,Pf=ke,Rf=Pf("toStringTag"),If=Object,Df=vs(function(){return arguments}())=="Arguments",Cf=function(i,e){try{return i[e]}catch(t){}},Ni=_f?vs:function(i){var e,t,s;return i===void 0?"Undefined":i===null?"Null":typeof(t=Cf(e=If(i),Rf))=="string"?t:Df?vs(e):(s=vs(e))=="Object"&&kf(e.callee)?"Arguments":s},Of=wa,Lf=Ni,xf=Of?{}.toString:function(){return"[object "+Lf(this)+"]"},Nf=wa,Bf=xt.f,Mf=Li,Uf=tt,Ff=xf,Vf=ke,In=Vf("toStringTag"),_a=function(i,e,t,s){if(i){var r=t?i:i.prototype;Uf(r,In)||Bf(r,In,{configurable:!0,value:e}),s&&!Nf&&Mf(r,"toString",Ff)}},Hf=wd.IteratorPrototype,Gf=Ed,Yf=Ns,qf=_a,jf=ri,zf=function(){return this},Wf=function(i,e,t,s){var r=e+" Iterator";return i.prototype=Gf(Hf,{next:Yf(+!s,t)}),qf(i,r,!1,!0),jf[r]=zf,i},Qf=We,Jf=Le,kd=Eh,Kf=Wf,Xf=$d,Zf=_a,Dn=Aa,ep=ke,Cn=ri,Pd=wd,tp=kd.PROPER;kd.CONFIGURABLE;Pd.IteratorPrototype;var Ki=Pd.BUGGY_SAFARI_ITERATORS,cr=ep("iterator"),On="keys",Xi="values",Ln="entries",ip=function(){return this},sp=function(i,e,t,s,r,a,n){Kf(t,e,s);var o=function(g){if(g===r&&h)return h;if(!Ki&&g in l)return l[g];switch(g){case On:return function(){return new t(this,g)};case Xi:return function(){return new t(this,g)};case Ln:return function(){return new t(this,g)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,l=i.prototype,c=l[cr]||l["@@iterator"]||r&&l[r],h=!Ki&&c||o(r),f=e=="Array"&&l.entries||c,m,p,S;if(f&&(m=Xf(f.call(new i)),m!==Object.prototype&&m.next&&(Zf(m,u,!0,!0),Cn[u]=ip)),tp&&r==Xi&&c&&c.name!==Xi&&(d=!0,h=function(){return Jf(c,this)}),r)if(p={values:o(Xi),keys:a?h:o(On),entries:o(Ln)},n)for(S in p)(Ki||d||!(S in l))&&Dn(l,S,p[S]);else Qf({target:e,proto:!0,forced:Ki||d},p);return n&&l[cr]!==h&&Dn(l,cr,h,{name:r}),Cn[e]=h,p},rp=function(i,e){return{value:i,done:e}},ap=Oi,ka=fl,xn=ri,Rd=dd,np=xt.f,op=sp,Zi=rp,dp=ad,up=ht,Id="Array Iterator",lp=Rd.set,cp=Rd.getterFor(Id);op(Array,"Array",function(i,e){lp(this,{type:Id,target:ap(i),index:0,kind:e})},function(){var i=cp(this),e=i.target,t=i.kind,s=i.index++;return!e||s>=e.length?(i.target=void 0,Zi(void 0,!0)):t=="keys"?Zi(s,!1):t=="values"?Zi(e[s],!1):Zi([s,e[s]],!1)},"values");var Nn=xn.Arguments=xn.Array;ka();ka();ka();if(!dp&&up&&Nn.name!=="values")try{np(Nn,"name",{value:"values"})}catch(i){}var hp=ke,fp=ri,pp=hp("iterator"),vp=Array.prototype,mp=function(i){return i!==void 0&&(fp.Array===i||vp[pp]===i)},Sp=Ni,Bn=Ls,gp=Ci,bp=ri,yp=ke,Tp=yp("iterator"),Dd=function(i){if(!gp(i))return Bn(i,Tp)||Bn(i,"@@iterator")||bp[Sp(i)]},Ep=Le,$p=Bt,Ap=ft,wp=Os,_p=Dd,kp=TypeError,Pp=function(i,e){var t=arguments.length<2?_p(i):e;if($p(t))return Ap(Ep(t,i));throw kp(wp(i)+" is not iterable")},Rp=Le,Mn=ft,Ip=Ls,Dp=function(i,e,t){var s,r;Mn(i);try{if(s=Ip(i,"return"),!s){if(e==="throw")throw t;return t}s=Rp(s,i)}catch(a){r=!0,s=a}if(e==="throw")throw t;if(r)throw s;return Mn(s),t},Cp=Bs,Op=Le,Lp=ft,xp=Os,Np=mp,Bp=$a,Un=Ds,Mp=Pp,Up=Dd,Fn=Dp,Fp=TypeError,ms=function(i,e){this.stopped=i,this.result=e},Vn=ms.prototype,Pa=function(i,e,t){var s=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=Cp(e,s),d,l,c,h,f,m,p,S=function(T){return d&&Fn(d,"normal",T),new ms(!0,T)},g=function(T){return r?(Lp(T),o?u(T[0],T[1],S):u(T[0],T[1])):o?u(T,S):u(T)};if(a)d=i.iterator;else if(n)d=i;else{if(l=Up(i),!l)throw Fp(xp(i)+" is not iterable");if(Np(l)){for(c=0,h=Bp(i);h>c;c++)if(f=g(i[c]),f&&Un(Vn,f))return f;return new ms(!1)}d=Mp(i,l)}for(m=a?i.next:d.next;!(p=Op(m,d)).done;){try{f=g(p.value)}catch(T){Fn(d,"throw",T)}if(typeof f=="object"&&f&&Un(Vn,f))return f}return new ms(!1)},Vp=Sa,Hp=xt,Gp=Ns,Yp=function(i,e,t){var s=Vp(e);s in i?Hp.f(i,s,Gp(0,t)):i[s]=t},qp=We,jp=Pa,zp=Yp;qp({target:"Object",stat:!0},{fromEntries:function(e){var t={};return jp(e,function(s,r){zp(t,s,r)},{AS_ENTRIES:!0}),t}});var Wp=va,Qp=Wp.Object.fromEntries,Jp={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},Kp=Jp,Xp=_e,Zp=Ni,ev=Li,Hn=ri,tv=ke,Gn=tv("toStringTag");for(var hr in Kp){var Yn=Xp[hr],fr=Yn&&Yn.prototype;fr&&Zp(fr)!==Gn&&ev(fr,Gn,hr),Hn[hr]=Hn.Array}var iv=Qp,sv=iv,rv=sv,av=rv,Bi=av,nv=Di,Ms=typeof process!="undefined"&&nv(process)=="process",ov=Nt,dv=xt,uv=ke,lv=ht,qn=uv("species"),cv=function(i){var e=ov(i),t=dv.f;lv&&e&&!e[qn]&&t(e,qn,{configurable:!0,get:function(){return this}})},hv=Ds,fv=TypeError,pv=function(i,e){if(hv(e,i))return i;throw fv("Incorrect invocation")},vv=Ge,mv=Te,Zr=ma,Sv=vv(Function.toString);mv(Zr.inspectSource)||(Zr.inspectSource=function(i){return Sv(i)});var Cd=Zr.inspectSource,gv=Ge,bv=He,Od=Te,yv=Ni,Tv=Nt,Ev=Cd,Ld=function(){},$v=[],xd=Tv("Reflect","construct"),Ra=/^\s*(?:class|function)\b/,Av=gv(Ra.exec),wv=!Ra.exec(Ld),gi=function(e){if(!Od(e))return!1;try{return xd(Ld,$v,e),!0}catch(t){return!1}},Nd=function(e){if(!Od(e))return!1;switch(yv(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return wv||!!Av(Ra,Ev(e))}catch(t){return!0}};Nd.sham=!0;var _v=!xd||bv(function(){var i;return gi(gi.call)||!gi(Object)||!gi(function(){i=!0})||i})?Nd:gi,kv=_v,Pv=Os,Rv=TypeError,Iv=function(i){if(kv(i))return i;throw Rv(Pv(i)+" is not a constructor")},jn=ft,Dv=Iv,Cv=Ci,Ov=ke,Lv=Ov("species"),Bd=function(i,e){var t=jn(i).constructor,s;return t===void 0||Cv(s=jn(t)[Lv])?e:Dv(s)},xv=Ge,Nv=xv([].slice),Bv=TypeError,Mv=function(i,e){if(i<e)throw Bv("Not enough arguments");return i},Uv=Cs,Md=/(?:ipad|iphone|ipod).*applewebkit/i.test(Uv),Ce=_e,Fv=ld,Vv=Bs,zn=Te,Hv=tt,Ud=He,Wn=bd,Gv=Nv,Qn=pa,Yv=Mv,qv=Md,jv=Ms,ea=Ce.setImmediate,ta=Ce.clearImmediate,zv=Ce.process,pr=Ce.Dispatch,Wv=Ce.Function,Jn=Ce.MessageChannel,Qv=Ce.String,vr=0,Ei={},Kn="onreadystatechange",Ri,Rt,mr,Sr;Ud(function(){Ri=Ce.location});var Ia=function(i){if(Hv(Ei,i)){var e=Ei[i];delete Ei[i],e()}},gr=function(i){return function(){Ia(i)}},Xn=function(i){Ia(i.data)},Zn=function(i){Ce.postMessage(Qv(i),Ri.protocol+"//"+Ri.host)};(!ea||!ta)&&(ea=function(e){Yv(arguments.length,1);var t=zn(e)?e:Wv(e),s=Gv(arguments,1);return Ei[++vr]=function(){Fv(t,void 0,s)},Rt(vr),vr},ta=function(e){delete Ei[e]},jv?Rt=function(i){zv.nextTick(gr(i))}:pr&&pr.now?Rt=function(i){pr.now(gr(i))}:Jn&&!qv?(mr=new Jn,Sr=mr.port2,mr.port1.onmessage=Xn,Rt=Vv(Sr.postMessage,Sr)):Ce.addEventListener&&zn(Ce.postMessage)&&!Ce.importScripts&&Ri&&Ri.protocol!=="file:"&&!Ud(Zn)?(Rt=Zn,Ce.addEventListener("message",Xn,!1)):Kn in Qn("script")?Rt=function(i){Wn.appendChild(Qn("script"))[Kn]=function(){Wn.removeChild(this),Ia(i)}}:Rt=function(i){setTimeout(gr(i),0)});var Fd={set:ea,clear:ta},Vd=function(){this.head=null,this.tail=null};Vd.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};var Hd=Vd,Jv=Cs,Kv=/ipad|iphone|ipod/i.test(Jv)&&typeof Pebble!="undefined",Xv=Cs,Zv=/web0s(?!.*chrome)/i.test(Xv),Lt=_e,eo=Bs,em=ya.f,br=Fd.set,tm=Hd,im=Md,sm=Kv,rm=Zv,yr=Ms,to=Lt.MutationObserver||Lt.WebKitMutationObserver,io=Lt.document,so=Lt.process,es=Lt.Promise,ro=em(Lt,"queueMicrotask"),ia=ro&&ro.value,qt,Tr,Er,ts,ao;if(!ia){var is=new tm,ss=function(){var i,e;for(yr&&(i=so.domain)&&i.exit();e=is.get();)try{e()}catch(t){throw is.head&&qt(),t}i&&i.enter()};!im&&!yr&&!rm&&to&&io?(Tr=!0,Er=io.createTextNode(""),new to(ss).observe(Er,{characterData:!0}),qt=function(){Er.data=Tr=!Tr}):!sm&&es&&es.resolve?(ts=es.resolve(void 0),ts.constructor=es,ao=eo(ts.then,ts),qt=function(){ao(ss)}):yr?qt=function(){so.nextTick(ss)}:(br=eo(br,Lt),qt=function(){br(ss)}),ia=function(i){is.head||qt(),is.add(i)}}var am=ia,nm=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},Da=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},om=_e,ai=om.Promise,Gd=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",dm=Gd,um=Ms,lm=!dm&&!um&&typeof window=="object"&&typeof document=="object",cm=_e,$i=ai,hm=Te,fm=vd,pm=Cd,vm=ke,mm=lm,Sm=Gd,$r=td,no=$i&&$i.prototype,gm=vm("species"),sa=!1,Yd=hm(cm.PromiseRejectionEvent),bm=fm("Promise",function(){var i=pm($i),e=i!==String($i);if(!e&&$r===66||!(no.catch&&no.finally))return!0;if(!$r||$r<51||!/native code/.test(i)){var t=new $i(function(a){a(1)}),s=function(a){a(function(){},function(){})},r=t.constructor={};if(r[gm]=s,sa=t.then(function(){})instanceof s,!sa)return!0}return!e&&(mm||Sm)&&!Yd}),Mi={CONSTRUCTOR:bm,REJECTION_EVENT:Yd,SUBCLASSING:sa},ni={},oo=Bt,ym=TypeError,Tm=function(i){var e,t;this.promise=new i(function(s,r){if(e!==void 0||t!==void 0)throw ym("Bad Promise constructor");e=s,t=r}),this.resolve=oo(e),this.reject=oo(t)};ni.f=function(i){return new Tm(i)};var Em=We,$s=Ms,Tt=_e,Ui=Le,$m=Aa,Am=_a,wm=cv,_m=Bt,ra=Te,km=ct,Pm=pv,Rm=Bd,qd=Fd.set,Ca=am,Im=nm,Dm=Da,Cm=Hd,jd=dd,aa=ai,Oa=Mi,zd=ni,Us="Promise",Wd=Oa.CONSTRUCTOR,Om=Oa.REJECTION_EVENT;Oa.SUBCLASSING;var Ar=jd.getterFor(Us),Lm=jd.set,xm=aa&&aa.prototype,Qt=aa,wr=xm,Qd=Tt.TypeError,na=Tt.document,La=Tt.process,oa=zd.f,Nm=oa,Bm=!!(na&&na.createEvent&&Tt.dispatchEvent),Jd="unhandledrejection",Mm="rejectionhandled",uo=0,Kd=1,Um=2,xa=1,Xd=2,rs,lo,Fm,Zd=function(i){var e;return km(i)&&ra(e=i.then)?e:!1},eu=function(i,e){var t=e.value,s=e.state==Kd,r=s?i.ok:i.fail,a=i.resolve,n=i.reject,o=i.domain,u,d,l;try{r?(s||(e.rejection===Xd&&Hm(e),e.rejection=xa),r===!0?u=t:(o&&o.enter(),u=r(t),o&&(o.exit(),l=!0)),u===i.promise?n(Qd("Promise-chain cycle")):(d=Zd(u))?Ui(d,u,a,n):a(u)):n(t)}catch(c){o&&!l&&o.exit(),n(c)}},tu=function(i,e){i.notified||(i.notified=!0,Ca(function(){for(var t=i.reactions,s;s=t.get();)eu(s,i);i.notified=!1,e&&!i.rejection&&Vm(i)}))},iu=function(i,e,t){var s,r;Bm?(s=na.createEvent("Event"),s.promise=e,s.reason=t,s.initEvent(i,!1,!0),Tt.dispatchEvent(s)):s={promise:e,reason:t},!Om&&(r=Tt["on"+i])?r(s):i===Jd&&Im("Unhandled promise rejection",t)},Vm=function(i){Ui(qd,Tt,function(){var e=i.facade,t=i.value,s=co(i),r;if(s&&(r=Dm(function(){$s?La.emit("unhandledRejection",t,e):iu(Jd,e,t)}),i.rejection=$s||co(i)?Xd:xa,r.error))throw r.value})},co=function(i){return i.rejection!==xa&&!i.parent},Hm=function(i){Ui(qd,Tt,function(){var e=i.facade;$s?La.emit("rejectionHandled",e):iu(Mm,e,i.value)})},Jt=function(i,e,t){return function(s){i(e,s,t)}},Xt=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=Um,tu(i,!0))},da=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw Qd("Promise can't be resolved itself");var s=Zd(e);s?Ca(function(){var r={done:!1};try{Ui(s,e,Jt(da,r,i),Jt(Xt,r,i))}catch(a){Xt(r,a,i)}}):(i.value=e,i.state=Kd,tu(i,!1))}catch(r){Xt({done:!1},r,i)}}};Wd&&(Qt=function(e){Pm(this,wr),_m(e),Ui(rs,this);var t=Ar(this);try{e(Jt(da,t),Jt(Xt,t))}catch(s){Xt(t,s)}},wr=Qt.prototype,rs=function(e){Lm(this,{type:Us,done:!1,notified:!1,parent:!1,reactions:new Cm,rejection:!1,state:uo,value:void 0})},rs.prototype=$m(wr,"then",function(e,t){var s=Ar(this),r=oa(Rm(this,Qt));return s.parent=!0,r.ok=ra(e)?e:!0,r.fail=ra(t)&&t,r.domain=$s?La.domain:void 0,s.state==uo?s.reactions.add(r):Ca(function(){eu(r,s)}),r.promise}),lo=function(){var i=new rs,e=Ar(i);this.promise=i,this.resolve=Jt(da,e),this.reject=Jt(Xt,e)},zd.f=oa=function(i){return i===Qt||i===Fm?new lo(i):Nm(i)});Em({global:!0,constructor:!0,wrap:!0,forced:Wd},{Promise:Qt});Am(Qt,Us,!1,!0);wm(Us);var Gm=ke,su=Gm("iterator"),ru=!1;try{var Ym=0,ho={next:function(){return{done:!!Ym++}},return:function(){ru=!0}};ho[su]=function(){return this},Array.from(ho,function(){throw 2})}catch(i){}var qm=function(i,e){if(!e&&!ru)return!1;var t=!1;try{var s={};s[su]=function(){return{next:function(){return{done:t=!0}}}},i(s)}catch(r){}return t},jm=ai,zm=qm,Wm=Mi.CONSTRUCTOR,au=Wm||!zm(function(i){jm.all(i).then(void 0,function(){})}),Qm=We,Jm=Le,Km=Bt,Xm=ni,Zm=Da,eS=Pa,tS=au;Qm({target:"Promise",stat:!0,forced:tS},{all:function(e){var t=this,s=Xm.f(t),r=s.resolve,a=s.reject,n=Zm(function(){var o=Km(t.resolve),u=[],d=0,l=1;eS(e,function(c){var h=d++,f=!1;l++,Jm(o,t,c).then(function(m){f||(f=!0,u[h]=m,--l||r(u))},a)}),--l||r(u)});return n.error&&a(n.value),s.promise}});var iS=We,sS=Mi.CONSTRUCTOR,fo=ai;fo&&fo.prototype;iS({target:"Promise",proto:!0,forced:sS,real:!0},{catch:function(i){return this.then(void 0,i)}});var rS=We,aS=Le,nS=Bt,oS=ni,dS=Da,uS=Pa,lS=au;rS({target:"Promise",stat:!0,forced:lS},{race:function(e){var t=this,s=oS.f(t),r=s.reject,a=dS(function(){var n=nS(t.resolve);uS(e,function(o){aS(n,t,o).then(s.resolve,r)})});return a.error&&r(a.value),s.promise}});var cS=We,hS=Le,fS=ni,pS=Mi.CONSTRUCTOR;cS({target:"Promise",stat:!0,forced:pS},{reject:function(e){var t=fS.f(this);return hS(t.reject,void 0,e),t.promise}});var vS=ft,mS=ct,SS=ni,nu=function(i,e){if(vS(i),mS(e)&&e.constructor===i)return e;var t=SS.f(i),s=t.resolve;return s(e),t.promise},gS=We,bS=Nt,yS=ad,TS=ai,ES=Mi.CONSTRUCTOR,$S=nu,AS=bS("Promise"),wS=!ES;gS({target:"Promise",stat:!0,forced:yS},{resolve:function(e){return $S(wS&&this===AS?TS:this,e)}});var _S=We,ua=ai,kS=He,PS=Nt,RS=Te,IS=Bd,po=nu,DS=ua&&ua.prototype,CS=!!ua&&kS(function(){DS.finally.call({then:function(){}},function(){})});_S({target:"Promise",proto:!0,real:!0,forced:CS},{finally:function(i){var e=IS(this,PS("Promise")),t=RS(i);return this.then(t?function(s){return po(e,i()).then(function(){return s})}:i,t?function(s){return po(e,i()).then(function(){throw s})}:i)}});var OS=Nt,Na=OS,LS=Na,xS=LS("Promise","finally"),NS=xS,BS=NS,MS=BS,US=MS,Fs=US,Zt;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(Zt||(Zt={}));var ei=(i,e=0,t=Zt.OFFSET_P)=>{switch(t){case Zt.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Zt.PLAYBACK_SHIFT:{if(e===0)return i;const s=new URL(i);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}default:x(t)}return i},R=(i,e,t=!1)=>{const s=i.getTransition();(t||!s||s.to===e)&&i.setState(e)},ne;(function(i){i.INVARIANT="Invariant quality",i.Q_144P="144p",i.Q_240P="240p",i.Q_360P="360p",i.Q_480P="480p",i.Q_720P="720p",i.Q_1080P="1080p",i.Q_1440P="1440p",i.Q_2160P="2160p",i.Q_4320P="4320p"})(ne||(ne={}));const ze={[ne.Q_144P]:{width:256,height:144},[ne.Q_240P]:{width:428,height:240},[ne.Q_360P]:{width:640,height:360},[ne.Q_480P]:{width:856,height:480},[ne.Q_720P]:{width:1280,height:720},[ne.Q_1080P]:{width:1920,height:1080},[ne.Q_1440P]:{width:2560,height:1440},[ne.Q_2160P]:{width:3840,height:2160},[ne.Q_4320P]:{width:7680,height:4320}},Ss=(i,e)=>ze[i].height>ze[e].height,FS=(i,e)=>ze[i].height>=ze[e].height,Ai=(i,e)=>ze[i].height<ze[e].height,VS=(i,e)=>ze[i].height<=ze[e].height,HS=i=>i.sort((e,t)=>e===t?0:e===ne.INVARIANT?1:t===ne.INVARIANT?-1:Ai(e,t)?1:-1)[0],GS=Object.keys(ze).sort((i,e)=>Ai(i,e)?-1:1),Mt=({width:i,height:e})=>{const t=Math.min(i,e),s=Math.max(i,e);return GS.find(r=>{const a=ze[r];return a.width>=s&&a.height>=t})},YS=i=>ze[i].height,As=i=>i===ne.INVARIANT;class le{constructor(e){this.transitionStarted$=new O,this.transitionEnded$=new O,this.transitionUpdated$=new O,this.forceChanged$=new O,this.stateChangeStarted$=L(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=L(this.transitionEnded$,this.forceChanged$),this.state=e}setState(e){const t=this.transition,s=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:s,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,s=this.state;s===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:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}const qS=i=>{switch(i){case b.MPEG:case b.DASH:case b.DASH_SEP:case b.DASH_ONDEMAND:case b.DASH_WEBM:case b.HLS:case b.HLS_ONDEMAND:return!1;case b.DASH_LIVE:case b.DASH_LIVE_CMAF:case b.HLS_LIVE:case b.HLS_LIVE_CMAF:case b.DASH_LIVE_WEBM:case b.WEB_RTC_LIVE:return!0;default:return x(i)}};var q;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(q||(q={}));const jS=5,zS=5,WS=500,vo=7e3;class QS{constructor(e){this.subscription=new se,this.loadMediaTimeoutSubscription=new se,this.videoState=new le(q.STOPPED),this.syncPlayback=()=>{const s=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: ${s}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${a}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(o)};`}),a===v.STOPPED){s!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==v.PAUSED&&o.state===H.Requested&&s!==q.STOPPED){this.seek(o.position/1e3);return}switch(a){case v.READY:{switch(s){case q.PLAYING:case q.PAUSED:case q.READY:break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:x(s)}break}case v.PLAYING:{switch(s){case q.PLAYING:break;case q.PAUSED:this.videoState.startTransitionTo(q.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case q.READY:this.videoState.startTransitionTo(q.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:x(s)}break}case v.PAUSED:{switch(s){case q.PLAYING:this.videoState.startTransitionTo(q.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case q.PAUSED:break;case q.READY:this.videoState.startTransitionTo(q.PAUSED),this.videoState.setState(q.PAUSED);break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:x(s)}break}default:x(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(qS(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 se;this.subscription.add(e),this.subscription.add(L(this.videoState.stateChangeStarted$.pipe($(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe($(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));const t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const r=new O;e.add(r.pipe(Ve(WS)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===H.Applying||Math.abs(o-a)>jS)&&r.next(o),a=o})),e.add(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<zS&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),R(this.params.desiredState.playbackState,v.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:x(n)}}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(U(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const s=L(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ve(0));t(s,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(q.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED)):(this.videoState.setState(q.PLAYING),R(this.params.desiredState.playbackState,v.PLAYING));const s=this.params.output.isLive$.getValue();this.params.output.duration$.next(s?0:t.duration),this.params.output.position$.next(s?0:t.currentTime),this.params.desiredState.seekState.setState({state:H.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),s=this.createLoadRequest(t);this.loadMedia(s)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===q.PAUSED||e===q.PLAYING)&&(this.videoState.setState(q.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===q.PLAYING||e===q.PAUSED)&&(this.videoState.setState(q.PLAYING),R(this.params.desiredState.playbackState,v.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===q.READY&&this.videoState.setState(q.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===v.READY&&R(this.params.desiredState.playbackState,v.READY)}handleRemoteStop(){this.videoState.getState()!==q.STOPPED&&this.videoState.setState(q.STOPPED)}handleRemoteVolumeChange(e){var t,s;const r=this.params.output.volume$.getValue(),a={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(s=e.muted)!==null&&s!==void 0?s: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:s}=this.params.connection;t.currentTime=e,s.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const s=this.params.source;let r,a,n;switch(e){case b.MPEG:{const l=s[e];P(l);const c=HS(Object.keys(l));P(c);const h=l[c];P(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case b.HLS:case b.HLS_ONDEMAND:{const l=s[e];P(l),r=l.url,a="application/x-mpegurl",n=chrome.cast.media.StreamType.BUFFERED;break}case b.DASH_SEP:case b.DASH_ONDEMAND:case b.DASH_WEBM:{const l=s[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case b.DASH_LIVE_CMAF:{const l=s[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case b.HLS_LIVE:case b.HLS_LIVE_CMAF:{const l=s[e];P(l),r=ei(l.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case b.DASH:case b.DASH_LIVE:case b.WEB_RTC_LIVE:{const l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:D.VIDEO_PIPELINE,message:l,thrown:c}),c}case b.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return x(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 s=this.params.desiredState.seekState.getState();return s.state===H.Applying||s.state===H.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:s.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),s=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(qu(vo).subscribe(()=>a(`timeout(${vo})`)))});Fs(Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===H.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})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}class mo{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}removeEventListener(e,t){if(!(e in this.listeners))return;const s=this.listeners[e];for(let r=0,a=s.length;r<a;r++)if(s[r].callback===t){s.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let r=0,a=s.length;r<a;r++){const n=s[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 ou extends mo{constructor(){super(),this.listeners||mo.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 du=class{constructor(){Object.defineProperty(this,"signal",{value:new ou,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 s=e;if(s===void 0)if(typeof document=="undefined")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch(r){s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(du.prototype[Symbol.toStringTag]="AbortController",ou.prototype[Symbol.toStringTag]="AbortSignal");function uu(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function JS(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!uu({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(d,l){let c;l&&l.signal&&(c=l.signal,delete l.signal);const h=new t(d,l);return c&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),h},a.prototype=t.prototype);const n=e;return{fetch:(u,d)=>{const l=a&&a.prototype.isPrototypeOf(u)?u.signal:d?d.signal:void 0;if(l){let c;try{c=new DOMException("Aborted","AbortError")}catch(f){c=new Error("Aborted"),c.name="AbortError"}if(l.aborted)return Promise.reject(c);const h=new Promise((f,m)=>{l.addEventListener("abort",()=>m(c),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([h,n(u,d)])}return n(u,d)},Request:a}}const Vs=uu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),lu=Vs?JS({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ti=Vs?lu.fetch:window.fetch;Vs?lu.Request:window.Request;const Dt=Vs?du:window.AbortController,bi=i=>i.range?i.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class wi{constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){var t;const{url:s}=e.request,r=(t=this.dashJsRequestQueue.get(s))!==null&&t!==void 0?t:[];r.push(e),this.dashJsRequestQueue.set(s,r)}executeNextRequests(){return ue(this,void 0,void 0,function*(){for(const[e,t]of this.dashJsRequestQueue.entries()){const s=this.activeRequests.get(e);if(s){t.length&&this.onBigRequestProgress(s);const r=t[0];if(!r||!r.request.range)continue;const[a,n]=bi(r.request);if(a>=s.from&&n<=s.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:s}=e,r=((t=this.dashJsRequestQueue.get(s.url))!==null&&t!==void 0?t:[]).includes(e),a=this.activeRequests.get(s.url);r&&a&&a.abortController.abort()}else for(const{abortController:s}of this.activeRequests.values())s.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const s=t.map(bi),r=s[0][0];let a=s[0][1];for(let h=1;h<s.length&&a<this.params.minDataSize;h++){const f=s[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 Dt,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,m;throw(m=(f=this.params).onError)===null||m===void 0||m.call(f,{id:"BigRequestParsing",category:D.PARSER,message:"Error parsing response data",thrown:h}),h};return ti(o,{signal:d}).then(h=>{var f,m,p;if(l.response=h,!h.ok||!h.body){this.onBigRequestError(l);return}const[S,g]=h.body.tee();(m=(f=this.params).onDownloadStream)===null||m===void 0||m.call(f,g);const T=S.getReader(),I=parseInt((p=h.headers.get("Content-Length"))!==null&&p!==void 0?p:"",10)||a-r+1;l.data=new ArrayBuffer(I);const w=new Uint8Array(l.data),A=({done:N,value:X})=>ue(this,void 0,void 0,function*(){N?this.onBigRequestProgress(l):X&&(w.set(X,l.loaded),l.loaded+=X.byteLength,this.onBigRequestProgress(l),yield T==null?void 0:T.read().then(A,wi.suppressStreamErrors).catch(c))});T==null||T.read().then(A,wi.suppressStreamErrors).catch(c)},wi.suppressAbort).catch(h=>this.onBigRequestError(l,h)),l}onBigRequestProgress({url:e,from:t,to:s,loaded:r,data:a,response:n}){var o,u,d,l,c,h,f,m;if(!this.activeRequests.has(e)||!a)return;const p=(o=this.dashJsRequestQueue.get(e))!==null&&o!==void 0?o:[];for(const S of p){const{request:g}=S,[T,I]=bi(g),w=T>=t&&I<=t+r,A=t>=T&&t+r<I,N=a.slice(T-t,Math.min(I-t+1,r));if((w||A)&&(g.requestStartDate=(u=g.requestStartDate)!==null&&u!==void 0?u:new Date,g.firstByteDate=(d=g.firstByteDate)!==null&&d!==void 0?d:new Date,g.bytesLoaded=N.byteLength,g.bytesTotal=s-t),w){g.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[]).filter(Y=>Y!==S)),(c=S.success)===null||c===void 0||c.call(S,N,"",e);const X=n?Array.from(n.headers.entries()).map(([Y,F])=>`${Y}: ${F}`).join(`\r
7
+ `):"";(h=this.dashMetrics)===null||h===void 0||h.addHttpRequest(g,e,(f=n==null?void 0:n.status)!==null&&f!==void 0?f:200,X,[])}else A&&((m=S.progress)===null||m===void 0||m.call(S,{loaded:r,total:s-t,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:t,to:s},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]=bi(l.request);(c>=t&&c<s||h>t&&h<=s)&&((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:s}){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]=bi(o.request);(u>=t&&u<s||d>t&&d<=s)&&((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 ws{constructor(e,t,s){this.baseLoader=e,this.config=s,this.bigRequest=t,t.setMetrics(s.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(ws.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;ws.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const KS=(i,e)=>t=>({create:s=>{const r=i(t).create(s);return new ws(r,e,s)}}),XS=(i,e)=>{const t=new wi(e);return i.extend("SchemeLoaderFactory",function(){const{parent:s}=this,r=s.getLoader;return{getLoader:a=>{const n=r(a);return KS(n,t)}}},!0),()=>t.destroy()};var ZS=i=>{let e,t=!1,s=!1;i.on("playbackTimeUpdated",({timeToEnd:r})=>{s=r<=3,t&&s&&(e==null||e())}),i.extend("MediaSourceController",function(){const{parent:r}=this,a=r.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>a(n),t&&s&&(e==null||e())}}},!0)},eg=i=>{const e=new y(1/0),t=new O,s=new y(void 0),r=new y(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},u=l=>{var c,h,f,m,p;const S=Bi(l.getAllResponseHeaders().trim().split(/[\n\r]+/).map(I=>I.split(": ")));if("x-playback-duration"in S||"x-playback-duration-millis"in S){const I=parseInt((c=l.getResponseHeader("X-Playback-Duration"))!==null&&c!==void 0?c:"",10),w=parseInt((h=l.getResponseHeader("X-Playback-Duration-Millis"))!==null&&h!==void 0?h:"",10),A=(f=w!=null?w:I*1e3)!==null&&f!==void 0?f:NaN;_(A)&&!isNaN(A)&&e.next(A)}const g=(m=S["x-delivery-type"])!==null&&m!==void 0?m:ki.HTTP1,T=(p={1:!0,0:!1}[S["x-reused"]])!==null&&p!==void 0?p:void 0;s.next(g),r.next(T)},d=l=>{l.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return i.extend("XHRLoader",function(){const{parent:l}=this,c=l.load.bind(l);return{load:function(h){if(h.request.type==="MPD"){const f=h.onload,m=h.progress;h.onload=function(...p){return u(this),f(...p)},h.progress=function(...p){return d(this),m(...p)},o()}return c(h)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:s}},ii=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},tg=i=>i.extend("RequestModifier",()=>({modifyRequestURL:ii}),!0),ig=i=>{i.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:s=>{if(s.request&&s.request.range){const[r,a]=s.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(s.request.url,location.href);n.searchParams.append("bytes",`${r}-${a}`),s.request.url=n.toString(),s.request.range=void 0}t(s)}}},!0)};const et=(i,e,t,{equal:s=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=i.getState(),o=e(),u=K(r),d=new se;return r&&d.add(r.subscribe(l=>{const c=i.getState();s(l,c)&&i.setState(l)},a)),s(o,n)||(t(n),u&&i.setState(n)),d.add(i.stateChangeStarted$.subscribe(l=>{t(l.to),u&&i.setState(l.to)},a)),d},Ut=(i,e,t)=>et(e,()=>i.loop,s=>{_(s)&&(i.loop=s)},{onError:t}),pt=(i,e,t,s)=>et(e,()=>({muted:i.muted,volume:i.volume}),r=>{_(r)&&(i.muted=r.muted,i.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:s}),Et=(i,e,t,s)=>et(e,()=>i.playbackRate,r=>{_(r)&&(i.playbackRate=r)},{changed$:t,onError:s}),sg=i=>["__",i.language,i.label].join("|"),rg=(i,e)=>{if(i.id===e)return!0;const[t,s,r]=e.split("|");return i.language===s&&i.label===r};class it{constructor(){this.available$=new O,this.current$=new y(void 0),this.error$=new O,this.subscription=new se,this.externalTracks=new Map}connect(e,t,s){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(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(et(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{_(a)&&this.setExternal(a)},{equal:(a,n)=>_(a)&&_(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe($(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(et(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(et(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){P(this.video);const{textTracks:e}=this.video;this.subscription.add(U(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();this.select(s)})),this.subscription.add(L(U(e,"addtrack"),U(e,"removetrack"),Oe(["init"])).pipe($(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),me((s,r)=>s.length===r.length&&s.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(L(U(e,"change"),Oe(["init"])).pipe($(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),$(s=>s&&this.htmlTextTrackToITextTrack(s).id),me()).subscribe(this.current$));const t=s=>{var r,a;return this.applyCueSettings((a=(r=s.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(U(e,"addtrack").subscribe(s=>{var r,a;(r=s.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=s.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(U(e,"removetrack").subscribe(s=>{var r;(r=s.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const s of Array.from(e)){const r=s;_(t.align)&&(r.align=t.align),_(t.position)&&(r.position=t.position),_(t.size)&&(r.size=t.size),_(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){P(this.video);const t=[...this.video.textTracks];return e?t:t.filter(it.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:s}=e,r=e.id!==""?e.id:sg(e);return this.externalTracks.has(r)?{id:r,type:"external",language:t,label:s,url:this.externalTracks.get(r).url}:{id:r,type:"internal",language:t,label:s}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.id===""&&e.label===""&&e.language==="")}setExternal(e){e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks.keys()).filter(t=>!e.find(s=>s.id===t)).forEach(t=>this.detach(t))}select(e){P(this.video);for(const t of this.htmlTextTracksAsArray(!0))_(e)&&rg(t,e)?t.mode="showing":t.mode="disabled"}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){P(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),this.externalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){P(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),s=>s.getAttribute("id")===e);t&&this.video.removeChild(t),this.externalTracks.delete(e)}}var vt=i=>{const e=document.createElement("video");return e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i.appendChild(e),e};class Ba{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()}}var cu=()=>{const{userAgent:i}=window.navigator;return!/chrome/i.test(i)&&/webkit|safari|khtml/i.test(i)};const la=3;class ag{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,s=this._source.buffered.length;t<s;t++){let r=this._source.buffered.start(t);const a=this._source.buffered.end(t);r>e&&r-e<la&&(r=e),this._buffer.push({from:r,to:a,i:t})}return this._buffer.sort(function(t,s){return t.from-s.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const s=this.getNext(e);if(s&&s.from-e.to<(t||la))return s}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,s){this._buffer.forEach(({from:r,to:a})=>{const n=r>=e&&r<t,o=a>=e&&a<t;n&&o||(n?s(t,a):o?s(r,e):r<e&&a>t?(s(t,a),s(r,e)):s(r,a))})}destroy(){this._buffer=[]}}var hu=(i,e,t=la)=>{let s=0,r=0;for(let a=0;a<i.length;a++){const n=i.start(a),o=i.end(a);if(n<=e&&e<=o){if(s=n,r=o,!t)return{from:s,to:r};for(let u=a-1;u>=0;u--)i.end(u)+t>=s&&(s=i.start(u));for(let u=a+1;u<i.length;u++)i.start(u)-t<=r&&(r=i.end(u))}}return{from:s,to:r}};const ng=50,og=i=>i.webkitAudioDecodedByteCount!==void 0?!!i.webkitAudioDecodedByteCount:i.mozHasAudio!==void 0?i.mozHasAudio:i.audioTracks?!!i.audioTracks.length:!0,mt=i=>{const e=m=>U(i,m).pipe(Ot(void 0)),s=L(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(m=>U(i,m))).pipe($(m=>m.type==="ended"?i.readyState<2:i.readyState<3),me()),r=L(U(i,"progress"),U(i,"timeupdate")).pipe($(()=>hu(i.buffered,i.currentTime))),a=cu()?dt({play:e("play").pipe(ye()),playing:e("playing")}).pipe(Ot(void 0)):e("playing"),n=U(i,"playing").pipe(Ve(ng),$(()=>og(i))),o=U(i,"volumechange").pipe($(()=>({muted:i.muted,volume:i.volume}))),u=U(i,"ratechange").pipe($(()=>i.playbackRate)),d=U(i,"error").pipe(j(()=>Boolean(i.error||i.played.length)),$(()=>{var m;const p=i.error;return{id:p?`MediaError#${p.code}`:"HtmlVideoError",category:D.VIDEO_PIPELINE,message:p?p.message:"Error event from HTML video element",thrown:(m=i.error)!==null&&m!==void 0?m:void 0}})),l=U(i,"timeupdate").pipe($(()=>i.currentTime)),c=new O,h=.3;let f;return l.subscribe(m=>{i.loop&&_(f)&&_(m)&&f>=i.duration-h&&m<=h&&c.next(f),f=m}),{playing$:a,pause$:e("pause").pipe(j(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:U(i,"durationchange").pipe($(()=>i.duration)),isBuffering$:s,currentBuffer$:r,volumeState$:o,isAudioAvailable$:n,playbackRateState$:u}},Ma=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var dg=We,ug=xs,lg=$a,cg=Ea;dg({target:"Array",proto:!0},{at:function(e){var t=ug(this),s=lg(t),r=cg(e),a=r>=0?r:s+r;return a<0||a>=s?void 0:t[a]}});var hg=Na,fg=hg("Array","at"),pg=fg,vg=pg,mg=vg,Sg=mg,at=Sg;let Ua=!1,nt={};const gg=i=>{Ua=i},bg=()=>{nt={}},yg=i=>{i(nt)},as=(i,e)=>{var t;Ua&&(nt.meta=(t=nt.meta)!==null&&t!==void 0?t:{},nt.meta[i]=e)};class Ze{constructor(e){this.name=e}next(e){var t,s;if(!Ua)return;nt.series=(t=nt.series)!==null&&t!==void 0?t:{};const r=(s=nt.series[this.name])!==null&&s!==void 0?s:[];r.push([Date.now(),e]),nt.series[this.name]=r}}const Tg=new Ze("best_bitrate"),Eg=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class $g{constructor(){this.history={}}recordSelection(e){this.history[e.id]=pe()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Fi=(i,{container:e,throughput:t,tuning:s,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:d})=>{var l,c,h,f;const m=s.usePixelRatio&&(l=window.devicePixelRatio)!==null&&l!==void 0?l:1,p=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*m*s.containerSizeFactor,height:e.height*m*s.containerSizeFactor},S=p&&Mt(p),g=s.considerPlaybackRate&&_(o)?o:1,T=i.filter(V=>!As(V.quality)).sort((V,B)=>Ss(V.quality,B.quality)?-1:1),I=(c=at(T,-1))===null||c===void 0?void 0:c.quality,w=(h=at(T,0))===null||h===void 0?void 0:h.quality,A=K(r)||_(r.min)&&_(r.max)&&Ai(r.max,r.min)||_(r.min)&&w&&Ss(r.min,w)||_(r.max)&&I&&Ai(r.max,I),N=g*Eg(n!=null?n:.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),Y=T.filter(V=>{const B=S?Ai(V.quality,S):!0,ie=_(t)&&isFinite(t)&&_(V.bitrate)?t-a>=V.bitrate*N:!0,ce=s.lazyQualitySwitch&&_(s.minBufferToSwitchUp)&&u&&!As(u.quality)&&(n!=null?n:0)<s.minBufferToSwitchUp&&Ss(V.quality,u.quality),Se=A||(K(r.max)||VS(V.quality,r.max))&&(K(r.min)||FS(V.quality,r.min));return B&&ie&&!ce&&Se})[0];Y&&Y.bitrate&&Tg.next(Y.bitrate);const F=(f=Y!=null?Y:T[Math.ceil((T.length-1)/2)])!==null&&f!==void 0?f:i[0],Z=F&&d&&d.history[F.id]&&pe()-d.history[F.id]<=s.trackCooldown&&(!d.last||F.id!==d.last.id);if(F!=null&&F.id&&d&&!Z&&d.recordSelection(F),Z&&(d!=null&&d.last)){const V=d.last;return d==null||d.recordSwitch(V),V}return d==null||d.recordSwitch(F),F};var Re=i=>new URL(i).hostname;const Ag=300,_s=(i,e=Ag)=>new Ii(t=>{const{width:s,height:r}=i.getBoundingClientRect();if(t.next({width:s,height:r}),!window.ResizeObserver)return;const a=new ResizeObserver(Wu(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(i),()=>a.disconnect()}),St=i=>{try{i.pause(),i.playbackRate=0,i.removeAttribute("src"),i.load(),i.remove()}catch(e){console.error(e)}},wg=5e3,yi={};var W;(function(i){i.DOWNLOADING_LIB="downloading_lib",i.STOPPED="stopped",i.STREAM_INITIALIZED="stream_initialized",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(W||(W={}));const be=(i,e)=>new Ii(t=>{const s=r=>t.next(r);return i.on(e,s),()=>i.off(e,s)});class So{constructor(e){this.subscription=new se,this.videoState=new le(W.DOWNLOADING_LIB),this.textTracksManager=new it,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new y(void 0),this.maxSeekBackTime$=new y(1/0),this.availableFrom$=new y(void 0),this.elementSize$=new y(void 0),this.liveOffset=new Ba,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState(),n=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===W.DOWNLOADING_LIB||t===W.STREAM_INITIALIZED))switch((r==null?void 0:r.to)!==v.PAUSED&&a.state===H.Requested&&t!==W.STOPPED&&s!==v.STOPPED&&(n?this.seek(a.position-this.liveOffset.getTotalPausedTime()):this.seek(a.position)),s){case v.STOPPED:{switch(t){case W.STOPPED:break;case W.PLAYING:case W.PAUSED:case W.READY:this.stop();break;default:x(t)}break}case v.READY:{switch(t){case W.STOPPED:this.prepare();break;case W.PLAYING:case W.PAUSED:case W.READY:break;default:x(t)}break}case v.PLAYING:{switch(t){case W.PLAYING:break;case W.PAUSED:n&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case W.READY:this.play();break;case W.STOPPED:this.prepare();break;default:x(t)}break}case v.PAUSED:{switch(t){case W.PLAYING:this.pause(),this.liveOffset.pause();break;case W.PAUSED:break;case W.READY:this.videoState.setState(W.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED);break;case W.STOPPED:this.prepare();break;default:x(t)}break}default:x(s)}},this.video=vt(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(Re(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},s=window.setTimeout(()=>t("timeout"),wg);Fs(import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(yi.MediaPlayer=r.MediaPlayer,yi.Debug=r.Debug,this.init())},t),()=>{window.clearTimeout(s),e=!0})}init(){P(yi.MediaPlayer,"dashjs not loaded"),P(yi.Debug,"dashjs not loaded"),this.player=yi.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?Ma(t.frameRate+""):void 0),!0)),(this.params.format===b.DASH_WEBM||this.params.format===b.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=XS(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&&ig(this.player),ZS(this.player),this.params.tuning.requestQuick&&tg(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(W.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,s=p=>{e.error$.next({id:"DashIFProvider",category:D.WTF,message:"DashIFProvider internal logic error",thrown:p})},r=(p,S)=>this.subscription.add(p.subscribe(S,s));r(_s(this.video),this.elementSize$),r(be(this.player,"error").pipe($(p=>{const S=typeof p.error=="object"?p.error.code:p.error,g=typeof p.error=="object"?p.error.message:void 0;return{id:`DashJS#${S}`,message:g}})),e.error$),r(be(this.player,"playbackError").pipe($(p=>({id:"DashJSPlayback",message:p.error}))),e.error$);const a=be(this.player,"qualityChangeRendered").pipe(j(({mediaType:p})=>p==="video"),$(({newQuality:p})=>{var S;return(S=this.videoTracks.find(({bitrateInfo:g})=>g.qualityIndex===p))===null||S===void 0?void 0:S.track}));a.pipe(j(_)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(j(({to:p})=>p===W.STREAM_INITIALIZED),ye()).subscribe(()=>{this.subscription.add(et(t.videoTrack,()=>{var p,S;const g=this.player.getQualityFor("video");return(S=(p=this.videoTracks.find(({bitrateInfo:T})=>T.qualityIndex===g))===null||p===void 0?void 0:p.track)===null||S===void 0?void 0:S.id},p=>{var S;if(K(p))return;const g=(S=this.videoTracks.find(({track:T})=>T.id===p))===null||S===void 0?void 0:S.bitrateInfo;g&&this.player.setQualityFor("video",g.qualityIndex)},{changed$:a.pipe($(p=>p==null?void 0:p.id)),onError:s}))},s)),this.subscription.add(et(t.autoVideoTrackSwitching,()=>{var p,S,g;return(g=(S=(p=this.player.getSettings().streaming)===null||p===void 0?void 0:p.abr)===null||S===void 0?void 0:S.autoSwitchBitrate)===null||g===void 0?void 0:g.video},p=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:p}}}}),{onError:s})),r(be(this.player,"bufferStateChanged").pipe(j(({mediaType:p})=>p==="video"),$(({state:p})=>p==="bufferStalled")),e.isBuffering$),r(be(this.player,"fragmentLoadingStarted"),({mediaType:p,request:{url:S}})=>{var g,T;const I=this.player.getDashMetrics(),w=I.getLatestFragmentRequestHeaderValueByID(p,"X-Reused"),A=(g=I.getLatestFragmentRequestHeaderValueByID(p,"X-Delivery-Type"))!==null&&g!==void 0?g:ki.HTTP1,N=(T={1:!0,0:!1}[w])!==null&&T!==void 0?T:void 0;this.params.output.httpConnectionType$.next(A),this.params.output.httpConnectionReused$.next(N),e.hostname$.next(Re(S))}),r(be(this.player,"streamInitialized"),({streamInfo:{duration:p,manifestInfo:{isDynamic:S,availableFrom:g}}})=>{this.isLive$.next(S),this.availableFrom$.next(g.getTime()),S||e.duration$.next(p),this.videoTracks=[];const T=this.player.getQualityFor("video");let I;for(const w of this.player.getBitrateInfoListFor("video")){const A=w.qualityIndex.toString(10),N=Mt(w),X=w.bitrate/1e3,Y={width:w.width,height:w.height},F=this.frameRatesByFrameHeight[w.height];if(N){const Z={id:A,quality:N,bitrate:X,size:Y,fps:F};this.videoTracks.push({track:Z,bitrateInfo:w}),w.qualityIndex===T&&(I=Z)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:w})=>w)),I&&e.currentVideoTrack$.next(I),this.videoState.setState(W.STREAM_INITIALIZED),this.videoState.startTransitionTo(W.READY)}),r(be(this.player,"fragmentLoadingCompleted"),({request:p})=>{if(!p.requestEndDate||!p.firstByteDate||!p.bytesLoaded)return;const S=p.requestEndDate.getTime()-p.firstByteDate.getTime(),g=p.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(g,S)}),r(L(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const p=this.params.dependencies.throughputEstimator.throughput$.getValue(),S=Fi(this.videoTracks.map(({track:T})=>T),{container:this.elementSize$.getValue(),throughput:p,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),g=this.videoTracks.find(({track:T})=>T===S);g!=null&&g.bitrateInfo&&this.player.setQualityFor("video",g==null?void 0:g.bitrateInfo.qualityIndex,!1)}),r(dt({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(j(_))}).pipe(j(({isLive:p})=>p),$(({maxSeekBackTime:p})=>-p/1e3)),this.params.output.duration$);const n=be(this.player,"playbackTimeUpdated").pipe($(({time:p})=>p!=null?p:0));r(dt({availableFrom:this.availableFrom$.pipe(j(_)),currentTime:n}),({availableFrom:p,currentTime:S})=>this.params.output.liveTime$.next(p+S*1e3)),r(n.pipe(j(()=>this.isLive$.getValue()===!1)),e.position$),r(be(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),r(be(this.player,"playbackEnded"),e.endedEvent$),r(be(this.player,"playbackProgress").pipe($(()=>hu(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(be(this.player,"playbackPlaying"),()=>{this.videoState.setState(W.PLAYING),R(t.playbackState,v.PLAYING)}),r(be(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(W.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(be(this.player,"playbackPaused"),()=>{this.videoState.setState(W.PAUSED),R(t.playbackState,v.PAUSED)}),r(be(this.player,"canPlay"),()=>{var p;((p=this.videoState.getTransition())===null||p===void 0?void 0:p.to)===W.READY&&this.videoState.setState(W.READY)}),r(this.isLive$,e.isLive$),r(_s(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const o=L(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ve(0));r(o,this.syncPlayback);const{playbackDuration$:u,ping$:d,connectionType$:l,connectionReused$:c}=eg(this.player);r(l,this.params.output.httpConnectionType$),r(c,this.params.output.httpConnectionReused$),r(u,this.maxSeekBackTime$),r(d.pipe(ye()),e.firstBytesEvent$),r(be(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(dt({isLive:this.isLive$,isShort:e.duration$.pipe($(p=>p<60))}),({isLive:p,isShort:S})=>{const g=!p&&S;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:g}}})}),r(n.pipe(j(p=>p>this.params.tuning.insufficientBufferRuleMargin),ye()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(be(this.player,"manifestLoaded").pipe(ye()).subscribe(()=>{this.subscription.add(be(this.player,"playbackPlaying").pipe(ye(),Ot(void 0)).subscribe(e.firstFrameEvent$,s))},s)),this.subscription.add(Ut(this.video,t.isLooped,s));const{volumeState$:h,looped$:f,playbackRateState$:m}=mt(this.video);this.subscription.add(pt(this.video,t.volume,h,s)),this.subscription.add(h.subscribe(e.volume$,s)),this.subscription.add(f.subscribe(e.loopedEvent$)),this.subscription.add(Et(this.video,t.playbackRate,m,s))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(W.STOPPED),R(this.params.desiredState.playbackState,v.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(W.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3);const r=ei(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Zt.PLAYBACK_SHIFT);this.player.attachSource(r)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(W.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(W.PAUSED),this.video.pause()}destroy(){var e,t;this.subscription.unsubscribe(),this.textTracksManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(s){}St(this.video),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var Vi=i=>{switch(i){case"mobile":return ne.Q_144P;case"lowest":return ne.Q_240P;case"low":return ne.Q_360P;case"sd":case"medium":return ne.Q_480P;case"hd":case"high":return ne.Q_720P;case"fullhd":case"full":return ne.Q_1080P;case"quadhd":case"quad":return ne.Q_1440P;case"ultrahd":case"ultra":return ne.Q_2160P}};const go=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))};var $t=i=>ue(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(!go(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(s){return go(s)&&(i.muted=!1,console.warn(s)),!1}}return!0});function Ae(){return pe()}function fu(i){return Ae()-i}function bo(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),s=/^([a-z]+:)?\/\//i,r=n=>s.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 _g(i,e,t){const s=(...r)=>{t.apply(null,r),i.removeEventListener(e,s)};i.addEventListener(e,s)}function gs(i,e,t,s){const r=window.XMLHttpRequest;let a,n,o,u=!1,d=0,l,c,h=!1,f="arraybuffer",m=7e3,p=2e3,S=()=>{if(u)return;P(l);const B=fu(l);let ie;if(B<p){ie=p-B,setTimeout(S,ie);return}p*=2,p>m&&(p=m),n&&n.abort(),n=new r,N()};const g=B=>(a=B,V),T=B=>(c=B,V),I=()=>(f="json",V),w=()=>{if(!u){if(--d>=0){S(),s&&s();return}u=!0,c&&c(),t&&t()}},A=B=>(h=B,V),N=()=>{l=Ae(),n=new r,n.open("get",i);let B=0,ie,ce=0;const Se=()=>(P(l),Math.max(l,Math.max(ie||0,ce||0)));if(a&&n.addEventListener("progress",k=>{const G=Ae();a.updateChunk&&k.loaded>B&&(a.updateChunk(Se(),k.loaded-B),B=k.loaded,ie=G)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>w())),n.addEventListener("load",()=>{if(u)return;P(n);const k=n.status;if(k>=200&&k<300){if(n.response.byteLength&&a){const G=n.response.byteLength-B;G&&a.updateChunk&&a.updateChunk(Se(),G)}c&&c(),n&&e(n.response)}else w()}),n.addEventListener("error",()=>{w()}),h){const k=()=>{P(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(ce=Ae(),n.removeEventListener("readystatechange",k))};n.addEventListener("readystatechange",k)}return n.responseType=f,n.send(),V},V={withBitrateReporting:g,withParallel:A,withJSONResponse:I,withRetryCount:B=>(d=B,V),withRetryInterval:(B,ie)=>(_(B)&&(p=B),_(ie)&&(m=ie),V),withTimeout:B=>(o=B,V),withFinally:T,send:N,abort:()=>{n&&(n.abort(),n=void 0),u=!0,c&&c()}};return V}const kg=100,Pg=2e3,Rg=500;let Ig=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,s){return{start:e,end:t,bytes:s}}_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-Rg;if(t-e>Pg){let s=0,r=0;for(;this.intervals.length>0;){const a=this.intervals[0];if(a.end<=t)s+=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;s+=n;const u=a.bytes*n/o;r+=u,a.start=t,a.bytes-=u}}}if(r>0&&s>0){const a=r*8/(s/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(s)} 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,s){return this.intervals.push(this._createInterval(e,t,s)),this._joinIntervals(),this.intervals.length>kg&&(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 Dg{constructor(e,t,s,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=s,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 s=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()-s,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=gs(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 s=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),s>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),s),!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,s,r){const a={};return a.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=s,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}`),s(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=s,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 ns=1e4,os=3,Cg=300,Og=2e3,Lg=6e4,xg=10,Ng=1,Bg=500;class Mg{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 Ig(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=bo(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let s=0;s<this.manifest.length;++s)if(t=this.manifest[s],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=bo(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 s=e.buffered.length;return s!==0&&(t=e.buffered.end(s-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 s;Boolean(e.error)&&!this.destroyed&&(t(`Video element error: ${(s=e.error)===null||s===void 0?void 0:s.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const s=this._getBufferSizeSec();!this.paused&&s<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(s+.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,s=t.buffered.length;let r;s!==0&&(r=t.buffered.start(s-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let s,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):(!s||s.bitrate>a.bitrate)&&(s=a));return r||s}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:s,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,s("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=()=>{_g(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 Dg(os,ns,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:s,playerCallback:r}=this.params;let a=!1,n=null,o=null,u=null,d=null,l=!1;const c=()=>{const w=a&&(!l||l===this.rep);return w||t("Not running!"),w},h=(w,A,N)=>{u&&u.abort(),u=gs(this.urlResolver.resolve(w,!1),A,N,()=>this._retryCallback()).withTimeout(ns).withBitrateReporting(this.bitrateSwitcher).withRetryCount(os).withFinally(()=>{u=null}).send()},f=(w,A,N)=>{P(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(w,!1),A,N,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},m=w=>{const A=s.playbackRate;s.playbackRate!==w&&(t(`Playback rate switch: ${A}=>${w}`),s.playbackRate=w)},p=w=>{this.lowLatency=w,t(`lowLatency changed to ${w}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let w=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}const N=Ae()-1e4;let X=0;for(let F=0;F<this.bufferStates.length;F++){const Z=this.bufferStates[F];w=Math.min(w,Z.buf),Z.ts<N&&X++}this.bufferStates.splice(0,X),t(`update playback rate; minBuffer=${w} drop=${X} jitter=${this.sourceJitter}`);let Y=w-Ng;this.sourceJitter>=0?Y-=this.sourceJitter/2:this.sourceJitter-=1,Y>3?m(1.15):Y>1?m(1.1):Y>.3?m(1.05):m(1)}},g=w=>{let A;const N=()=>A&&A.start?A.start.length:0,X=k=>A.start[k]/1e3,Y=k=>A.dur[k]/1e3,F=k=>A.fragIndex+k,Z=(k,G)=>({chunkIdx:F(k),startTS:X(k),dur:Y(k),discontinuity:G}),V=()=>{let k=0;if(A&&A.dur){let G=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,oe=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ve=G;this.sourceJitter>1&&(ve+=this.sourceJitter-1);let ge=A.dur.length-1;for(;ge>=0&&(ve-=A.dur[ge],!(ve<=0));--ge);k=Math.min(ge,A.dur.length-1-oe),k=Math.max(k,0)}return Z(k,!0)},B=k=>{const G=N();if(!(G<=0)){if(_(k)){for(let oe=0;oe<G;oe++)if(X(oe)>k)return Z(oe)}return V()}},ie=k=>{const G=N(),oe=k?k.chunkIdx+1:0,ve=oe-A.fragIndex;if(!(G<=0)){if(!k||ve<0||ve-G>xg)return t(`Resync: offset=${ve} bChunks=${G} chunk=`+JSON.stringify(k)),V();if(!(ve>=G))return Z(oe-A.fragIndex,!1)}},ce=(k,G,oe)=>{d&&d.abort(),d=gs(this.urlResolver.resolve(k,!0,this.lowLatency),G,oe,()=>this._retryCallback()).withTimeout(ns).withRetryCount(os).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(k,G)=>{ce(w,oe=>{if(!c())return;A=oe;const ve=Boolean(A.lowLatency);ve!==this.lowLatency&&p(ve);let ge=0;for(let Ie=0;Ie<A.dur.length;++Ie)ge+=A.dur[Ie];ge>0&&(P(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,k(B(G))},()=>this._handleNetworkError())},nextChunk:ie}},T=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),P(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:w=>{const{videoElement:A,logger:N}=this.params;let X=g(e.jidxUrl),Y,F,Z,V,B=0,ie,ce,Se;const k=()=>{ie&&(clearTimeout(ie),ie=void 0);const ee=Math.max(Bg,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ee=B+ee,Pe=Ae(),xe=Math.min(1e4,Ee-Pe);B=Pe;const At=()=>{d||c()&&X.seek(()=>{c()&&(B=Ae(),G(),k())})};xe>0?ie=window.setTimeout(()=>{this.paused?k():At()},xe):At()},G=()=>{let ee;for(;ee=X.nextChunk(V);)V=ee,Qe(ee);const Ee=X.nextChunk(Z);if(Ee){if(Z&&Ee.discontinuity){N("Detected discontinuity; restarting playback"),this.paused?k():(T(),this._initPlayerWith(e));return}Ie(Ee)}else k()},oe=(ee,Ee)=>{if(!c()||!this.sourceBuffer)return;let Pe,xe,At;const Je=gt=>{window.setTimeout(()=>{c()&&oe(ee,Ee)},gt)};if(this.sourceBuffer.updating)N("Source buffer is updating; delaying appendBuffer"),Je(100);else{const gt=Ae(),wt=A.currentTime;!this.paused&&A.buffered.length>1&&ce===wt&&gt-Se>500&&(N("Stall suspected; trying to fix"),this._fixupStall()),ce!==wt&&(ce=wt,Se=gt);const di=this._getBufferSizeSec();if(di>30)N(`Buffered ${di} seconds; delaying appendBuffer`),Je(2e3);else try{this.sourceBuffer.appendBuffer(ee),this.videoPlayStarted?(this.bufferStates.push({ts:gt,buf:di}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ee&&Ee()}catch(Ft){if(Ft.name==="QuotaExceededError")N("QuotaExceededError; delaying appendBuffer"),At=this.sourceBuffer.buffered.length,At!==0&&(Pe=this.sourceBuffer.buffered.start(0),xe=wt,xe-Pe>4&&this.sourceBuffer.remove(Pe,xe-3)),Je(1e3);else throw Ft}}},ve=()=>{F&&Y&&(N([`Appending chunk, sz=${F.byteLength}:`,JSON.stringify(Z)]),oe(F,function(){F=null,G()}))},ge=ee=>e.fragUrlTemplate.replace("%%id%%",ee.chunkIdx),Ie=ee=>{c()&&f(ge(ee),(Ee,Pe)=>{if(c()){if(Pe/=1e3,F=Ee,Z=ee,n=ee.startTS,Pe){const xe=Math.min(10,ee.dur/Pe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*xe:xe}ve()}},()=>this._handleNetworkError())},Qe=ee=>{c()&&(P(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ge(ee),!1)))},oi=ee=>{c()&&(e.cachedHeader=ee,oe(ee,()=>{Y=!0,ve()}))};a=!0,X.seek(ee=>{if(c()){if(B=Ae(),!ee){k();return}V=ee,!K(w)||ee.startTS>w?Ie(ee):(Z=ee,G())}},w),e.cachedHeader?oi(e.cachedHeader):h(e.headerUrl,oi,()=>this._handleNetworkError())},stop:T,getTimestampSec:()=>n},l}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),_(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,P(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),s({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return _(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=c=>{if(!this.autoQuality)return;let h,f,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(f=this._getBufferSizeSec(),m=c/this.bitrate,f>10&&m>.8||f>15&&m>.5||f>20&&m>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},a=(()=>({updateChunk:(h,f)=>{const m=Ae();if(this.chunkRateEstimator.addInterval(h,m,f)){const S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:m-h,speed:S}),!0}},get:()=>{const h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}}))();let n=-1/0,o,u=!0;const d=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(u&&c>o&&fu(n)<3e4)return;s(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,s){this.manifestRequest=gs(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(ns).withRetryCount(os).withRetryInterval(Cg,Og).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;$t(t).then(s=>{s||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,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}`),s({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))},Lg))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var z;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(z||(z={}));const Ug=[z.PAUSED,z.PLAYING,z.READY],Fg=[z.PAUSED,z.PLAYING,z.READY];class Vg{constructor(e){this.subscription=new se,this.videoState=new le(z.STOPPED),this.representations$=new y([]),this.textTracksManager=new it,this.maxSeekBackTime$=new y(1/0),this.zeroTime$=new y(void 0),this.liveOffset=new Ba,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:Mt(c.video),m=c.bitrate/1e3,p=Object.assign({},c.video);if(!f)continue;const S={id:h,quality:f,bitrate:m,size:p};l.push({track:S,representation:c})}this.representations$.next(l),this.params.output.availableVideoTracks$.next(l.map(({track:c})=>c)),((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===z.MANIFEST_READY&&this.videoState.setState(z.MANIFEST_READY);break}case"qualitySwitch":{const d=r.quality,l=(u=this.representations$.getValue().find(({representation:c})=>c===d))===null||u===void 0?void 0:u.track;this.params.output.hostname$.next(new URL(d.headerUrl,this.params.source.url).hostname),_(l)&&this.params.output.currentVideoTrack$.next(l);break}case"bandwidth":{const{size:d,duration:l}=r;this.params.dependencies.throughputEstimator.addRawSpeed(d,l);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{var r;const a=this.videoState.getState(),n=this.videoState.getTransition(),o=this.params.desiredState.playbackState.getState(),u=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${a}; videoTransition: ${JSON.stringify(n)}; desiredPlaybackState: ${o}; seekState: ${JSON.stringify(d)};`}),o===v.STOPPED){a!==z.STOPPED&&(this.videoState.startTransitionTo(z.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(z.STOPPED));return}if(!n){if(Fg.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)!==v.PAUSED&&d.state===H.Requested&&Ug.includes(a)){this.seek(d.position-this.liveOffset.getTotalPausedTime());return}switch(a){case z.STOPPED:this.videoState.startTransitionTo(z.MANIFEST_READY),this.dash.attachSource(ei(this.params.source.url));return;case z.MANIFEST_READY:this.videoState.startTransitionTo(z.READY),this.prepare();break;case z.READY:if(o===v.PAUSED)this.videoState.setState(z.PAUSED);else if(o===v.PLAYING){this.videoState.startTransitionTo(z.PLAYING);const l=u==null?void 0:u.from;l&&l===v.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(z.PAUSED)})}return;case z.PLAYING:o===v.PAUSED&&(this.videoState.startTransitionTo(z.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case z.PAUSED:o===v.PLAYING&&(this.videoState.startTransitionTo(z.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(z.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return x(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})};L(this.videoState.stateChangeStarted$.pipe($(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe($(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=vt(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(Re(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 s=mt(this.video);this.subscription.add(s.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===z.READY&&this.videoState.setState(z.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===H.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(z.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(me(),$(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(dt({zeroTime:this.zeroTime$.pipe(j(_)),position:s.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Ut(this.video,this.params.desiredState.isLooped,t)).add(pt(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(Et(this.video,this.params.desiredState.playbackRate,s.playbackRateState$,t)).add(s.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(s.playing$.subscribe(this.params.output.firstFrameEvent$)).add(s.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:r}})=>{const a=r&&YS(r);this.dash.setMaxAutoQuality(a)})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case z.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(v.STOPPED);break;case z.MANIFEST_READY:case z.READY:((a=this.params.desiredState.playbackState.getTransition())===null||a===void 0?void 0:a.to)===v.READY&&this.params.desiredState.playbackState.setState(v.READY);break;case z.PAUSED:this.params.desiredState.playbackState.setState(v.PAUSED);break;case z.PLAYING:this.params.desiredState.playbackState.setState(v.PLAYING);break;default:return x(r.to)}},t)).add(L(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ve(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),St(this.video)}createLiveDashPlayer(){const e=new Mg({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,s,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=(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||s===void 0?void 0:s.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),l=!d&&_(u)?u:(a=Fi(o.map(({track:h})=>h),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState()}))===null||a===void 0?void 0:a.id,c=(n=o.find(({track:h})=>h.id===l))===null||n===void 0?void 0:n.representation;P(c,"Representations missing"),this.dash.startPlay(c,d),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(l),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(d)}setVideoTrack(e){var t;const s=(t=this.representations$.getValue().find(({track:r})=>r.id===e))===null||t===void 0?void 0:t.representation;P(s,`No such representation ${e}`),this.dash.switchByName(s.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(),s=this.videoState.getState(),r=t===v.PAUSED&&s===z.PAUSED,a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ei(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}}var pu=i=>{var e,t;const s=i.get("X-Delivery-Type"),r=i.get("X-Reused"),a=s===null?ki.HTTP1:(e=s)!==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}},It=(i,e)=>{let t=0;for(let s=0;s<i.length;s++){const r=i.start(s)*1e3,a=i.end(s)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};const Hg=i=>{const e=document.createElement("a");return e.href=i,e.origin},Gg=i=>{const e=document.createElement("a");return e.href=i,e.host};class vu{constructor(e,t=[],s,r,a,n){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=s,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,s,r,a,n,o,u,d;if(P(this._xhr),((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(s=this._errorCb)===null||s===void 0||s.call(this,`Http${(r=this._xhr)===null||r===void 0?void 0:r.status}`,`XHR response code ${(a=this._xhr)===null||a===void 0?void 0:a.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const l=Bi(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(c=>c.split(":").map(h=>h.trim())));(n=this._headersCb)===null||n===void 0||n.call(this,new Headers(l))}else this._xhr.readyState===4?(o=this._completeCb)===null||o===void 0||o.call(this,this._xhr.response):this._xhr.readyState===3&&((u=this._progressCb)===null||u===void 0||u.call(this,this._xhr.response))}catch(l){throw(d=this._errorCb)===null||d===void 0||d.call(this,"XHR2CallbackError",`xhr2 callback threw ${String(l)}`,l),l}},this._xhr.onerror=()=>{var t;(t=this._xhr)===null||t===void 0||t.abort(),this._retryTimeout=window.setTimeout(()=>{var s;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(s=this._errorCb)===null||s===void 0||s.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(Gg(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 ks{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(s){if(s.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",s),s}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,s,r,a,n,o){this.abort(()=>{let u=0;const d=Date.now();let l=0,c=0,h=0;const f=p=>{r(ks._str2ua(p.substr(u))),u=p.length};let m=e.baseURL+"&bytes="+t+"-"+s;this._params.requestQuic&&(m=ii(m)),this._lastXhr=new vu(m,e.failoverHosts,p=>{this._lastXhr=void 0,f(p);const S=Date.now()-d;this._params.onBandwidthChange({size:p.length,duration:S,speed:8*p.length/(S/1e3)}),this._onDashCallback("loading",{size:p.length,done:!0}),a==null||a()},p=>{if(p.length-u>o&&f(p),c===0){c=Date.now();return}h=p.length-l;const S=Date.now()-c;h>=100*1024&&S>=1e3&&(this._params.onBandwidthChange({size:h,duration:S,speed:8*h/(S/1e3)}),h=0,l=p.length,c=Date.now()),this._onDashCallback("loading",{size:p.length,done:!1})},n,(p,S,g)=>this._params.onError(p,S,g))})}abort(e){var t;(t=this._lastXhr)===null||t===void 0||t.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e==null||e()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(s){throw this._params.onError("SourceBuffer","Source Buffer update error",s),s}};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=ks._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 s=new Uint8Array(e.byteLength+t.byteLength);return s.set(e,0),s.set(t,e.byteLength),s}static _str2ua(e){const t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);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 Yg{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)?)?$/,s=(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:s(r==null?void 0:r[2],a),months:s(r==null?void 0:r[3],a),weeks:s(r==null?void 0:r[4],a),days:s(r==null?void 0:r[5],a),hours:s(r==null?void 0:r[6],a),minutes:s(r==null?void 0:r[7],a),seconds:s(r==null?void 0:r[8],a)};return n.hours*3600+n.minutes*60+n.seconds}getRepresentations(){return this._representations}attachSource(e,t){let s=e;this._config.REQUEST_QUIC&&(s=ii(s)),new vu(s,t,r=>{this.attachManifest(r,t,Hg(s))},void 0,r=>{this._params.onResponseHeaders(r)},(r,a,n)=>this._params.onError(r,a,n))}attachManifest(e,t,s){const a=new DOMParser().parseFromString(e,"text/xml").documentElement,n=(d,l)=>{const c=d.attributes.getNamedItem(l);return c?c.value:null};this._duration=this._parseDurationFromISO8601(String(n(a,"mediaPresentationDuration")));const o=[],u=[];if(Array.prototype.forEach.call(a.getElementsByTagName("Representation"),d=>{var l,c,h,f,m,p,S,g,T,I,w,A,N,X,Y,F,Z,V,B;const ie=d.getElementsByTagName("SegmentBase")[0],ce=ie&&n(ie,"indexRange").split("-"),Se=ie&&ie.getElementsByTagName("Initialization")[0],k=Se&&n(Se,"range").split("-");if(!k||!ce){const Qe=d.parentElement;if((Qe==null?void 0:Qe.getAttribute("contentType"))==="text"){const oi=(l=d.getAttribute("id"))!==null&&l!==void 0?l:void 0,ee=(s?s+"/":"")+((m=(f=(h=(c=d.getElementsByTagName("BaseURL"))===null||c===void 0?void 0:c[0])===null||h===void 0?void 0:h.childNodes)===null||f===void 0?void 0:f[0])===null||m===void 0?void 0:m.data),Ee=(p=Qe.getAttribute("lang"))!==null&&p!==void 0?p:void 0;ee&&u.push({id:oi,url:ee,language:Ee})}return}const G=.1,oe=Number((S=d.attributes.getNamedItem("bandwidth"))===null||S===void 0?void 0:S.value),ve=(s?s+"/":"")+d.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ge;const Ie=(T=(g=d.attributes.getNamedItem("frameRate"))===null||g===void 0?void 0:g.value)!==null&&T!==void 0?T:void 0;ge=Ie?Ma(Ie):void 0,o.push({width:Number((I=d.attributes.getNamedItem("width"))===null||I===void 0?void 0:I.value),height:Number((w=d.attributes.getNamedItem("height"))===null||w===void 0?void 0:w.value),bandwidth:oe,baseURL:ve,failoverHosts:t,indexFrom:Number(ce[0]),indexTo:Number(ce[1]),initFrom:Number(k[0]),initTo:Number(k[1]),codecs:(N=(A=d.attributes.getNamedItem("codecs"))===null||A===void 0?void 0:A.value)!==null&&N!==void 0?N:void 0,mimeType:(Y=(X=d.attributes.getNamedItem("mimeType"))===null||X===void 0?void 0:X.value)!==null&&Y!==void 0?Y:void 0,fps:ge,bufferSize:G*oe/8,bufferLength:G,name:(Z=(F=d.attributes.getNamedItem("okQuality"))===null||F===void 0?void 0:F.value)!==null&&Z!==void 0?Z:void 0,id:(B=(V=d.attributes.getNamedItem("id"))===null||V===void 0?void 0:V.value)!==null&&B!==void 0?B:void 0})}),o.length)this._representations=o;else{this._onDashCallback("error");return}u.forEach(({id:d,language:l,url:c})=>{const h=document.createElement("track");h.setAttribute("src",c),d&&h.setAttribute("id",d),l&&h.setAttribute("srclang",l),this._video.appendChild(h)}),this._representations.sort((d,l)=>l.bandwidth-d.bandwidth),this._params.onManifestReady(this._representations)}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const s=Date.now();this._stream.load(e,e.initFrom,e.indexTo,r=>{let a=e.initTo-e.initFrom+1;if(!r.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(r.buffer,0,a);const n=new DataView(r.buffer);a+=12;const o=n.getUint32(a+4,!1);a+=8;let u=n.getUint32(a,!1),d=n.getUint32(a+4,!1)+(e.indexTo+1);a+=8;const l=n.getUint16(a+2,!1);a+=4,e.refs=[];for(let h=0;h<l;h+=1){const f=d+(n.getUint32(a,!1)&2147483647),m=u+n.getUint32(a+4,!1);a+=12,e.refs.push({fromTime:u/o,toTime:m/o,fromOffset:d,toOffset:f-1}),d=f,u=m}const c=e.refs[e.refs.length-1];c.toTime-c.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,r=>{this._params.onResponseHeaders(r),this._params.onIdxRequestPing(Date.now()-s)},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 s=new t;let r,a;const n=()=>{const d=this._findRef(this._video.currentTime);if(!d||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const f=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),f)}const l=this._appendVector[String(d.fromTime)];l!==r&&(r=l,this._params.onRepresentationPlay(l));let c;if(this._findRef(d.toTime)){const f=this._buffer.getByTime(this._video.currentTime);if(!f){this._onDashCallback("buffering");return}c=f.to-this._video.currentTime,c<e.bufferLength&&(this._onDashCallback("buffering"),a!==f.to&&(a=f.to,window.setTimeout(()=>{try{const m=this._buffer.getNextWithGap(f);m&&(this._video.currentTime=m.from)}catch(m){throw this._params.onError("GapSyncError",`Seek Error ${String(m)}`,m),m}},c*1e3)))}},o=()=>{this._loopTimeout=window.setTimeout(()=>{try{n()}catch(d){throw this._params.onError("LoopError",`Dash Loop exception ${String(d)}`,d),d}o()},250)},u=()=>{if(!this._stream)try{const d=s.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new ks({mediaSource:s,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),s.duration||(s.duration=this._duration),this._loopTimeout||o(),s.removeEventListener("sourceopen",u),s.removeEventListener("webkitsourceopen",u)};s.addEventListener("sourceopen",u,!1),s.addEventListener("webkitsourceopen",u,!1),this._video&&(this._video.src=window.URL.createObjectURL(s),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,s=!1,r=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const a=this._findRef(t);if(a){if(s){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 s=this._buffer.getByTime(this._video.currentTime),r=this._findRef(this._video.currentTime);if(!s||!r){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const a=.1;if(r.toTime<s.to+a){const n=this._findRef(r.toTime);n&&n.toTime<s.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||K(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const s=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!s)return;if(Array.isArray(s)&&s.length===0){this._params.onError("emptyrefs","Empty refs");return}let r;for(let a=0;a<s.length;a++){const n=s[a];if(n.fromTime<=e&&n.toTime>e)return n;n.fromTime>e&&(!r||n.fromTime<r.fromTime)&&(r=n)}if(!r){const a=s[s.length-1];if(e>a.toTime)return a}return r}_isLastRef(e){var t;const s=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!s)return!1;const r=s[s.length-1];return e.fromTime===r.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const s=this._video.buffered.start(t),r=this._video.buffered.end(t);if(e>s&&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(i){i.STOPPED="stopped",i.MANIFEST_LOADED="manifest-loaded",i.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",i.METADATA_LOADED="metadata-loaded",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(Q||(Q={}));const qg=[Q.PAUSED,Q.PLAYING];class jg{constructor(e){this.videoState=new le(Q.STOPPED),this.subscription=new se,this.representations$=new y([]),this.currentRepresentation$=new y(void 0),this.textTracksManager=new it,this.elementSize$=new y(void 0),this.dashLiteEvents={idxRequestPing$:new O,responseHeaders$:new O,manifestReady$:new O,representationPlay$:new O,error$:new O},this.handleManifestReady=t=>{var s,r,a;const n=[];for(const o of t){const u=(r=(s=o.name)!==null&&s!==void 0?s:o.id)!==null&&r!==void 0?r:o.height.toString(10),d=(a=o.name&&Vi(o.name))!==null&&a!==void 0?a:Mt(o),l=o.bandwidth/1e3,c={width:o.width,height:o.height},h=o.fps;if(!d)continue;const f={id:u,quality:d,bitrate:l,size:c,fps:h};n.push({track:f,representation:o})}this.representations$.next(n),this.params.output.availableVideoTracks$.next(n.map(({track:o})=>o)),this.videoState.setState(Q.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var s;const r=(s=this.representations$.getValue().find(({representation:a})=>a===t))===null||s===void 0?void 0:s.track;r&&(this.params.output.currentVideoTrack$.next(r),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(r.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return P(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),s=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(s)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(n)};`}),r===v.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),R(this.params.desiredState.playbackState,v.STOPPED,!0));return}if(!s)switch((a==null?void 0:a.to)!==v.PAUSED&&n.state===H.Requested&&qg.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===v.READY?R(this.params.desiredState.playbackState,v.READY):r===v.PAUSED?(this.videoState.setState(Q.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED)):r===v.PLAYING&&(this.videoState.startTransitionTo(Q.PLAYING),this.playIfAllowed());return;case Q.PLAYING:r===v.PAUSED?(this.videoState.startTransitionTo(Q.PAUSED),this.video.pause()):(a==null?void 0:a.to)===v.PLAYING&&R(this.params.desiredState.playbackState,v.PLAYING);return;case Q.PAUSED:r===v.PLAYING?(this.videoState.startTransitionTo(Q.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===v.PAUSED&&R(this.params.desiredState.playbackState,v.PAUSED);return;default:return x(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),L(this.videoState.stateChangeStarted$.pipe($(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe($(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(t)}`})}),this.video=vt(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(Re(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new ag(this.video),this.dash=new Yg({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:t=>this.dashLiteEvents.manifestReady$.next(t),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,s,r)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:s,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,s=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=mt(this.video),n=(o,u)=>this.subscription.add(o.subscribe(u,s));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(a.seeking$.subscribe(()=>{K(this.params.desiredState.seekState.getState().state!==H.Applying)&&(this.videoState.getState()===Q.PLAYING||this.videoState.getState()===Q.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(Ut(this.video,t.isLooped,s)),this.subscription.add(pt(this.video,t.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Et(this.video,t.playbackRate,a.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),n(_s(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)},s)).add(a.pause$.subscribe(()=>{this.videoState.setState(Q.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED)})).add(a.playing$.subscribe(()=>{this.videoState.setState(Q.PLAYING),R(this.params.desiredState.playbackState,v.PLAYING)},s)).add(a.loadedMetadata$.subscribe(()=>{this.videoState.setState(Q.METADATA_LOADED)},s)).add(a.currentBuffer$.subscribe(o=>{this.buffer.fill(),e.currentBuffer$.next(o)},s)).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(L(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$,this.params.output.element$,this.elementSize$,U(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(),m=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),p=this.elementSize$.getValue(),S=r();h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to);let g;if(!S&&_(f))g=f;else{const T=It(this.video.buffered,this.video.currentTime*1e3),I=S?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,w=Math.min(T/I,1);g=(u=Fi(c.map(({track:A})=>A),{container:p,throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:w,playbackRate:this.video.playbackRate,current:(o=c.find(({representation:A})=>A===l))===null||o===void 0?void 0:o.track}))===null||u===void 0?void 0:u.id}return _(g)?(d=c.find(({track:T})=>T.id===g))===null||d===void 0?void 0:d.representation:void 0}),me()).subscribe(this.currentRepresentation$,s)).add(dt({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(j(o=>o.to===Q.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(j(_))}).pipe(ye()).subscribe(()=>this.videoState.setState(Q.INITIAL_REPRESENTATION_SELECTED),s)).add(this.currentRepresentation$.pipe(j(_),me((o,u)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?o.height<=u.height:o===u)).subscribe(o=>{const u=It(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(Re(o.baseURL)))},s)).add(this.dashLiteEvents.responseHeaders$.subscribe(o=>{const{type:u,reused:d}=pu(o);this.params.output.httpConnectionType$.next(u),this.params.output.httpConnectionReused$.next(d)})).add(this.dashLiteEvents.idxRequestPing$.pipe(ye(),Ot(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,s)).add(this.dashLiteEvents.representationPlay$.pipe(j(_)).subscribe(this.handleRepresentationPlay,s)).add(L(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ve(0)).subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),St(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 x(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){$t(this.video).then(e=>{e||(this.videoState.setState(Q.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}}var Me;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(Me||(Me={}));var Ps;(function(i){i.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",i.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Ps||(Ps={}));var Ue;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(Ue||(Ue={}));var te;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(te||(te={}));var si;(function(i){i.MP4="mp4",i.WEBM="webm"})(si||(si={}));var ca=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};const zg=(i,e={})=>{const s=e.timeout||1,r=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-r-1>s},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},Wg=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",yo=Wg?zg:window.requestIdleCallback;var _r,kr;let mu=!1;try{mu=cu()&&parseInt((kr=(_r=navigator.userAgent.match(/Version\/(\d+)/))===null||_r===void 0?void 0:_r[1])!==null&&kr!==void 0?kr:"",10)<16}catch(i){console.error(i)}class Qg{constructor(e){this.bufferFull$=new O,this.error$=new O,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const s=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!s),this.currentTask=null}this.queue.length&&this.pull()}catch(s){this.error$.next({id:"BufferTaskQueueUnknown",category:D.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:s})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return ue(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(s=>{const r={operation:"append",data:e,signal:t,callback:s};this.queue.push(r),this.pull()})})}remove(e,t,s){return ue(this,void 0,void 0,function*(){return s&&s.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:s,callback:r};this.queue.unshift(a),this.pull()})})}abort(e){return ue(this,void 0,void 0,function*(){return new Promise(t=>{let s;mu&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);s&&(this.queue=[s]),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:s}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&s==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${s}`,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:x(t)}}}var To=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};const Su=new TextDecoder("ascii"),gu=i=>{let e=0,t=i.getUint32(e);e+=4;const s=new DataView(i.buffer,i.byteOffset+e,4),r=Su.decode(s);e+=4,t===0?t=1/0:t===1&&(e+=8,t=1/0);const a=Math.min(t,i.byteLength)-e,n=new DataView(i.buffer,i.byteOffset+e,a);return{id:r,size:t,contents:n}},Jg=i=>Su.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",Kg=(i,e,t)=>{const s=gu(i),r=[];let a=0;const n=()=>{const p=s.contents.getUint32(a);return a+=4,p};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,m=(t?t.to+1:i.byteOffset+i.byteLength)+c;for(let p=0;p<h;p++){const S=n(),g=S>>>31,T=S<<1>>>1,I=n();if(n(),g!==0)throw new Error("Unsupported multilevel sidx");const w=I/d*1e3;r.push({status:te.NONE,time:{from:f,to:f+w},byte:{from:m,to:m+T-1}}),f+=w,m+=T}return r},Xg=i=>{let e=0,t=!1,s=!1;for(;e<=i.byteLength&&!t;){const r=new DataView(i.buffer,i.byteOffset+e);try{const a=gu(r);if(s||(s=a.id==="mdat"),e+a.size<=i.byteLength)e+=a.size;else break}catch(a){t=!0}}return e>0&&e<=i.byteLength&&s?new DataView(i.buffer,i.byteOffset,e):null},Zg={validateData:Jg,parseInit:()=>null,getIndexRange:()=>{},parseSegments:Kg,parseFeedableSegmentChunk:Xg};var E;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.Chapters=272869232]="Chapters",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.SilentTracks=22612]="SilentTracks",i[i.SilentTrackNumber=22743]="SilentTrackNumber",i[i.Position=167]="Position",i[i.PrevSize=171]="PrevSize",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.EncryptedBlock=175]="EncryptedBlock",i[i.Attachments=423732329]="Attachments",i[i.Tags=307544935]="Tags",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.CueRelativePosition=240]="CueRelativePosition",i[i.CueDuration=178]="CueDuration",i[i.CueBlockNumber=21368]="CueBlockNumber",i[i.CueCodecState=234]="CueCodecState",i[i.CueReference=219]="CueReference",i[i.CueRefTime=150]="CueRefTime"})(E||(E={}));var C;(function(i){i.SignedInteger="int",i.UnsignedInteger="uint",i.Float="float",i.String="string",i.UTF8="utf8",i.Date="date",i.Master="master",i.Binary="binary"})(C||(C={}));const Eo={[E.EBML]:{type:C.Master},[E.EBMLVersion]:{type:C.UnsignedInteger},[E.EBMLReadVersion]:{type:C.UnsignedInteger},[E.EBMLMaxIDLength]:{type:C.UnsignedInteger},[E.EBMLMaxSizeLength]:{type:C.UnsignedInteger},[E.DocType]:{type:C.String},[E.DocTypeVersion]:{type:C.UnsignedInteger},[E.DocTypeReadVersion]:{type:C.UnsignedInteger},[E.Void]:{type:C.Binary},[E.Segment]:{type:C.Master},[E.SeekHead]:{type:C.Master},[E.Seek]:{type:C.Master},[E.SeekID]:{type:C.Binary},[E.SeekPosition]:{type:C.UnsignedInteger},[E.Info]:{type:C.Master},[E.TimestampScale]:{type:C.UnsignedInteger},[E.Duration]:{type:C.Float},[E.Tracks]:{type:C.Master},[E.Chapters]:{type:C.Master},[E.Cluster]:{type:C.Master},[E.Timestamp]:{type:C.UnsignedInteger},[E.SilentTracks]:{type:C.Master},[E.SilentTrackNumber]:{type:C.UnsignedInteger},[E.Position]:{type:C.UnsignedInteger},[E.PrevSize]:{type:C.UnsignedInteger},[E.SimpleBlock]:{type:C.Binary},[E.BlockGroup]:{type:C.Master},[E.EncryptedBlock]:{type:C.Binary},[E.Attachments]:{type:C.Master},[E.Tags]:{type:C.Master},[E.Cues]:{type:C.Master},[E.CuePoint]:{type:C.Master},[E.CueTime]:{type:C.UnsignedInteger},[E.CueTrackPositions]:{type:C.Master},[E.CueTrack]:{type:C.UnsignedInteger},[E.CueClusterPosition]:{type:C.UnsignedInteger},[E.CueRelativePosition]:{type:C.UnsignedInteger},[E.CueDuration]:{type:C.UnsignedInteger},[E.CueBlockNumber]:{type:C.UnsignedInteger},[E.CueCodecState]:{type:C.UnsignedInteger},[E.CueReference]:{type:C.Master},[E.CueRefTime]:{type:C.UnsignedInteger}},bu=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const s=Rs(i,t),r=s in Eo,a=r?Eo[s].type:C.Binary,n=i.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(i.buffer,i.byteOffset+t+1,o-1),d=n&255>>o,l=Rs(u),c=d*Math.pow(2,(o-1)*8)+l,h=t+o;let f;return h+c>i.byteLength?f=new DataView(i.buffer,i.byteOffset+h):f=new DataView(i.buffer,i.byteOffset+h,c),{tag:r?s:"0x"+s.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:f,valueSize:c}},Rs=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*Math.pow(2,16)+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*Math.pow(2,32)+i.getUint32(1);case 6:return i.getUint16(0)*Math.pow(2,32)+i.getUint32(2);case 7:{const t=i.getUint8(0)*Math.pow(2,48)+i.getUint16(1)*Math.pow(2,32)+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ot=(i,e)=>{switch(e){case C.SignedInteger:return i.getInt8(0);case C.UnsignedInteger:return Rs(i);case C.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case C.String:return new TextDecoder("ascii").decode(i);case C.UTF8:return new TextDecoder("utf-8").decode(i);case C.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case C.Master:return i;case C.Binary:return i;default:x(e)}},Hi=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),r=bu(s);if(!e(r))return;r.type===C.Master&&Hi(r.value,e),t=r.value.byteOffset-i.byteOffset+r.valueSize}},eb=i=>{if(i.getUint32(0)!==E.EBML)return!1;let e,t,s;const r=bu(i);return Hi(r.value,({tag:a,type:n,value:o})=>(a===E.EBMLReadVersion?e=ot(o,n):a===E.DocType?t=ot(o,n):a===E.DocTypeReadVersion&&(s=ot(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},yu=[E.Info,E.SeekHead,E.Tracks,E.Chapters,E.Cluster,E.Cues,E.Attachments,E.Tags],tb=[E.Timestamp,E.SilentTracks,E.SilentTrackNumber,E.Position,E.PrevSize,E.SimpleBlock,E.BlockGroup,E.EncryptedBlock],ib=i=>{let e,t,s,r,a=!1,n=!1,o=!1,u,d;return Hi(i,({tag:l,type:c,value:h,valueSize:f})=>{if(l===E.SeekID){const m=ot(h,c);d=Rs(m)}else l!==E.SeekPosition&&(d=void 0);return l===E.Segment?(e=h.byteOffset,t=h.byteOffset+f):l===E.Info?a=!0:l===E.SeekHead?n=!0:l===E.TimestampScale?s=ot(h,c):l===E.Duration?r=ot(h,c):l===E.SeekPosition&&d===E.Cues?u=ot(h,c):a&&n&&yu.includes(l)&&(o=!0),!o}),P(e,"Failed to parse webm Segment start"),P(t,"Failed to parse webm Segment end"),P(r,"Failed to parse webm Segment duration"),s=s!=null?s:1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(t/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(r/1e9*s*1e3),cuesSeekPosition:u}},sb=i=>{if(K(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},rb=(i,e)=>{let t=!1,s=!1;const r=o=>_(o.time)&&_(o.position),a=[];let n;return Hi(i,({tag:o,type:u,value:d})=>{switch(o){case E.Cues:t=!0;break;case E.CuePoint:n&&r(n)&&a.push(n),n={};break;case E.CueTime:n&&(n.time=ot(d,u));break;case E.CueTrackPositions:break;case E.CueClusterPosition:n&&(n.position=ot(d,u));break;default:t&&yu.includes(o)&&(s=!0)}return!(t&&s)}),n&&r(n)&&a.push(n),a.map((o,u)=>{const{time:d,position:l}=o,c=a[u+1];return{status:te.NONE,time:{from:d,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+l,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},ab=i=>{let e=0,t=!1;try{Hi(i,s=>s.tag===E.Cluster?s.tagSize<=i.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):tb.includes(s.tag)?(e+s.tagSize<=i.byteLength&&(e+=s.tagSize,t||(t=[E.SimpleBlock,E.BlockGroup,E.EncryptedBlock].includes(s.tag))),!0):!1)}catch(s){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},nb={validateData:eb,parseInit:ib,getIndexRange:sb,parseSegments:rb,parseFeedableSegmentChunk:ab};class $o{constructor(e,t,s,r,{fetcher:a,tuning:n,getCurrentPosition:o,compatibilityMode:u=!1}){switch(this.onLastSegment$=new y(!1),this.fullyBuffered$=new y(!1),this.playingRepresentation$=new y(void 0),this.error$=new O,this.gaps=[],this.subscription=new se,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new Dt,this.destroyAbortController=new Dt,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=qe(this.destroyAbortController.signal,function(d){return je(this,arguments,function*(){const l=this.representations.get(d);P(l,`Cannot find representation ${d}`),this.playingRepresentationId=d,this.downloadingRepresentationId=d,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${l.mime}; codecs="${l.codecs}"`),this.sourceBufferTaskQueue=new Qg(this.sourceBuffer),this.subscription.add(U(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},m=>this.error$.next({id:"SegmentEjection",category:D.WTF,message:"Error when trying to clear segments ejected by browser",thrown:m}))),this.subscription.add(U(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(m=>{if(!this.sourceBuffer)return;const p=Math.min(this.bufferLimit,To(this.sourceBuffer.buffered)*.8);this.bufferLimit=p,this.pruneBuffer(this.getCurrentPosition(),m)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(m=>this.error$.next(m))),yield yield M(this.loadInit(l,"high",!0));const c=this.initData.get(l.id),h=this.segments.get(l.id);if(P(c,"No init buffer for starting representation"),P(h,"No segments for starting representation"),!(c instanceof ArrayBuffer))return yield M(void 0);let f=0;for(const m of h)m.time.from-f>0&&this.gaps.push({representation:l.id,from:f,to:m.time.from}),f=m.time.to;_(l.duration)&&l.duration-f>0&&this.gaps.push({representation:l.id,from:f,to:l.duration}),yield yield M(this.sourceBufferTaskQueue.append(c,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId)})}.bind(this)),this.switchTo=qe(this.destroyAbortController.signal,function(d){return je(this,arguments,function*(){if(d===this.downloadingRepresentationId||d===this.switchingToRepresentationId)return yield M(void 0);this.switchingToRepresentationId=d;const l=this.representations.get(d);P(l,`No such representation ${d}`);let c=this.initData.get(d);if(K(c)?yield yield M(this.loadInit(l,"high",!1)):c instanceof Promise&&(yield yield M(c)),c=this.initData.get(d),!c||!(c instanceof ArrayBuffer)||!this.sourceBuffer)return yield M(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=d,this.abort(),yield yield M(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=s,s){case si.MP4:this.containerParser=Zg;break;case si.WEBM:this.containerParser=nb;break;default:x(s)}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 Dt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(K(e)||K(this.downloadingRepresentationId)||K(this.playingRepresentationId)||K(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(P(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const r=s.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const l=It(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)&&To(this.sourceBuffer.buffered)>=this.bufferLimit){const d=It(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(s,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{const l=at(o,0);l&&l.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===te.FED&&!o.length&&It(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const u=at(s,-1);u&&u.status===te.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===u))}findSegmentStartTime(e){var t,s,r;const a=(s=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&s!==void 0?s: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,s){const r=e.findIndex(({status:c,time:{from:h,to:f}},m)=>{const p=h<=s&&f>=s,S=h>s||p||m===0&&s===0,g=Math.min(this.forwardBufferTarget,this.bufferLimit),T=this.preloadOnly&&h<=s+g||f<=s+g;return(c===te.NONE||c===te.PARTIALLY_EJECTED&&S&&T&&this.sourceBuffer&&!ca(this.sourceBuffer.buffered,s))&&S&&T});if(r===-1)return[];if(t!==Ue.BYTE_RANGE)return e.slice(r,r+1);const a=e;let n=0,o=0;const u=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,l=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=d||o<=l);c++){const h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status===te.NONE||h.status===te.PARTIALLY_EJECTED)u.push(h);else break}return u}loadSegments(e,t,s="auto"){return ue(this,void 0,void 0,function*(){if(!e.length)return;let r,a,n=e;const{type:o}=t.segmentReference;switch(o){case Ue.BYTE_RANGE:{r=t.segmentReference.url,a={from:at(e,0).byte.from,to:at(e,-1).byte.to};break}case Ue.TEMPLATE:{const d=at(e,0);r=new URL(d.url,t.segmentReference.baseUrl).toString(),n=[d];break}default:x(o)}for(const d of n)d.status=te.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:u}=this.downloadAbortController;if(this.failedDownloads&&(yield qe(u,function(){return je(this,arguments,function*(){const d=Ja(this.failedDownloads,this.tuning.downloadBackoff);yield yield M(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:s}).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 s=!1;const r=this.getCurrentPosition();this.sourceBuffer&&_(r)&&(s=It((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,s||this.error$.next({id:"SegmentDownload",category:D.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,s,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=te.FED,"size"in c.segment&&(c.segment.size=c.fedBytes);for(const f of this.representations.values())if(f.id!==t)for(const m of(h=this.segments.get(f.id))!==null&&h!==void 0?h:[])m.status===te.FED&&m.time.from===c.segment.time.from&&m.time.to===c.segment.time.to&&(m.status=te.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===Ue.BYTE_RANGE,m=f?h.byte.to-h.byte.from+1:l;if(c.representationId!==t||!(!f||h.byte.from>=s&&h.byte.to<s+e.byteLength))continue;if(a.aborted){n();continue}const S=f?h.byte.from-s:0,g=f?h.byte.to-s:e.byteLength,T=S<r,I=g<=r;if(h.status===te.DOWNLOADING&&T&&I){h.status=te.DOWNLOADED,this.activeSegments.delete(c);const w=new DataView(e.buffer,e.byteOffset+S,m);this.sourceBufferTaskQueue.append(w,a).then(A=>A&&!a.aborted?o(c):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&T&&(c.loadedBytes=Math.min(m,r-S),c.loadedBytes>c.feedingBytes)){const w=new DataView(e.buffer,e.byteOffset+S+c.feedingBytes,c.loadedBytes-c.feedingBytes),A=c.loadedBytes===m?w:this.containerParser.parseFeedableSegmentChunk(w);A!=null&&A.byteLength&&(h.status=te.PARTIALLY_FED,c.feedingBytes+=A.byteLength,this.sourceBufferTaskQueue.append(A,a).then(N=>{if(a.aborted)n();else if(N)c.fedBytes+=A.byteLength,c.fedBytes===m&&o(c);else{if(c.feedingBytes<m)return;n()}}))}}}abortSegment(e){e.status===te.PARTIALLY_FED||e.status===te.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=te.NONE),e.status=te.PARTIALLY_EJECTED):e.status=te.NONE;for(const 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 s=this.representations.get(e);s&&(this.initLoadIdleCallback=yo(()=>Fs(this.loadInit(s,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",s=!1){return ue(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!s&&this.failedDownloads>0?qe(this.destroyAbortController.signal,function(){return je(this,arguments,function*(){const o=Ja(this.failedDownloads,this.tuning.downloadBackoff);yield yield M(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),s&&this.error$.next({id:"LoadInits",category:D.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n})}pruneBuffer(e,t,s=!1){return ue(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||K(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===te.FED&&u(l)}if(o=isFinite(a)&&isFinite(n),!o){r=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const l of d){if(l.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;l.status===te.FED&&u(l)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const l=this.sourceBuffer.buffered.start(d)*1e3,c=this.sourceBuffer.buffered.end(d)*1e3;for(const h of this.segments.values())for(const f of h)if(f.status===te.NONE&&Math.round(f.time.from)<=Math.round(l)&&Math.round(f.time.to)>=Math.round(c)){a=l,n=c;break}}if(o=isFinite(a)&&isFinite(n),!o&&s){r=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const l of this.segments.values())for(const c of l)c.time.from>e+d&&c.status===te.FED&&u(c)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}detectGaps(e,t){if(this.sourceBuffer)for(const s of t){let r={representation:e,from:s.time.from,to:s.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<=s.time.from||n>=s.time.to)){if(n<=s.time.from&&o>=s.time.to){r=void 0;break}o>s.time.from&&o<s.time.to&&(r.from=o),n<s.time.to&&n>s.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=yo(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:D.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(K(this.sourceBuffer)||K(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const r=Math.round(this.sourceBuffer.buffered.start(s)*1e3),a=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:r,to:a})}const t=1;for(const s of this.segments.values())for(const r of s){const{status:a}=r;if(a!==te.FED&&a!==te.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),u=e.some(l=>l.from-t<=n&&l.to+t>=o),d=e.filter(l=>n>=l.from-t&&n<=l.to+t||o>=l.from-t&&o<=l.to+t);u||(d.length===1?r.status=te.PARTIALLY_EJECTED:r.status=te.NONE)}}}var Kt;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(Kt||(Kt={}));class ob{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.lastConnectionType$=new y(void 0),this.lastConnectionReused$=new y(void 0),this.lastRequestFirstBytes$=new y(void 0),this.abortAllController=new Dt,this.subscription=new se,this.fetchManifest=qe(this.abortAllController.signal,function(r){return je(this,arguments,function*(){let a=r;this.requestQuic&&(a=ii(a));const n=yield yield M(ti(a,{signal:this.abortAllController.signal}).catch(Ti));return n?(this.onHeadersReceived(n.headers),yield M(n.text())):yield M(null)})}.bind(this)),this.fetch=qe(this.abortAllController.signal,function(r,{rangeMethod:a=this.compatibilityMode?Kt.HEADER:Kt.PARAM,range:n,onProgress:o,priority:u="auto",signal:d,measureThroughput:l=!0}={}){var c,h,f,m;return je(this,arguments,function*(){let p=r;const S=new Headers;if(n)switch(a){case Kt.HEADER:{S.append("Range",`bytes=${n.from}-${n.to}`);break}case Kt.PARAM:{const k=new URL(p,location.href);k.searchParams.append("bytes",`${n.from}-${n.to}`),p=k.toString();break}default:x(a)}this.requestQuic&&(p=ii(p));let g=this.abortAllController.signal;if(d){const k=new Dt;if(this.subscription.add(L(U(this.abortAllController.signal,"abort"),U(d,"abort")).subscribe(()=>{try{k.abort()}catch(G){Ti(G)}})),this.abortAllController.signal.aborted||d.aborted)try{k.abort()}catch(G){Ti(G)}g=k.signal}const T=pe(),I=yield yield M(ti(p,{priority:u,headers:S,signal:g}).catch(Ti)),w=pe();if((c=this.throughputEstimator)===null||c===void 0||c.addRawRtt(w-T),!I)return yield M(null);if(!I.ok||!I.body)return yield M(Promise.reject(new Error(`Fetch error ${I.status}: ${I.statusText}`)));this.onHeadersReceived(I.headers);const A=parseInt((h=I.headers.get("Content-Length"))!==null&&h!==void 0?h:"",10)||n&&n.to-n.from+1||NaN;if(!A){const k=yield yield M(I.arrayBuffer());return(f=this.throughputEstimator)===null||f===void 0||f.addRawSpeed(k.byteLength,pe()-w),o==null||o(new DataView(k),k.byteLength),yield M(k)}if(!o&&!l)return yield M(I.arrayBuffer());const[N,X]=I.body.tee(),Y=N.getReader();l&&((m=this.throughputEstimator)===null||m===void 0||m.trackStream(X));let F=0;const Z=new ArrayBuffer(A),V=new Uint8Array(Z),B=new DataView(Z);let ie=!1;const ce=k=>{ie=!0,Ti(k)},Se=qe(g,function({done:k,value:G}){return je(this,arguments,function*(){if(F===0&&this.lastRequestFirstBytes$.next(pe()-T),g.aborted)return yield M(void 0);k?o==null||o(B,F):G&&(V.set(G,F),F+=G.byteLength,o==null||o(B,F),yield yield M(Y==null?void 0:Y.read().then(Se,ce)))})}.bind(this));return yield yield M(Y==null?void 0:Y.read().then(Se,ce)),yield M(ie?null:Z)})}.bind(this)),this.fetchByteRangeRepresentation=qe(this.abortAllController.signal,function(r,a,n){var o;return je(this,arguments,function*(){if(r.type!==Ue.BYTE_RANGE)return yield M(null);const{from:u,to:d}=r.initRange;let l=u,c=d,h=!1,f,m;r.indexRange&&(f=r.indexRange.from,m=r.indexRange.to,h=d+1===f,h&&(l=Math.min(f,u),c=Math.max(m,d))),l=Math.min(l,0);const p=yield yield M(this.fetch(r.url,{range:{from:l,to:c},priority:n,measureThroughput:!1}));if(!p)return yield M(null);const S=new DataView(p,u-l,d-l+1);if(!a.validateData(S))throw new Error("Invalid media file");const g=a.parseInit(S),T=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(g);if(!T)throw new ReferenceError("No way to load representation index");let I;if(h)I=new DataView(p,T.from-l,T.to-T.from+1);else{const A=yield yield M(this.fetch(r.url,{range:T,priority:n,measureThroughput:!1}));if(!A)return yield M(null);I=new DataView(A)}const w=a.parseSegments(I,g,T);return yield M({dataView:new DataView(p),segments:w})})}.bind(this)),this.fetchTemplateRepresentation=qe(this.abortAllController.signal,function(r,a){return je(this,arguments,function*(){if(r.type!==Ue.TEMPLATE)return yield M(null);const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield yield M(this.fetch(n,{priority:a,measureThroughput:!1}));if(!o)return yield M(null);const u=r.segments.map(d=>Object.assign(Object.assign({},d),{status:te.NONE,size:void 0}));return yield M({segments:u,dataView:new DataView(o)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=pu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchRepresentation(e,t,s="auto"){var r,a;return ue(this,void 0,void 0,function*(){const{type:n}=e;switch(n){case Ue.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,s))!==null&&r!==void 0?r:null;case Ue.TEMPLATE:return(a=yield this.fetchTemplateRepresentation(e,s))!==null&&a!==void 0?a:null;default:x(n)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Ti=i=>{if(!(i instanceof DOMException)||!(i.name==="AbortError"||i.code===20))throw i};var db=ct,ub=Di,lb=ke,cb=lb("match"),hb=function(i){var e;return db(i)&&((e=i[cb])!==void 0?!!e:ub(i)=="RegExp")},fb=Ni,pb=String,vb=function(i){if(fb(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return pb(i)},mb=ft,Sb=function(){var i=mb(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e},gb=Le,bb=tt,yb=Ds,Tb=Sb,Ao=RegExp.prototype,Eb=function(i){var e=i.flags;return e===void 0&&!("flags"in Ao)&&!bb(i,"flags")&&yb(Ao,i)?gb(Tb,i):e},Fa=Ge,$b=xs,Ab=Math.floor,Pr=Fa("".charAt),wb=Fa("".replace),Rr=Fa("".slice),_b=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,kb=/\$([$&'`]|\d{1,2})/g,Pb=function(i,e,t,s,r,a){var n=t+i.length,o=s.length,u=kb;return r!==void 0&&(r=$b(r),u=_b),wb(a,u,function(d,l){var c;switch(Pr(l,0)){case"$":return"$";case"&":return i;case"`":return Rr(e,0,t);case"'":return Rr(e,n);case"<":c=r[Rr(l,1,-1)];break;default:var h=+l;if(h===0)return d;if(h>o){var f=Ab(h/10);return f===0?d:f<=o?s[f-1]===void 0?Pr(l,1):s[f-1]+Pr(l,1):d}c=s[h-1]}return c===void 0?"":c})},Rb=We,Ib=Le,Va=Ge,wo=fa,Db=Te,Cb=Ci,Ob=hb,jt=vb,Lb=Ls,xb=Eb,Nb=Pb,Bb=ke,Mb=Bb("replace"),Ub=TypeError,Tu=Va("".indexOf),Fb=Va("".replace),_o=Va("".slice),Vb=Math.max,ko=function(i,e,t){return t>i.length?-1:e===""?t:Tu(i,e,t)};Rb({target:"String",proto:!0},{replaceAll:function(e,t){var s=wo(this),r,a,n,o,u,d,l,c,h,f=0,m=0,p="";if(!Cb(e)){if(r=Ob(e),r&&(a=jt(wo(xb(e))),!~Tu(a,"g")))throw Ub("`.replaceAll` does not allow non-global regexes");if(n=Lb(e,Mb),n)return Ib(n,e,s,t);if(r)return Fb(jt(s),e,t)}for(o=jt(s),u=jt(e),d=Db(t),d||(t=jt(t)),l=u.length,c=Vb(1,l),f=ko(o,u,0);f!==-1;)h=d?jt(t(u,f,o)):Nb(u,o,f,[],void 0,t),p+=_o(o,m,f)+h,m=f+l,f=ko(o,u,f+c);return m<o.length&&(p+=_o(o,m)),p}});var Hb=Na,Gb=Hb("String","replaceAll"),Yb=Gb,qb=Yb,jb=qb,zb=jb,Po=zb;const Ro=i=>{if(!i.startsWith("P"))return;const e=(n,o)=>{const u=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(u)?0:u)*o},s=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),r=(s==null?void 0:s[1])==="-"?-1:1,a={days:e(s==null?void 0:s[5],r),hours:e(s==null?void 0:s[6],r),minutes:e(s==null?void 0:s[7],r),seconds:e(s==null?void 0:s[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},Ir=(i,e)=>{let t=i;t=Po(t,"$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,a]of Object.entries(s)){const n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=Po(t,n,(o,u)=>K(a)?o:K(u)?a:a.padStart(parseInt(u,10),"0"))}return t},Wb=(i,e)=>{var t,s,r,a,n,o,u,d,l,c,h,f,m,p,S,g,T,I,w,A,N,X,Y,F,Z,V,B,ie,ce,Se,k,G,oe,ve,ge,Ie,Qe;const ee=new DOMParser().parseFromString(i,"application/xml"),Ee={video:[],audio:[],text:[]},Pe=ee.children[0],xe=Pe.getElementsByTagName("Period")[0],At=xe.children;let Je;const gt=Pe.getAttribute("mediaPresentationDuration"),wt=xe.getAttribute("duration");if(gt)Je=Ro(gt);else if(wt){const Ke=Ro(wt);_(Ke)&&(Je=Ke)}let di=0;const Ft=(s=(t=Pe.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&s!==void 0?s:[],ku=Ft.includes(Ps.WEBM_AS_IN_FFMPEG)||Ft.includes(Ps.WEBM_AS_IN_SPEC)?si.WEBM:si.MP4;for(const Ke of At){const Gi=Ke.getAttribute("mimeType"),Pu=Ke.getAttribute("codecs"),Ha=(r=Ke.getAttribute("contentType"))!==null&&r!==void 0?r:Gi==null?void 0:Gi.split("/")[0],Ru=(n=(a=Ke.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],Iu=Ke.querySelectorAll("Representation"),Du=Ke.querySelector("SegmentTemplate");if(Ha!=="text")for(const $e of Iu){const ui=(o=$e.getAttribute("mimeType"))!==null&&o!==void 0?o:Gi,Ga=(d=(u=$e.getAttribute("codecs"))!==null&&u!==void 0?u:Pu)!==null&&d!==void 0?d:"",Yi=(c=(l=$e.getAttribute("contentType"))!==null&&l!==void 0?l:ui==null?void 0:ui.split("/")[0])!==null&&c!==void 0?c:Ha,Cu=(f=(h=Ke.getAttribute("profiles"))===null||h===void 0?void 0:h.split(","))!==null&&f!==void 0?f:[],Ou=parseInt((m=$e.getAttribute("width"))!==null&&m!==void 0?m:"",10),Ya=parseInt((p=$e.getAttribute("height"))!==null&&p!==void 0?p:"",10),qa=parseInt((S=$e.getAttribute("bandwidth"))!==null&&S!==void 0?S:"",10)/1e3,ja=(g=$e.getAttribute("frameRate"))!==null&&g!==void 0?g:"",Lu=(T=$e.getAttribute("quality"))!==null&&T!==void 0?T:void 0,xu=ja?Ma(ja):void 0,Nu=(I=$e.getAttribute("id"))!==null&&I!==void 0?I:(di++).toString(10),Bu=Yi==="video"?`${Ya}p`:Yi==="audio"?`${qa}Kbps`:Ga,Mu=`${Nu}@${Bu}`,Uu=(N=(A=(w=$e.querySelector("BaseURL"))===null||w===void 0?void 0:w.textContent)===null||A===void 0?void 0:A.trim())!==null&&N!==void 0?N:"",za=new URL(Uu,e).toString(),Fu=[...Ft,...Ru,...Cu];let Gs;const Vu=$e.querySelector("SegmentBase"),_t=(X=$e.querySelector("SegmentTemplate"))!==null&&X!==void 0?X:Du;if(Vu){const li=(F=(Y=$e.querySelector("SegmentBase Initialization"))===null||Y===void 0?void 0:Y.getAttribute("range"))!==null&&F!==void 0?F:"",[ci,qs]=li.split("-").map(kt=>parseInt(kt,10)),hi={from:ci,to:qs},fi=(Z=$e.querySelector("SegmentBase"))===null||Z===void 0?void 0:Z.getAttribute("indexRange"),[js,qi]=fi?fi.split("-").map(kt=>parseInt(kt,10)):[],pi=fi?{from:js,to:qi}:void 0;Gs={type:Ue.BYTE_RANGE,url:za,initRange:hi,indexRange:pi}}else if(_t){const li={representationId:(V=$e.getAttribute("id"))!==null&&V!==void 0?V:void 0,bandwidth:(B=$e.getAttribute("bandwidth"))!==null&&B!==void 0?B:void 0},ci=parseInt((ie=_t.getAttribute("timescale"))!==null&&ie!==void 0?ie:"",10),qs=(ce=_t.getAttribute("initialization"))!==null&&ce!==void 0?ce:"",hi=_t.getAttribute("media"),fi=(k=parseInt((Se=_t.getAttribute("startNumber"))!==null&&Se!==void 0?Se:"",10))!==null&&k!==void 0?k:1,js=Ir(qs,li);if(!hi)throw new ReferenceError("No media attribute in SegmentTemplate");const qi=(G=_t.querySelectorAll("SegmentTimeline S"))!==null&&G!==void 0?G:[],pi=[];if(qi.length){let kt=fi,Pt=0;for(const vi of qi){const Vt=parseInt((oe=vi.getAttribute("d"))!==null&&oe!==void 0?oe:"",10)*1e3,mi=parseInt((ve=vi.getAttribute("r"))!==null&&ve!==void 0?ve:"",10)||0,Si=(Ie=parseInt((ge=vi.getAttribute("t"))!==null&&ge!==void 0?ge:"",10))!==null&&Ie!==void 0?Ie:void 0;for(let Wa=0;Wa<mi+1;Wa++){const Hu=Ir(hi,Object.assign(Object.assign({},li),{segmentNumber:kt.toString(10),segmentTime:Si.toString(10)})),Gu=Si?Si/ci:Pt;Pt+=Vt/ci;const Yu=Pt;kt++,pi.push({time:{from:Gu,to:Yu},url:Hu})}}}else if(_(Je)){const Pt=parseInt((Qe=_t.getAttribute("duration"))!==null&&Qe!==void 0?Qe:"",10)/ci*1e3,vi=Math.ceil(Je/Pt);let Vt=0;for(let mi=1;mi<vi;mi++){const Si=Ir(hi,Object.assign(Object.assign({},li),{segmentNumber:mi.toString(10),segmentTime:Vt.toString(10)}));pi.push({time:{from:Vt,to:Vt+Pt},url:Si}),Vt+=Pt}}Gs={type:Ue.TEMPLATE,baseUrl:za,initUrl:js,segments:pi}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Yi||!ui)continue;const Ys={video:Me.VIDEO,audio:Me.AUDIO,text:Me.TEXT}[Yi];Ys&&Ee[Ys].push({id:Mu,kind:Ys,segmentReference:Gs,profiles:Fu,duration:Je,bitrate:qa,mime:ui,codecs:Ga,width:Ou,height:Ya,fps:xu,quality:Lu})}}return{duration:Je,container:ku,representations:Ee}},Qb=["timeupdate","progress","play","seeked","stalled","waiting"];var Be;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(Be||(Be={}));let Jb=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new se,this.state$=new le(Be.NONE),this.currentVideoRepresentation$=new y(void 0),this.error$=new O,this.lastConnectionType$=new y(void 0),this.lastConnectionReused$=new y(void 0),this.lastRequestFirstBytes$=new y(void 0),this.forceEnded$=new O,this.gapWatchdogStarted=!1,this.destroyController=new Dt,this.initManifest=qe(this.destroyController.signal,function(t,s){return je(this,arguments,function*(){this.element=t,this.state$.startTransitionTo(Be.MANIFEST_READY);const r=yield yield M(this.fetcher.fetchManifest(s).catch(o=>this.error$.next({id:"LoadManifest",category:D.NETWORK,message:"Failed to load manifest",thrown:o})));if(!r)return yield M(void 0);let a;try{a=Wb(r!=null?r:"",s)}catch(o){this.error$.next({id:"ManifestParsing",category:D.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!a)return yield M(void 0);const n=({mime:o,codecs:u})=>{var d,l,c;return Boolean(((d=t.canPlayType)===null||d===void 0?void 0:d.call(t,o))&&((c=(l=window.MediaSource)===null||l===void 0?void 0:l.isTypeSupported)===null||c===void 0?void 0:c.call(l,`${o}; codecs="${u}"`)))};this.manifest=Object.assign(Object.assign({},a),{representations:Bi(Object.entries(a.representations).map(([o,u])=>[o,u.filter(n)]))}),this.manifest.representations.video.length?this.state$.setState(Be.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:D.PARSER,message:"No playable video representations"})})}.bind(this)),this.initRepresentations=qe(this.destroyController.signal,function(t,s){return je(this,arguments,function*(){P(this.manifest),P(this.element),this.state$.startTransitionTo(Be.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 $o(Me.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],_(s)&&(this.audioBufferManager=new $o(Me.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,r),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));const a=L(...this.bufferManagers.map(o=>o.fullyBuffered$)).pipe($(()=>this.bufferManagers.every(o=>o.fullyBuffered$.getValue()))),n=L(...this.bufferManagers.map(o=>o.onLastSegment$)).pipe($(()=>this.bufferManagers.some(o=>o.onLastSegment$.getValue())));this.subscription.add(L(this.forceEnded$,dt({allBuffersFull:a,someBufferEnded:n}).pipe(j(({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(L(...this.bufferManagers.map(o=>o.error$)).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.source.readyState!=="open"&&(yield yield M(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&&_(s)?yield yield M(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)])):yield yield M(this.videoBufferManager.startWith(t)),this.state$.setState(Be.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,s;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||!((s=this.audioBufferManager)===null||s===void 0)&&s.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=ju(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 ob({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initBuffer(){P(this.element),this.state$.setState(Be.RUNNING),this.subscription.add(L(...Qb.map(e=>U(this.element,e)),U(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:D.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(U(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(U(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&ca(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}switchRepresentation(e,t){return ue(this,void 0,void 0,function*(){const s={[Me.VIDEO]:this.videoBufferManager,[Me.AUDIO]:this.audioBufferManager,[Me.TEXT]:null}[e];return s==null?void 0:s.switchTo(t)})}seek(e,t){var s,r,a,n,o;P(this.element),P(this.videoBufferManager);let u;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?u=e:u=Math.max((s=this.videoBufferManager.findSegmentStartTime(e))!==null&&s!==void 0?s:e,(a=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&a!==void 0?a:e),ca(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(Be.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 s of this.bufferManagers)for(const r of s.gaps)s.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 s=Math.max(...t);s===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=s/1e3}}};var he;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(he||(he={}));const Kb=({id:i,width:e,height:t,bitrate:s,fps:r,quality:a})=>{var n;const o=(n=a?Vi(a):void 0)!==null&&n!==void 0?n:Mt({width:e,height:t});return o&&{id:i,quality:o,bitrate:s,size:{width:e,height:t},fps:r}},Xb=({id:i,bitrate:e})=>({id:i,bitrate:e}),Zb=(i,e,t)=>{var s;const r=e.indexOf(t);return(s=at(i,Math.round(i.length*r/e.length)))!==null&&s!==void 0?s:at(i,-1)};class ey{constructor(e){this.subscription=new se,this.videoState=new le(he.STOPPED),this.elementSize$=new y(void 0),this.textTracksManager=new it,this.videoTracks=[],this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new $g,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(a.state===H.Requested&&(r==null?void 0:r.to)!==v.PAUSED&&t!==he.STOPPED&&s!==v.STOPPED&&this.seek(a.position,a.forcePrecise),s===v.STOPPED){t!==he.STOPPED&&(this.videoState.startTransitionTo(he.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(he.STOPPED),R(this.params.desiredState.playbackState,v.STOPPED,!0));return}switch(t){case he.STOPPED:this.videoState.startTransitionTo(he.READY),this.prepare();return;case he.READY:s===v.PAUSED?(this.videoState.setState(he.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED)):s===v.PLAYING?(this.videoState.startTransitionTo(he.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===v.READY&&R(this.params.desiredState.playbackState,v.READY);return;case he.PLAYING:s===v.PAUSED?(this.videoState.startTransitionTo(he.PAUSED),this.video.pause()):(r==null?void 0:r.to)===v.PLAYING&&R(this.params.desiredState.playbackState,v.PLAYING);return;case he.PAUSED:s===v.PLAYING?(this.videoState.startTransitionTo(he.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===v.PAUSED&&R(this.params.desiredState.playbackState,v.PAUSED);return;default:return x(t)}}},this.params=e,this.video=vt(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Re(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Jb({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=mt(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(s.timeUpdate$,e.position$),a(s.durationChange$,e.duration$),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.playing$,e.firstFrameEvent$),a(s.canplay$,e.canplay$),a(s.isAudioAvailable$,e.isAudioAvailable$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.lastRequestFirstBytes$.pipe(j(_),ye(),Ot(void 0)),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Ut(this.video,t.isLooped,r)),this.subscription.add(pt(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Et(this.video,t.playbackRate,s.playbackRateState$,r)),a(_s(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(he.PLAYING),R(t.playbackState,v.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(he.PAUSED),R(t.playbackState,v.PAUSED)},r)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===he.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d===Be.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[];const c=this.player.getRepresentations();P(c,"Manifest not loaded or empty");const h=Array.from(c.audio).sort((p,S)=>S.bitrate-p.bitrate),f=Array.from(c.video).sort((p,S)=>S.bitrate-p.bitrate);if(!this.params.tuning.isAudioDisabled)for(const p of h){const S=Xb(p);S&&this.audioTracks.push({track:S,representation:p})}for(const p of f){const S=Kb(p);if(S){this.videoTracks.push({track:S,representation:p});const g=!this.params.tuning.isAudioDisabled&&Zb(h,f,p);g&&this.audioRepresentations.set(p.id,g)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:p})=>p)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:p})=>p)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length);const m=this.selectVideoRepresentation();P(m),this.player.initRepresentations(m.id,(l=this.audioRepresentations.get(m.id))===null||l===void 0?void 0:l.id)}else d===Be.REPRESENTATIOS_READY&&(this.videoState.setState(he.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(L(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,U(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!==Be.RUNNING||l||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation();if(c){this.player.switchRepresentation(Me.VIDEO,c.id).catch(n);const h=this.audioRepresentations.get(c.id);h&&this.player.switchRepresentation(Me.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===v.READY),me());this.subscription.add(L(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===v.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(L(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===v.READY)));const u=L(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ve(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,s,r,a,n;const o=this.params.desiredState.autoVideoTrackSwitching.getState(),u=this.params.desiredState.videoTrack.getState(),d=(e=this.videoTracks.find(({track:{id:g}})=>g===u))===null||e===void 0?void 0:e.track,l=this.params.output.currentVideoTrack$.getValue(),c=It(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),m=Math.max(d&&!o&&(s=(t=this.audioRepresentations.get(d.id))===null||t===void 0?void 0:t.bitrate)!==null&&s!==void 0?s:0,l&&(a=(r=this.audioRepresentations.get(l.id))===null||r===void 0?void 0:r.bitrate)!==null&&a!==void 0?a:0),p=Fi(this.videoTracks.map(({track:g})=>g),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:m,forwardBufferHealth:f,current:l,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),S=o?p!=null?p:d:d!=null?d:p;return S&&((n=this.videoTracks.find(({track:g})=>g===S))===null||n===void 0?void 0:n.representation)}prepare(){return ue(this,void 0,void 0,function*(){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),St(this.video)}playIfAllowed(){$t(this.video).then(e=>{e||(this.videoState.setState(he.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:D.DOM,thrown:e}))}}const ty=5e3,st={};var J;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(J||(J={}));const ds=(i,e)=>new Ii(t=>{const s=(r,a)=>t.next(a);return i.on(e,s),()=>i.off(e,s)});class iy{constructor(e){this.subscription=new se,this.videoState=new le(J.INITIALIZING),this.textTracksManager=new it,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(t!==J.INITIALIZING)switch((r==null?void 0:r.to)!==v.PAUSED&&a.state===H.Requested&&this.seek(a.position),s){case v.STOPPED:switch(t){case J.STOPPED:break;case J.READY:case J.PLAYING:case J.PAUSED:this.stop();break;default:x(t)}break;case v.READY:switch(t){case J.STOPPED:this.prepare();break;case J.READY:case J.PLAYING:case J.PAUSED:break;default:x(t)}break;case v.PLAYING:switch(t){case J.PLAYING:break;case J.STOPPED:this.prepare();break;case J.READY:case J.PAUSED:this.playIfAllowed();break;default:x(t)}break;case v.PAUSED:switch(t){case J.PAUSED:break;case J.STOPPED:this.prepare();break;case J.READY:this.videoState.setState(J.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED);break;case J.PLAYING:this.pause();break;default:x(t)}break;default:x(s)}},this.video=vt(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(Re(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),St(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},s=window.setTimeout(()=>t("timeout"),ty);Fs(import("hls.js").then(r=>{e||(st.Hls=r.default,st.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(s),e=!0})}init(){P(st.Hls,"hls.js not loaded"),this.hls=new st.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(J.STOPPED)}subscribe(){P(st.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=d=>{t.error$.next({id:"HlsJsProvider",category:D.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=mt(this.video),a=(d,l)=>this.subscription.add(d.subscribe(l,s));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.isAudioAvailable$,t.isAudioAvailable$),this.subscription.add(Ut(this.video,e.isLooped,s)),this.subscription.add(pt(this.video,e.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Et(this.video,e.playbackRate,r.playbackRateState$,s)),this.subscription.add(ds(this.hls,st.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(J.PLAYING),R(e.playbackState,v.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED),R(e.playbackState,v.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())===null||d===void 0?void 0:d.to)===J.READY&&this.videoState.setState(J.READY),this.videoState.getState()===J.PLAYING&&this.playIfAllowed()},s)),a(ds(this.hls,st.Events.MANIFEST_PARSED).pipe($(({levels:d})=>d.reduce((l,c)=>{var h,f;const m=c.name||c.height.toString(10),{width:p,height:S}=c,g=(f=Vi((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:Mt({width:p,height:S});if(!g)return l;const T=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,I={id:m.toString(),quality:g,bitrate:c.bitrate/1e3,size:{width:p,height:S},fps:T};return this.trackLevels.set(m,{track:I,level:c}),l.push(I),l},[]))),t.availableVideoTracks$),a(ds(this.hls,st.Events.LEVEL_LOADING).pipe($(({url:d})=>Re(d))),t.hostname$),this.subscription.add(et(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:s}));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=ds(this.hls,st.Events.LEVEL_SWITCHED).pipe($(({level:d})=>n(this.hls.levels[d])));o.pipe(j(_)).subscribe(t.currentVideoTrack$,s),this.subscription.add(et(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(K(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,m=this.hls.levels[f];!m||c.bitrate>m.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o.pipe($(d=>d==null?void 0:d.id)),onError:s})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const u=L(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ve(0));this.subscription.add(u.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(J.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return ue(this,void 0,void 0,function*(){this.videoState.startTransitionTo(J.PLAYING),(yield $t(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(J.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(J.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(J.STOPPED),R(this.params.desiredState.playbackState,v.STOPPED,!0)}}const Io="X-Playback-Duration";var Do=i=>ue(void 0,void 0,void 0,function*(){const e=yield ti(i,{method:"HEAD"});return e.headers.has(Io)?parseInt(e.headers.get(Io),10):void 0});const sy=i=>{let e=null;if(i.QUALITY&&(e=Vi(i.QUALITY)),!e&&i.RESOLUTION){const[t,s]=i.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Mt({width:t,height:s})}return e!=null?e:null},Eu=(i,e=i)=>ue(void 0,void 0,void 0,function*(){var t;const a=(yield(yield ti(i)).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=Bi(d[1].split(",").map(g=>g.split("="))),c=(t=l.QUALITY)!==null&&t!==void 0?t:`stream-${l.BANDWIDTH}`,h=sy(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 m=l["FRAME-RATE"]?parseFloat(l["FRAME-RATE"]):void 0;let p;if(l.RESOLUTION){const[g,T]=l.RESOLUTION.split("x").map(I=>parseInt(I,10));g&&T&&(p={width:g,height:T})}const S=new URL(a[++o],e).toString();h&&n.push({id:c,quality:h,url:S,bandwidth:f,size:p,fps:m})}return n});var re;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(re||(re={}));class ry{constructor(e){var t;this.subscription=new se,this.videoState=new le(re.STOPPED),this.textTracksManager=new it,this.manifests$=new y([]),this.liveOffset=new Ba,this.manifestStartTime$=new y(void 0),this.syncPlayback=()=>{const r=this.videoState.getState(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a===v.STOPPED){r!==re.STOPPED&&(this.videoState.startTransitionTo(re.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(re.STOPPED),R(this.params.desiredState.playbackState,v.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(r===re.STOPPED){this.videoState.startTransitionTo(re.READY),this.prepare();return}if(o||u){const c=this.videoState.getState();this.videoState.setState(re.CHANGING_MANIFEST),this.videoState.startTransitionTo(c),this.prepare(),l.state===H.None&&this.params.desiredState.seekState.setState({state:H.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==v.PAUSED&&l.state===H.Requested){this.videoState.startTransitionTo(re.READY),this.seek(l.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case re.READY:a===v.READY?R(this.params.desiredState.playbackState,v.READY):a===v.PAUSED?(this.videoState.setState(re.PAUSED),this.liveOffset.pause(),R(this.params.desiredState.playbackState,v.PAUSED)):a===v.PLAYING&&(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed());return;case re.PLAYING:a===v.PAUSED?(this.videoState.startTransitionTo(re.PAUSED),this.liveOffset.pause(),this.video.pause()):(n==null?void 0:n.to)===v.PLAYING&&R(this.params.desiredState.playbackState,v.PLAYING);return;case re.PAUSED:a===v.PLAYING?(this.videoState.startTransitionTo(re.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)===v.PAUSED&&(R(this.params.desiredState.playbackState,v.PAUSED),this.liveOffset.pause());return;case re.CHANGING_MANIFEST:break;default:return x(r)}},this.params=e,this.video=vt(e.container),this.params.output.element$.next(this.video);const s={id:"master",quality:ne.INVARIANT,url:this.params.source.url};this.manifests$.next([s]),Eu(ei(this.params.source.url),this.params.source.url).then(r=>{this.manifests$.next([s,...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(Re(this.params.source.url)),this.maxSeekBackTime$=new y((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:s,videoTrack:r}=this.params.desiredState,a=s.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,s=o=>{e.error$.next({id:"HlsLiveProvider",category:D.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=mt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,s));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(pt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Et(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(re.PLAYING),R(t.playbackState,v.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(re.PAUSED),R(t.playbackState,v.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===re.READY&&this.videoState.setState(re.READY),this.videoState.getState()===re.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.maxSeekBackTime$.pipe(me(),$(o=>-o/1e3)).subscribe(this.params.output.duration$,s)),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(Re(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===re.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===H.Requested&&this.seek(o.position)},s)),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)},s)),this.subscription.add(dt({startTime:this.manifestStartTime$.pipe(j(_)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),s)),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$,s));const n=L(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,Oe(["init"])).pipe(Ve(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),St(this.video)}prepare(){const e=this.selectManifest();if(K(e))return;const t=ei(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),Do(t).then(s=>{var r;if(!K(s))this.maxSeekBackTime$.next(s);else{const a=(r=this.params.source.maxSeekBackTime)!==null&&r!==void 0?r:this.maxSeekBackTime$.getValue();if(K(a)||!isFinite(a))try{ti(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();Do(d).then(l=>{K(l)||this.maxSeekBackTime$.next(l)})}})}catch(n){}}})}playIfAllowed(){$t(this.video).then(e=>{e||(this.videoState.setState(re.PAUSED),this.liveOffset.pause(),R(this.params.desiredState.playbackState,v.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,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3),this.params.output.seekedEvent$.next()}}var de;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(de||(de={}));class ay{constructor(e){this.subscription=new se,this.videoState=new le(de.STOPPED),this.textTracksManager=new it,this.manifests$=new y([]),this.syncPlayback=()=>{const s=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===v.STOPPED){s!==de.STOPPED&&(this.videoState.startTransitionTo(de.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(de.STOPPED),R(this.params.desiredState.playbackState,v.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.seekState.getState();if(s===de.STOPPED){this.videoState.startTransitionTo(de.READY),this.prepare();return}if(n||o){const l=this.videoState.getState();this.videoState.setState(de.CHANGING_MANIFEST),this.videoState.startTransitionTo(l);const{currentTime:c}=this.video;this.prepare(),d.state===H.None&&this.params.desiredState.seekState.setState({state:H.Requested,position:c*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==v.PAUSED&&d.state===H.Requested&&this.seek(d.position),s){case de.READY:r===v.READY?R(this.params.desiredState.playbackState,v.READY):r===v.PAUSED?(this.videoState.setState(de.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED)):r===v.PLAYING&&(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed());return;case de.PLAYING:r===v.PAUSED?(this.videoState.startTransitionTo(de.PAUSED),this.video.pause()):(a==null?void 0:a.to)===v.PLAYING&&R(this.params.desiredState.playbackState,v.PLAYING);return;case de.PAUSED:r===v.PLAYING?(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===v.PAUSED&&R(this.params.desiredState.playbackState,v.PAUSED);return;case de.CHANGING_MANIFEST:break;default:return x(s)}},this.params=e,this.video=vt(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:ne.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(Re(this.params.source.url)),Eu(this.params.source.url).then(s=>{this.manifests$.next([t,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:D.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:s,videoTrack:r}=this.params.desiredState,a=s.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,s=o=>{e.error$.next({id:"HlsProvider",category:D.WTF,message:"HlsProvider internal logic error",thrown:o})},r=mt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(Ut(this.video,t.isLooped,s)),this.subscription.add(pt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Et(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(de.PLAYING),R(t.playbackState,v.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED),R(t.playbackState,v.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===de.READY&&this.videoState.setState(de.READY),this.videoState.getState()===de.PLAYING&&this.playIfAllowed()},s).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(Re(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===de.CHANGING_MANIFEST&&this.videoState.setState(u.to),o.state===H.Requested&&this.seek(o.position)},s))),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$,s));const n=L(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ve(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),St(this.video)}prepare(){const e=this.selectManifest();K(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){$t(this.video).then(e=>{e||(this.videoState.setState(de.PAUSED),R(this.params.desiredState.playbackState,v.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 fe;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(fe||(fe={}));class ny{constructor(e){this.subscription=new se,this.videoState=new le(fe.STOPPED),this.trackUrls={},this.textTracksManager=new it,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(s===v.STOPPED){t!==fe.STOPPED&&(this.videoState.startTransitionTo(fe.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(fe.STOPPED),R(this.params.desiredState.playbackState,v.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.seekState.getState();if(t===fe.STOPPED){this.videoState.startTransitionTo(fe.READY),this.prepare();return}if(n){const{currentTime:u}=this.video;this.prepare(),o.state===H.None&&this.params.desiredState.seekState.setState({state:H.Requested,position:u*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!==v.PAUSED&&o.state===H.Requested&&this.seek(o.position),t){case fe.READY:s===v.READY?R(this.params.desiredState.playbackState,v.READY):s===v.PAUSED?(this.videoState.setState(fe.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED)):s===v.PLAYING&&(this.videoState.startTransitionTo(fe.PLAYING),this.playIfAllowed());return;case fe.PLAYING:s===v.PAUSED?(this.videoState.startTransitionTo(fe.PAUSED),this.video.pause()):(r==null?void 0:r.to)===v.PLAYING&&R(this.params.desiredState.playbackState,v.PLAYING);return;case fe.PAUSED:s===v.PLAYING?(this.videoState.startTransitionTo(fe.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===v.PAUSED&&R(this.params.desiredState.playbackState,v.PAUSED);return;default:return x(t)}},this.params=e,this.video=vt(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach(([t,s],r)=>{const a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:s}}),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,s=o=>{e.error$.next({id:"MpegProvider",category:D.WTF,message:"MpegProvider internal logic error",thrown:o})},r=mt(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,s));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(Ut(this.video,t.isLooped,s)),this.subscription.add(pt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Et(this.video,t.playbackRate,r.playbackRateState$,s)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(fe.PLAYING),R(t.playbackState,v.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(fe.PAUSED),R(t.playbackState,v.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===fe.READY&&this.videoState.setState(fe.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()===fe.PLAYING&&this.playIfAllowed()},s)),this.textTracksManager.connect(this.video,t,e);const n=L(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ve(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),St(this.video)}prepare(){var e,t;const s=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState();P(s,"MpegProvider: track is not selected");let{url:r}=this.trackUrls[s];P(r,`MpegProvider: No url for ${s}`),this.params.tuning.requestQuick&&(r=ii(r)),this.video.setAttribute("src",r),this.video.load(),this.params.output.hostname$.next(Re(r))}playIfAllowed(){$t(this.video).then(e=>{e||(this.videoState.setState(fe.PAUSED),R(this.params.desiredState.playbackState,v.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 Co=["stun:videostun.mycdn.me:80"],oy=1e3,dy=3,Dr=()=>null;class uy{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=Dr,this.externalStopCallback=Dr,this.externalErrorCallback=Dr,this.options=this.normalizeOptions(t);const s=e.split("/");this.serverUrl=s.slice(0,s.length-1).join("/"),this.streamKey=s[s.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return ue(this,void 0,void 0,function*(){try{const t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return ue(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:Co}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return ue(this,void 0,void 0,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return ue(this,void 0,void 0,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:D.WTF,message:e.message})}onPeerConnectionStream(e){return ue(this,void 0,void 0,function*(){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return ue(this,void 0,void 0,function*(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=yield this.peerConnection.createOffer(e),s=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(s))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),oy)}normalizeOptions(e={}){const t={stunServerList:Co,maxRetryNumber:dy,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var ae;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(ae||(ae={}));class ly{constructor(e){this.videoState=new le(ae.STOPPED),this.maxSeekBackTime$=new y(0),this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(s===v.STOPPED){t!==ae.STOPPED&&(this.videoState.startTransitionTo(ae.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(ae.STOPPED),R(this.params.desiredState.playbackState,v.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===ae.STOPPED){this.videoState.startTransitionTo(ae.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case ae.READY:s===v.PAUSED?(this.videoState.setState(ae.PAUSED),R(this.params.desiredState.playbackState,v.PAUSED)):s===v.PLAYING&&(this.videoState.startTransitionTo(ae.PLAYING),this.playIfAllowed());return;case ae.PLAYING:s===v.PAUSED?(this.videoState.startTransitionTo(ae.PAUSED),this.video.pause()):(r==null?void 0:r.to)===v.PLAYING&&R(this.params.desiredState.playbackState,v.PLAYING);return;case ae.PAUSED:s===v.PLAYING?(this.videoState.startTransitionTo(ae.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===v.PAUSED&&R(this.params.desiredState.playbackState,v.PAUSED);return;default:return x(t)}},this.subscription=new se,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=vt(e.container),this.liveStreamClient=new uy(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),St(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,s=n=>{e.error$.next({id:"WebRTCLiveProvider",category:D.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};L(this.videoState.stateChangeStarted$.pipe($(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe($(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const r=mt(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,s));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)===ae.READY&&this.videoState.setState(ae.READY)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(ae.PAUSED)},s)).add(r.playing$.subscribe(()=>{this.videoState.setState(ae.PLAYING)},s)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(pt(this.video,t.volume,r.volumeState$,s)).add(r.volumeState$.subscribe(e.volume$,s)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case ae.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(v.STOPPED);break;case ae.READY:break;case ae.PAUSED:t.playbackState.setState(v.PAUSED);break;case ae.PLAYING:t.playbackState.setState(v.PLAYING);break;default:return x(n.to)}},s)).add(L(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Oe(["init"])).pipe(Ve(0)).subscribe(this.syncPlayback.bind(this),s)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),s))}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(Re(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:ne.INVARIANT}),this.video.srcObject=e,R(this.params.desiredState.playbackState,v.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(ae.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(){$t(this.video).then(e=>{e||(this.videoState.setState(ae.PAUSED),R(this.params.desiredState.playbackState,v.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 Oo{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 cy=()=>{var i,e;const t=window.navigator;return t.userAgentData?((e=(i=t.userAgentData)===null||i===void 0?void 0:i.platform)===null||e===void 0?void 0:e.toLowerCase())==="android":window.navigator.userAgent.toLowerCase().includes("android")},Cr,Or,Lr,xr,Nr,Br,us,Mr,ls,Ur,cs,Fr,hs,Vr,fs,Hr;const $u=cy(),bt=document.createElement("video"),rt={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&((Or=(Cr=window.SourceBuffer)===null||Cr===void 0?void 0:Cr.prototype)===null||Or===void 0?void 0:Or.appendBuffer)),hls:Boolean(((Lr=bt.canPlayType)===null||Lr===void 0?void 0:Lr.call(bt,"application/x-mpegurl"))||((xr=bt.canPlayType)===null||xr===void 0?void 0:xr.call(bt,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection)},Ne={mp4:Boolean((Nr=bt.canPlayType)===null||Nr===void 0?void 0:Nr.call(bt,"video/mp4")),webm:Boolean((Br=bt.canPlayType)===null||Br===void 0?void 0:Br.call(bt,"video/webm")),cmaf:!0},yt={h264:Boolean((Mr=(us=window.MediaSource)===null||us===void 0?void 0:us.isTypeSupported)===null||Mr===void 0?void 0:Mr.call(us,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean((Ur=(ls=window.MediaSource)===null||ls===void 0?void 0:ls.isTypeSupported)===null||Ur===void 0?void 0:Ur.call(ls,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean((Fr=(cs=window.MediaSource)===null||cs===void 0?void 0:cs.isTypeSupported)===null||Fr===void 0?void 0:Fr.call(cs,'video/webm; codecs="vp9"')),aac:Boolean((Vr=(hs=window.MediaSource)===null||hs===void 0?void 0:hs.isTypeSupported)===null||Vr===void 0?void 0:Vr.call(hs,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean((Hr=(fs=window.MediaSource)===null||fs===void 0?void 0:fs.isTypeSupported)===null||Hr===void 0?void 0:Hr.call(fs,'audio/webm; codecs="opus"'))},zt=(yt.h264||yt.h265)&&yt.aac,Hs=rt.hls&&Ne.mp4,hy=Boolean(window.WebSocket),fy=()=>Object.keys(yt).filter(i=>yt[i]),py=(i,e=!1)=>i.filter(t=>{switch(t){case b.DASH:return rt.mse&&Ne.mp4&&zt;case b.DASH_SEP:return rt.mse&&Ne.mp4&&zt;case b.DASH_WEBM:return rt.mse&&Ne.webm&&yt.vp9&&yt.opus;case b.DASH_LIVE:return rt.mse&&Ne.mp4&&zt;case b.DASH_LIVE_CMAF:return rt.mse&&Ne.mp4&&zt&&Ne.cmaf;case b.DASH_ONDEMAND:return rt.mse&&Ne.mp4&&zt;case b.HLS:case b.HLS_LIVE:case b.HLS_LIVE_CMAF:case b.HLS_ONDEMAND:return Hs||e&&rt.mse&&Ne.mp4&&zt;case b.MPEG:return Ne.mp4;case b.DASH_LIVE_WEBM:return!1;case b.WEB_RTC_LIVE:return rt.webrtc&&hy&&yt.h264&&(Ne.mp4||Ne.webm);default:return x(t)}}),vy=()=>$u?[b.MPEG,b.DASH_WEBM,b.DASH_SEP,b.DASH,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND]:Hs?[b.DASH_WEBM,b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG,b.DASH]:[b.DASH_WEBM,b.DASH_SEP,b.DASH,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG],my=()=>$u?[b.HLS_LIVE,b.HLS_LIVE_CMAF,b.WEB_RTC_LIVE,b.DASH_LIVE,b.DASH_LIVE_CMAF]:Hs?[b.WEB_RTC_LIVE,b.HLS_LIVE,b.HLS_LIVE_CMAF,b.DASH_LIVE,b.DASH_LIVE_CMAF]:[b.WEB_RTC_LIVE,b.DASH_LIVE,b.DASH_LIVE_CMAF,b.HLS_LIVE,b.HLS_LIVE_CMAF],Lo=i=>i?[b.HLS_LIVE]:[b.DASH_WEBM,b.DASH_SEP,b.DASH_ONDEMAND,b.HLS,b.HLS_ONDEMAND,b.MPEG];var Sy=i=>new Ii(e=>{const t=new se,s=i.desiredPlaybackState$.stateChangeStarted$.pipe($(({from:d,to:l})=>`${d}-${l}`)),r=i.desiredPlaybackState$.stateChangeEnded$,a=i.providerChanged$,n=new O;let o=0,u="unknown";return t.add(s.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>n.next(d),i.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="provider change",o=0})),t.add(a.subscribe(()=>{o&&(window.clearTimeout(o),o=window.setTimeout(()=>n.next(u),i.maxTransitionInterval))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const xo={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},gy={cacheDuration:12e4},by={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},yy={maxPausedTime:3e4},No={maxPausedTime:3e4};class Ty{constructor(e){this.current$=new y({type:void 0}),this.providerError$=new O,this.noAvailableProvidersError$=new O,this.providerOutput={position$:new y(0),duration$:new y(1/0),volume$:new y({muted:!1,volume:1}),currentVideoTrack$:new y(void 0),availableVideoTracks$:new y([]),availableAudioTracks$:new y([]),isAudioAvailable$:new y(!0),autoVideoTrackLimitingAvailable$:new y(!1),currentBuffer$:new y(void 0),isBuffering$:new y(!0),error$:new O,willSeekEvent$:new O,seekedEvent$:new O,loopedEvent$:new O,endedEvent$:new O,firstBytesEvent$:new O,firstFrameEvent$:new O,canplay$:new O,isLive$:new y(void 0),liveTime$:new y(void 0),availableTextTracks$:new y([]),currentTextTrack$:new y(void 0),hostname$:new y(void 0),httpConnectionType$:new y(void 0),httpConnectionReused$:new y(void 0),element$:new y(void 0)},this.subscription=new se,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=py([...my(),...vy()],this.params.tuning.useHlsJs).filter(n=>_(e.sources[n])),{formatsToAvoid:s}=this.params.tuning,r=s.length?[...t.filter(n=>!s.includes(n)),...t.filter(n=>s.includes(n))]:t;this.screenFormatsIterator=new Oo(r);const a=[...Lo(!0),...Lo(!1)];this.chromecastFormatsIterator=new Oo(a.filter(n=>_(e.sources[n])))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(K(t)){this.handleNoFormatsError(e);return}let s;try{s=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:D.WTF,message:"Failed to create provider",thrown:r})}s?this.current$.next({type:t,provider:s,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const e=this.current$.getValue().destination;P(e,"No current provider"),this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,s=this.params.desiredState.seekState.getState(),r=s.state!==H.None;this.params.desiredState.seekState.setState({state:H.Requested,position:r?s.position:t,forcePrecise:r?s.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 De.SCREEN:return this.createScreenProvider(t);case De.CHROMECAST:return this.createChromecastProvider(t);default:return x(e)}}createScreenProvider(e){const{sources:t,container:s,desiredState:r}=this.params,a=this.providerOutput,n={container:s,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case b.DASH:{const o=this.applyFailoverHost(t[e]);return P(o),new jg(Object.assign(Object.assign({},n),{source:o,config:gy}))}case b.DASH_SEP:case b.DASH_WEBM:case b.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),this.params.tuning.useDashJs?new So(Object.assign(Object.assign({},n),{source:o,format:e,config:No})):new ey(Object.assign(Object.assign({},n),{source:o}))}case b.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new So(Object.assign(Object.assign({},n),{source:o,format:e,config:No}))}case b.HLS:case b.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),Hs||!this.params.tuning.useHlsJs?new ay(Object.assign(Object.assign({},n),{source:o})):new iy(Object.assign(Object.assign({},n),{source:o}))}case b.HLS_LIVE:case b.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new ry(Object.assign(Object.assign({},n),{source:o,config:yy}))}case b.MPEG:{const o=this.applyFailoverHost(t[e]);return P(o),new ny(Object.assign(Object.assign({},n),{source:o}))}case b.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new Vg(Object.assign(Object.assign({},n),{source:o,config:by}))}case b.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new ly({container:s,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case b.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return x(e)}}createChromecastProvider(e){const{sources:t,container:s,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return P(o),new QS({connection:o,meta:a,container:s,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?De.CHROMECAST:De.SCREEN}chooseFormat(e){switch(e){case De.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case De.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return x(e)}}skipFormat(e){switch(e){case De.SCREEN:return this.screenFormatsIterator.next();case De.CHROMECAST:return this.chromecastFormatsIterator.next();default:return x(e)}}handleNoFormatsError(e){switch(e){case De.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case De.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return x(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const s=r=>{const a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return Object.assign(Object.assign({},e),{url:s(e.url)})}return Bi(Object.entries(e).map(([r,a])=>[r,s(a)]))}initProviderErrorHandling(){const e=new se;let t=!1,s=0;return e.add(L(this.providerOutput.error$,Sy({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:xo.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(j(({type:r})=>r!==void 0))}).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(j(({to:a})=>a===v.PLAYING),ye()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{if(this.current$.getValue().destination===De.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const a=r.category===D.NETWORK,n=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),o=s<xo.providerErrorLimit;n&&(a&&t||!o)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):o?(s++,this.reinitProvider()):this.switchToNextProvider()}})),e}}var Fe;(function(i){i[i.LOCAL_STORAGE=0]="LOCAL_STORAGE",i[i.SESSION_STORAGE=1]="SESSION_STORAGE",i[i.RUNTIME=2]="RUNTIME"})(Fe||(Fe={}));const Au=new Map;let Ct=Fe.RUNTIME;const Gr=`vk-videoplayer-dummy-key-${Math.random()}`,Ey=()=>{try{localStorage.setItem(Gr,"test"),localStorage.removeItem(Gr),Ct=Fe.LOCAL_STORAGE}catch(i){if(i instanceof DOMException||i instanceof TypeError)try{sessionStorage.getItem(Gr),Ct=Fe.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)Ct=Fe.RUNTIME;else throw e}else throw i}};Ey();const $y=i=>{var e,t;switch(Ct){case Fe.LOCAL_STORAGE:return(e=localStorage.getItem(i))!==null&&e!==void 0?e:void 0;case Fe.SESSION_STORAGE:return(t=sessionStorage.getItem(i))!==null&&t!==void 0?t:void 0;case Fe.RUNTIME:return Au.get(i);default:x(Ct)}},Bo=(i,e)=>{switch(Ct){case Fe.LOCAL_STORAGE:try{localStorage.setItem(i,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Fe.SESSION_STORAGE:try{sessionStorage.setItem(i,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Fe.RUNTIME:return void Au.set(i,e);default:x(Ct)}},ha=(i,e,t)=>t*e+(1-t)*i,wu=(i,e)=>i.reduce((t,s)=>t+s,0)/e,Ay=(i,e,t,s)=>{let r=0,a=t;const n=wu(i,e),o=e<s?e:s;for(let u=0;u<o;u++)i[a]>n?r++:r--,a=(i.length+a-1)%i.length;return Math.abs(r)===o};class _u{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new y(e.initial),this.debounced$=new y(e.initial);const s=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ze(`raw_${s}`),this.smoothedSeries$=new Ze(`smoothed_${s}`),this.reportedSeries$=new Ze(`reported_${s}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,s=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=Math.pow(this.pastMeasures[o]-this.smoothed,2),s++);this.takenMeasures=s,t/=s;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)&&(K(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 wy extends _u{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ha(this.slow,e,this.params.emaAlphaSlow),this.fast=ha(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class _y extends _u{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=wu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ha(this.emaSmoothed,e,this.params.emaAlpha);const s=Ay(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class Mo{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new wy({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new _y({initial:e,emaAlpha:s.emaAlpha,basisTrendChangeCount:s.basisTrendChangeCount,changeThreshold:s.changeThreshold,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"})}}const ky=5e3,Uo="one_video_throughput",Fo="one_video_rtt",lt=window.navigator.connection,Vo=()=>{const i=lt==null?void 0:lt.downlink;if(_(i)&&i!==10)return i*1e3},Ho=()=>{const i=lt==null?void 0:lt.rtt;if(_(i)&&i!==3e3)return i},Go=(i,e,t)=>{const s=t*8,r=s/i;return s/(r+e)};class _i{constructor(e){var t,s;this.subscription=new se,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=_i.load(Uo)||(e.useBrowserEstimation?Vo():void 0)||ky,a=(s=(t=_i.load(Fo))!==null&&t!==void 0?t:e.useBrowserEstimation?Ho():void 0)!==null&&s!==void 0?s:0;if(this.throughput$=new y(r),this.rtt$=new y(a),this.rttAdjustedThroughput$=new y(Go(r,a,e.rttPenaltyRequestSize)),this.throughput=Mo.getSmoothedValue(r,-1,e),this.rtt=Mo.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const u=Vo();u&&this.throughput.next(u);const d=Ho();_(d)&&this.rtt.next(d)};lt&&"onchange"in lt&&this.subscription.add(U(lt,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Bo(Uo,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Bo(Fo,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(dt({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe($(({throughput:n,rtt:o})=>Go(n,o,e.rttPenaltyRequestSize)),j(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,s=pe();const r=new se;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(U(e,"progress").pipe(ye()).subscribe(a=>{t=a.loaded,s=pe()}));break;case 1:case 0:r.add(U(e,"loadstart").subscribe(()=>{t=0,s=pe()}));break}r.add(U(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=pe(),u=n-t,d=o-s;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 s=0;const r=pe();let a=0,n=pe();const o=d=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},u=({done:d,value:l})=>ue(this,void 0,void 0,function*(){d?(this.addRawSpeed(s,pe()-r,1),this.concurrentDownloads.delete(e)):l&&(s+=l.byteLength,a+=l.byteLength,a>=this.tuningConfig.streamMinSampleSize&&pe()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,pe()-n,this.concurrentDownloads.size),a=0,n=pe()),yield t==null?void 0:t.read().then(u,o))});this.concurrentDownloads.add(e),t==null||t.read().then(u,o)}addRawSpeed(e,t,s=1){if(_i.sanityCheck(e,t)){const r=e*8/t;this.throughput.next(r*s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const s=e*8/t;return!(!s||!isFinite(s)||s>1e6||s<30||e<10*1024||t<=20)}static load(e){var t;const s=$y(e);if(_(s))return(t=parseInt(s,10))!==null&&t!==void 0?t:void 0}}const Yo={throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useHlsJs:!0,isAudioDisabled:!1,webrtc:{connectionRetryMaxNumber:3}},Py=i=>{const e={};for(const t of Object.keys(Yo)){const s=Yo[t],r=i[t];Array.isArray(s)&&Array.isArray(r)?e[t]=r:typeof s=="object"&&typeof r=="object"?e[t]=Object.assign(Object.assign({},s),r):e[t]=r!=null?r:s}return e};var Ry=({seekState:i,position$:e})=>L(i.stateChangeEnded$.pipe($(({to:t})=>{var s;return t.state===H.None?void 0:((s=t.position)!==null&&s!==void 0?s:NaN)/1e3}),j(_)),e.pipe(j(()=>i.getState().state===H.None))),Iy=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return P(e,`Wrong container or containerId {${i.container}}`),e};const qo=({playbackState:i,seekState:e,playbackAbort$:t,looped$:s,position$:r})=>new Ii(a=>{let n;const o=i.transitionEnded$.pipe(j(f=>(f.from===v.PAUSED||f.from===v.STOPPED)&&f.to===v.PLAYING)),u=i.stateChangeEnded$.pipe(j(f=>f.from===v.PLAYING&&f.to===v.PAUSED)),d=e.stateChangeEnded$.pipe(j(({to:f})=>{var m,p;return f.state===H.Requested&&((p=(m=i.getTransition())===null||m===void 0?void 0:m.from)!==null&&p!==void 0?p:i.getState())===v.PLAYING})),l=e.stateChangeEnded$.pipe(j(({from:f,to:m})=>{var p,S;return f.state===H.Applying&&m.state===H.None&&((S=(p=i.getTransition())===null||p===void 0?void 0:p.from)!==null&&S!==void 0?S:i.getState())===v.PLAYING})),c=L(o,l).pipe($(()=>r.getValue()),j(_)),h=L(L(u,d,t),s).pipe($(()=>r.getValue()),j(_));return new se().add(c.subscribe(f=>{n=f})).add(h.subscribe(f=>{if(K(n)||n===f)return;const m={from:n,to:f};n=void 0,a.next(m)}))});class Ny{constructor(e={}){if(this.subscription=new se,this.logger=new zu,this.isPlaybackStarted=!1,this.desiredState={playbackState:new le(v.STOPPED),seekState:new le({state:H.None}),volume:new le({volume:1,muted:!1}),videoTrack:new le(void 0),autoVideoTrackSwitching:new le(!0),autoVideoTrackLimits:new le({}),isLooped:new le(!1),playbackRate:new le(1),externalTextTracks:new le([]),currentTextTrack:new le(void 0),textTrackCuesSettings:new le({})},this.info={playbackState$:new y(v.STOPPED),position$:new y(0),duration$:new y(1/0),muted$:new y(!1),volume$:new y(1),availableQualities$:new y([]),availableQualitiesFps$:new y({}),availableAudioTracks$:new y([]),isAudioAvailable$:new y(!0),currentQuality$:new y(void 0),isAutoQualityEnabled$:new y(!0),autoQualityLimitingAvailable$:new y(!1),autoQualityLimits$:new y({}),currentPlaybackRate$:new y(1),currentBuffer$:new y({start:0,end:0}),isBuffering$:new y(!0),isStalled$:new y(!1),isEnded$:new y(!1),isLooped$:new y(!1),isLive$:new y(void 0),liveTime$:new y(void 0),currentFormat$:new y(void 0),availableTextTracks$:new y([]),currentTextTrack$:new y(void 0),throughputEstimation$:new y(void 0),rttEstimation$:new y(void 0),videoBitrate$:new y(void 0),hostname$:new y(void 0),httpConnectionType$:new y(void 0),httpConnectionReused$:new y(void 0),chromecastState$:new y(we.NOT_AVAILABLE),chromecastDeviceName$:new y(void 0),intrinsicVideoSize$:new y(void 0)},this.events={inited$:new O,started$:new O,willPause$:new O,willResume$:new O,willDestruct$:new O,watchCoverageRecord$:new O,watchCoverageLive$:new O,managedError$:new O,fatalError$:new O,ended$:new O,looped$:new O,seeked$:new O,willSeek$:new O,firstBytes$:new O,firstFrame$:new O,canplay$:new O,log$:new O},this.experimental={element$:new y(void 0),enableDebugTelemetry$:new y(!1),dumpTelemetry:yg},this.initLogs(),this.tuning=Py(e),this.chromecastInitializer=new Xu({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new _i(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,s,r)=>{const a=Reflect.get(t,s,r);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const u=n.map(c=>JSON.stringify(c,(h,f)=>{const m=typeof f;return["number","string","boolean"].includes(m)?f:f===null?null:`<${m}>`})),d=`Player.${String(s)}`,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,s,r;return this.config=e,this.domContainer=Iy(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Ty({sources:e.sources,meta:(s=e.meta)!==null&&s!==void 0?s:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.events.willDestruct$.next(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===v.STOPPED&&e.startTransitionTo(v.READY),this}play(){const e=this.desiredState.playbackState;return e.getState()!==v.PLAYING&&e.startTransitionTo(v.PLAYING),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==v.PAUSED&&e.startTransitionTo(v.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==v.STOPPED&&e.startTransitionTo(v.STOPPED),this}seekTime(e,t=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:H.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()===we.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()===we.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){P(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const s=t.find(r=>r.quality===e);return s&&this.desiredState.videoTrack.startTransitionTo(s.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.setState(e),this}setPlaybackRate(e){var t;P(this.providerContainer);const s=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return s&&(this.desiredState.playbackRate.setState(e),s.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>Object.assign({type:"external"},t))),this}selectTextTrack(e){var t;return(e===void 0||!((t=this.providerContainer)===null||t===void 0)&&t.providerOutput.availableTextTracks$.getValue().find(s=>s.id===e))&&this.desiredState.currentTextTrack.startTransitionTo(e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){P(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(K(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),s=t.state===H.None?void 0:t.position;return _(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}setIntrinsicVideoSize(...e){const t={width:e.reduce((s,{width:r})=>s||r||0,0),height:e.reduce((s,{height:r})=>s||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(L(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe($(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe($(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(j(({from:e})=>e===v.STOPPED),ye()).subscribe(()=>{this.initedAt=pe(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.pipe(j(()=>!this.isPlaybackStarted),j(e=>e.to===v.PLAYING)).subscribe(()=>{this.isPlaybackStarted=!0,this.events.started$.next()})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case v.PAUSED:this.events.willPause$.next();break;case v.PLAYING:this.isPlaybackStarted&&this.events.willResume$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const u=this.desiredState.seekState.getState();u.state===H.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},u),{state:H.Applying})):this.events.managedError$.next({id:`WillSeekIn${u.state}`,category:D.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===H.Applying&&(this.desiredState.seekState.setState({state:H.None}),this.events.seeked$.next())})).add(e.current$.pipe($(u=>u.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe($(u=>u.destination),me()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe($(u=>u.map(({quality:d})=>d).sort((d,l)=>As(d)?1:As(l)?-1:Ss(l,d)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(u=>{const d={};for(const l of u)l.fps&&(d[l.quality]=l.fps);this.info.availableQualitiesFps$.next(d)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(u=>{this.info.currentQuality$.next(u==null?void 0:u.quality),this.info.videoBitrate$.next(u==null?void 0:u.bitrate)})).add(e.providerOutput.hostname$.pipe(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($(u=>u?{start:u.from,end:u.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe($(u=>u.muted),me()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe($(u=>u.volume),me()).subscribe(this.info.volume$)).add(Ry({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(L(e.providerOutput.endedEvent$.pipe(Ot(!0)),e.providerOutput.seekedEvent$.pipe(Ot(!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($(u=>({id:"NoProviders",category:D.VIDEO_PIPELINE,message:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(ye(),$(()=>pe()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(ye(),$(()=>pe()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(ye(),$(()=>pe()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const t=new y(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const s=new y(!0);this.subscription.add(e.current$.subscribe(()=>s.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(j(({to:u})=>u===v.PLAYING),ye()).subscribe(()=>s.next(!1)));let r=0;const a=L(e.providerOutput.isBuffering$,t,s).pipe($(()=>{const u=e.providerOutput.isBuffering$.getValue(),d=t.getValue()||s.getValue();return u&&!d}),me());this.subscription.add(a.subscribe(u=>{u?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))}));const n=new se;this.subscription.add(n);const o=L(U(window,"beforeunload"),this.events.willDestruct$,e.current$.pipe(j(u=>Boolean(u==null?void 0:u.provider))));e.providerOutput.isLive$.pipe(me()).subscribe(u=>{switch(P(this.providerContainer),n.unsubscribe(),u){case!0:{const d=new y(void 0);n.add(this.providerContainer.providerOutput.liveTime$.subscribe(l=>d.next(l&&Math.floor(l/1e3)))),n.add(qo({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:o,looped$:this.events.looped$,position$:d}).pipe($(({from:l,to:c})=>({start:l,end:c}))).subscribe(this.events.watchCoverageLive$));break}case!1:n.add(qo({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:o,position$:this.providerContainer.providerOutput.position$}).pipe($(({from:d,to:l})=>({start:d,end:l}))).subscribe(this.events.watchCoverageRecord$));break}}),this.subscription.add(L(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:u==null?void 0:u.videoWidth,height:u==null?void 0:u.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(u=>{var d,l;const c=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(d=u==null?void 0:u.size)===null||d===void 0?void 0:d.width,height:(l=u==null?void 0:u.size)===null||l===void 0?void 0:l.height},{width:c==null?void 0:c.videoWidth,height:c==null?void 0:c.videoHeight})}))}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 se;this.subscription.add(t),this.subscription.add(e.current$.pipe(me((s,r)=>s.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(j(s=>s.length>0),ye()).subscribe(s=>{this.setStartingVideoTrack(s)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:s})=>s===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=Fi(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0})),this.desiredState.videoTrack.startTransitionTo(t.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(L(this.desiredState.videoTrack.stateChangeStarted$.pipe($(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe($(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe($(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe($(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe($(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe($(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe($(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe($(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe($(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;P(this.providerContainer),P(t),bg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(s=>gg(s)),this.providerContainer.current$.subscribe(({type:s})=>as("provider",s)),t.duration$.subscribe(s=>as("duration",s)),t.availableVideoTracks$.pipe(j(s=>!!s.length),ye()).subscribe(s=>as("tracks",s)),this.events.fatalError$.subscribe(new Ze("fatalError")),this.events.managedError$.subscribe(new Ze("managedError")),t.position$.subscribe(new Ze("position")),t.currentVideoTrack$.pipe($(s=>s==null?void 0:s.quality)).subscribe(new Ze("quality")),this.info.currentBuffer$.subscribe(new Ze("buffer")),t.isBuffering$.subscribe(new Ze("isBuffering"))].forEach(s=>this.subscription.add(s)),as("codecs",fy())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},s=()=>ue(this,void 0,void 0,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:D.DOM,message:String(r)})})});this.subscription.add(L(U(document,"visibilitychange"),U(document,"fullscreenchange"),this.desiredState.playbackState.transitionEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===v.PLAYING,n=Boolean(e)&&!(e!=null&&e.released);r&&a?n||s():t()})).add(this.events.willDestruct$.subscribe(t))}}const By=`${Ju}@${Qu}`;export{we as ChromecastState,ki as HttpConnectionType,Fy as Observable,v as PlaybackState,Ny as Player,By as SDK_VERSION,Vy as Subject,Hy as Subscription,Gy as ValueSubject,b as VideoFormat,ne as VideoQuality};