@vkontakte/videoplayer-core 2.0.78 → 2.0.79
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +6 -6
- package/es2015.esm.js +6 -6
- package/es2018.cjs.js +6 -6
- package/es2018.esm.js +6 -6
- package/esnext.cjs.js +6 -6
- package/esnext.esm.js +6 -6
- package/index.d.ts +6 -0
- package/package.json +3 -3
package/es2015.cjs.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.79
|
|
3
|
+
* Fri, 03 Mar 2023 15:20:00 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-79/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var ru=Object.create;var pa=Object.defineProperty;var su=Object.getOwnPropertyDescriptor;var au=Object.getOwnPropertyNames;var nu=Object.getPrototypeOf,ou=Object.prototype.hasOwnProperty;var lu=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of au(e))!ou.call(i,s)&&s!==t&&pa(i,s,{get:()=>e[s],enumerable:!(r=su(e,s))||r.enumerable});return i};var ma=(i,e,t)=>(t=i!=null?ru(nu(i)):{},lu(e||!i||!i.__esModule?pa(t,"default",{value:i,enumerable:!0}):t,i));var a=require("@vkontakte/videoplayer-shared/es2015.cjs.js"),uu=require("lodash/debounce.js");const du="2.0.78",cu="@vkontakte/videoplayer-core";exports.PlaybackState=void 0;(function(i){i.STOPPED="stopped",i.PLAYING="playing",i.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(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_WEBM="DASH_LIVE_WEBM",i.HLS="HLS",i.HLS_ONDEMAND="HLS_ONDEMAND",i.HLS_JS="HLS",i.HLS_LIVE="HLS_LIVE",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(exports.VideoFormat||(exports.VideoFormat={}));var he;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(he||(he={}));exports.ChromecastState=void 0;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var D;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(D||(D={}));var hu=i=>new Promise((e,t)=>{const r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});class fu{constructor(e){var t;this.connection$=new a.ValueSubject(void 0),this.castState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new a.Subject,this.realCastState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const r="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${r}`}),e.isDisabled||!r)return;const s=a.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=Boolean(window.__onGCastApiAvailable);s?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||hu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:a.ErrorCategory.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 r,s,n;(n=(s=(r=cast.framework.CastContext.getInstance())===null||r===void 0?void 0:r.getCurrentSession())===null||s===void 0?void 0:s.getMediaSession())===null||n===void 0||n.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){a.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();a.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();a.isNullable(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),r=cast.framework.CastContext.getInstance();this.subscription.add(a.fromEvent(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(s=>{var n,o;switch(s.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=r.getCurrentSession())===null||n===void 0?void 0:n.getMediaSession())===null||o===void 0?void 0:o.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 a.assertNever(s.sessionState)}})).add(a.merge(a.fromEvent(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(a.tap(s=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(s)}`})}),a.map(s=>s.castState)),a.observableFrom([r.getCastState()])).pipe(a.filterChanged(),a.map(pu),a.tap(s=>{this.log({message:`realCastState$: ${s}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(s=>{var n;const o=s===exports.ChromecastState.CONNECTED,l=a.isNonNullable(this.connection$.getValue());if(o&&!l){const d=r.getCurrentSession();a.assertNonNullable(d);const u=d.getCastDevice(),c=(n=d.getMediaSession())===null||n===void 0?void 0:n.media.contentId;(a.isNullable(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:d,castDevice:u}))}else!o&&l&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(s===exports.ChromecastState.CONNECTED?a.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:s)}))}initializeCastApi(){var e;let t,r,s;try{t=cast.framework.CastContext.getInstance(),r=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,s=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:r,autoJoinPolicy:s}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:a.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const pu=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return exports.ChromecastState.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return exports.ChromecastState.AVAILABLE;case cast.framework.CastState.CONNECTING:return exports.ChromecastState.CONNECTING;case cast.framework.CastState.CONNECTED:return exports.ChromecastState.CONNECTED;default:return a.assertNever(i)}};var va=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},ye=function(i){try{return!!i()}catch(e){return!0}},mu=ye,er=!mu(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),so=er,ao=Function.prototype,hs=ao.call,vu=so&&ao.bind.bind(hs,hs),Ce=so?vu:function(i){return function(){return hs.apply(i,arguments)}},no=Ce,Su=no({}.toString),bu=no("".slice),tr=function(i){return bu(Su(i),8,-1)},gu=Ce,yu=ye,Tu=tr,Sr=Object,Eu=gu("".split),$u=yu(function(){return!Sr("z").propertyIsEnumerable(0)})?function(i){return Tu(i)=="String"?Eu(i,""):Sr(i)}:Sr,ir=function(i){return i==null},Pu=ir,ku=TypeError,oo=function(i){if(Pu(i))throw ku("Can't call method on "+i);return i},_u=$u,wu=oo,si=function(i){return _u(wu(i))},Au=function(){},Ct={},vi=function(i){return i&&i.Math==Math&&i},le=vi(typeof globalThis=="object"&&globalThis)||vi(typeof window=="object"&&window)||vi(typeof self=="object"&&self)||vi(typeof va=="object"&&va)||function(){return this}()||Function("return this")(),fs=typeof document=="object"&&document.all,Ru=typeof fs=="undefined"&&fs!==void 0,lo={all:fs,IS_HTMLDDA:Ru},uo=lo,Iu=uo.all,se=uo.IS_HTMLDDA?function(i){return typeof i=="function"||i===Iu}:function(i){return typeof i=="function"},Nu=le,Cu=se,Sa=Nu.WeakMap,Du=Cu(Sa)&&/native code/.test(String(Sa)),ba=se,co=lo,Ou=co.all,Ke=co.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:ba(i)||i===Ou}:function(i){return typeof i=="object"?i!==null:ba(i)},Lu=ye,Ue=!Lu(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),dt={},xu=le,ga=Ke,ps=xu.document,Bu=ga(ps)&&ga(ps.createElement),Ds=function(i){return Bu?ps.createElement(i):{}},Mu=Ue,Vu=ye,Fu=Ds,ho=!Mu&&!Vu(function(){return Object.defineProperty(Fu("div"),"a",{get:function(){return 7}}).a!=7}),Uu=Ue,ju=ye,fo=Uu&&ju(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Hu=Ke,Gu=String,qu=TypeError,Xe=function(i){if(Hu(i))return i;throw qu(Gu(i)+" is not an object")},Yu=er,Si=Function.prototype.call,Pe=Yu?Si.bind(Si):function(){return Si.apply(Si,arguments)},Os={},br=Os,gr=le,zu=se,ya=function(i){return zu(i)?i:void 0},ct=function(i,e){return arguments.length<2?ya(br[i])||ya(gr[i]):br[i]&&br[i][e]||gr[i]&&gr[i][e]},Wu=Ce,Ls=Wu({}.isPrototypeOf),rr=typeof navigator!="undefined"&&String(navigator.userAgent)||"",po=le,yr=rr,Ta=po.process,Ea=po.Deno,$a=Ta&&Ta.versions||Ea&&Ea.version,Pa=$a&&$a.v8,Te,Hi;Pa&&(Te=Pa.split("."),Hi=Te[0]>0&&Te[0]<4?1:+(Te[0]+Te[1]));!Hi&&yr&&(Te=yr.match(/Edge\/(\d+)/),(!Te||Te[1]>=74)&&(Te=yr.match(/Chrome\/(\d+)/),Te&&(Hi=+Te[1])));var mo=Hi,ka=mo,Qu=ye,vo=!!Object.getOwnPropertySymbols&&!Qu(function(){var i=Symbol();return!String(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&ka&&ka<41}),Ju=vo,So=Ju&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Ku=ct,Xu=se,Zu=Ls,ed=So,td=Object,bo=ed?function(i){return typeof i=="symbol"}:function(i){var e=Ku("Symbol");return Xu(e)&&Zu(e.prototype,td(i))},id=String,sr=function(i){try{return id(i)}catch(e){return"Object"}},rd=se,sd=sr,ad=TypeError,ht=function(i){if(rd(i))return i;throw ad(sd(i)+" is not a function")},nd=ht,od=ir,xs=function(i,e){var t=i[e];return od(t)?void 0:nd(t)},Tr=Pe,Er=se,$r=Ke,ld=TypeError,ud=function(i,e){var t,r;if(e==="string"&&Er(t=i.toString)&&!$r(r=Tr(t,i))||Er(t=i.valueOf)&&!$r(r=Tr(t,i))||e!=="string"&&Er(t=i.toString)&&!$r(r=Tr(t,i)))return r;throw ld("Can't convert object to primitive value")},Gi={},dd={get exports(){return Gi},set exports(i){Gi=i}},go=!0,_a=le,cd=Object.defineProperty,hd=function(i,e){try{cd(_a,i,{value:e,configurable:!0,writable:!0})}catch(t){_a[i]=e}return e},fd=le,pd=hd,wa="__core-js_shared__",md=fd[wa]||pd(wa,{}),Bs=md,Aa=Bs;(dd.exports=function(i,e){return Aa[i]||(Aa[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 vd=oo,Sd=Object,Ms=function(i){return Sd(vd(i))},bd=Ce,gd=Ms,yd=bd({}.hasOwnProperty),je=Object.hasOwn||function(e,t){return yd(gd(e),t)},Td=Ce,Ed=0,$d=Math.random(),Pd=Td(1 .toString),yo=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Pd(++Ed+$d,36)},kd=le,_d=Gi,Ra=je,wd=yo,Ad=vo,Rd=So,Tt=kd.Symbol,Pr=_d("wks"),Id=Rd?Tt.for||Tt:Tt&&Tt.withoutSetter||wd,pe=function(i){return Ra(Pr,i)||(Pr[i]=Ad&&Ra(Tt,i)?Tt[i]:Id("Symbol."+i)),Pr[i]},Nd=Pe,Ia=Ke,Na=bo,Cd=xs,Dd=ud,Od=pe,Ld=TypeError,xd=Od("toPrimitive"),Bd=function(i,e){if(!Ia(i)||Na(i))return i;var t=Cd(i,xd),r;if(t){if(e===void 0&&(e="default"),r=Nd(t,i,e),!Ia(r)||Na(r))return r;throw Ld("Can't convert object to primitive value")}return e===void 0&&(e="number"),Dd(i,e)},Md=Bd,Vd=bo,Vs=function(i){var e=Md(i,"string");return Vd(e)?e:e+""},Fd=Ue,Ud=ho,jd=fo,bi=Xe,Ca=Vs,Hd=TypeError,kr=Object.defineProperty,Gd=Object.getOwnPropertyDescriptor,_r="enumerable",wr="configurable",Ar="writable";dt.f=Fd?jd?function(e,t,r){if(bi(e),t=Ca(t),bi(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Ar in r&&!r[Ar]){var s=Gd(e,t);s&&s[Ar]&&(e[t]=r.value,r={configurable:wr in r?r[wr]:s[wr],enumerable:_r in r?r[_r]:s[_r],writable:!1})}return kr(e,t,r)}:kr:function(e,t,r){if(bi(e),t=Ca(t),bi(r),Ud)try{return kr(e,t,r)}catch(s){}if("get"in r||"set"in r)throw Hd("Accessors not supported");return"value"in r&&(e[t]=r.value),e};var ar=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},qd=Ue,Yd=dt,zd=ar,ai=qd?function(i,e,t){return Yd.f(i,e,zd(1,t))}:function(i,e,t){return i[e]=t,i},Wd=Gi,Qd=yo,Da=Wd("keys"),Fs=function(i){return Da[i]||(Da[i]=Qd(i))},Us={},Jd=Du,To=le,Kd=Ke,Xd=ai,Rr=je,Ir=Bs,Zd=Fs,ec=Us,Oa="Object already initialized",ms=To.TypeError,tc=To.WeakMap,qi,ii,Yi,ic=function(i){return Yi(i)?ii(i):qi(i,{})},rc=function(i){return function(e){var t;if(!Kd(e)||(t=ii(e)).type!==i)throw ms("Incompatible receiver, "+i+" required");return t}};if(Jd||Ir.state){var Ae=Ir.state||(Ir.state=new tc);Ae.get=Ae.get,Ae.has=Ae.has,Ae.set=Ae.set,qi=function(i,e){if(Ae.has(i))throw ms(Oa);return e.facade=i,Ae.set(i,e),e},ii=function(i){return Ae.get(i)||{}},Yi=function(i){return Ae.has(i)}}else{var St=Zd("state");ec[St]=!0,qi=function(i,e){if(Rr(i,St))throw ms(Oa);return e.facade=i,Xd(i,St,e),e},ii=function(i){return Rr(i,St)?i[St]:{}},Yi=function(i){return Rr(i,St)}}var Eo={set:qi,get:ii,has:Yi,enforce:ic,getterFor:rc},sc=er,$o=Function.prototype,La=$o.apply,xa=$o.call,Po=typeof Reflect=="object"&&Reflect.apply||(sc?xa.bind(La):function(){return xa.apply(La,arguments)}),ac=tr,nc=Ce,ko=function(i){if(ac(i)==="Function")return nc(i)},js={},_o={},wo={}.propertyIsEnumerable,Ao=Object.getOwnPropertyDescriptor,oc=Ao&&!wo.call({1:2},1);_o.f=oc?function(e){var t=Ao(this,e);return!!t&&t.enumerable}:wo;var lc=Ue,uc=Pe,dc=_o,cc=ar,hc=si,fc=Vs,pc=je,mc=ho,Ba=Object.getOwnPropertyDescriptor;js.f=lc?Ba:function(e,t){if(e=hc(e),t=fc(t),mc)try{return Ba(e,t)}catch(r){}if(pc(e,t))return cc(!uc(dc.f,e,t),e[t])};var vc=ye,Sc=se,bc=/#|\.prototype\./,ni=function(i,e){var t=yc[gc(i)];return t==Ec?!0:t==Tc?!1:Sc(e)?vc(e):!!e},gc=ni.normalize=function(i){return String(i).replace(bc,".").toLowerCase()},yc=ni.data={},Tc=ni.NATIVE="N",Ec=ni.POLYFILL="P",Ro=ni,Ma=ko,$c=ht,Pc=er,kc=Ma(Ma.bind),nr=function(i,e){return $c(i),e===void 0?i:Pc?kc(i,e):function(){return i.apply(e,arguments)}},gi=le,_c=Po,wc=ko,Ac=se,Rc=js.f,Ic=Ro,bt=Os,Nc=nr,gt=ai,Va=je,Cc=function(i){var e=function(t,r,s){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,r)}return new i(t,r,s)}return _c(i,this,arguments)};return e.prototype=i.prototype,e},De=function(i,e){var t=i.target,r=i.global,s=i.stat,n=i.proto,o=r?gi:s?gi[t]:(gi[t]||{}).prototype,l=r?bt:bt[t]||gt(bt,t,{})[t],d=l.prototype,u,c,h,f,p,v,m,S,b;for(f in e)u=Ic(r?f:t+(s?".":"#")+f,i.forced),c=!u&&o&&Va(o,f),v=l[f],c&&(i.dontCallGetSet?(b=Rc(o,f),m=b&&b.value):m=o[f]),p=c&&m?m:e[f],!(c&&typeof v==typeof p)&&(i.bind&&c?S=Nc(p,gi):i.wrap&&c?S=Cc(p):n&&Ac(p)?S=wc(p):S=p,(i.sham||p&&p.sham||v&&v.sham)&>(S,"sham",!0),gt(l,f,S),n&&(h=t+"Prototype",Va(bt,h)||gt(bt,h,{}),gt(bt[h],f,p),i.real&&d&&(u||!d[f])&>(d,f,p)))},vs=Ue,Dc=je,Io=Function.prototype,Oc=vs&&Object.getOwnPropertyDescriptor,Hs=Dc(Io,"name"),Lc=Hs&&function(){}.name==="something",xc=Hs&&(!vs||vs&&Oc(Io,"name").configurable),Bc={EXISTS:Hs,PROPER:Lc,CONFIGURABLE:xc},No={},Mc=Math.ceil,Vc=Math.floor,Fc=Math.trunc||function(e){var t=+e;return(t>0?Vc:Mc)(t)},Uc=Fc,Gs=function(i){var e=+i;return e!==e||e===0?0:Uc(e)},jc=Gs,Hc=Math.max,Gc=Math.min,qc=function(i,e){var t=jc(i);return t<0?Hc(t+e,0):Gc(t,e)},Yc=Gs,zc=Math.min,Wc=function(i){return i>0?zc(Yc(i),9007199254740991):0},Qc=Wc,qs=function(i){return Qc(i.length)},Jc=si,Kc=qc,Xc=qs,Fa=function(i){return function(e,t,r){var s=Jc(e),n=Xc(s),o=Kc(r,n),l;if(i&&t!=t){for(;n>o;)if(l=s[o++],l!=l)return!0}else for(;n>o;o++)if((i||o in s)&&s[o]===t)return i||o||0;return!i&&-1}},Zc={includes:Fa(!0),indexOf:Fa(!1)},eh=Ce,Nr=je,th=si,ih=Zc.indexOf,rh=Us,Ua=eh([].push),sh=function(i,e){var t=th(i),r=0,s=[],n;for(n in t)!Nr(rh,n)&&Nr(t,n)&&Ua(s,n);for(;e.length>r;)Nr(t,n=e[r++])&&(~ih(s,n)||Ua(s,n));return s},Co=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],ah=sh,nh=Co,oh=Object.keys||function(e){return ah(e,nh)},lh=Ue,uh=fo,dh=dt,ch=Xe,hh=si,fh=oh;No.f=lh&&!uh?Object.defineProperties:function(e,t){ch(e);for(var r=hh(t),s=fh(t),n=s.length,o=0,l;n>o;)dh.f(e,l=s[o++],r[l]);return e};var ph=ct,Do=ph("document","documentElement"),mh=Xe,vh=No,ja=Co,Sh=Us,bh=Do,gh=Ds,yh=Fs,Ha=">",Ga="<",Ss="prototype",bs="script",Oo=yh("IE_PROTO"),Cr=function(){},Lo=function(i){return Ga+bs+Ha+i+Ga+"/"+bs+Ha},qa=function(i){i.write(Lo("")),i.close();var e=i.parentWindow.Object;return i=null,e},Th=function(){var i=gh("iframe"),e="java"+bs+":",t;return i.style.display="none",bh.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Lo("document.F=Object")),t.close(),t.F},yi,Mi=function(){try{yi=new ActiveXObject("htmlfile")}catch(e){}Mi=typeof document!="undefined"?document.domain&&yi?qa(yi):Th():qa(yi);for(var i=ja.length;i--;)delete Mi[Ss][ja[i]];return Mi()};Sh[Oo]=!0;var xo=Object.create||function(e,t){var r;return e!==null?(Cr[Ss]=mh(e),r=new Cr,Cr[Ss]=null,r[Oo]=e):r=Mi(),t===void 0?r:vh.f(r,t)},Eh=ye,$h=!Eh(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),Ph=je,kh=se,_h=Ms,wh=Fs,Ah=$h,Ya=wh("IE_PROTO"),gs=Object,Rh=gs.prototype,Bo=Ah?gs.getPrototypeOf:function(i){var e=_h(i);if(Ph(e,Ya))return e[Ya];var t=e.constructor;return kh(t)&&e instanceof t?t.prototype:e instanceof gs?Rh:null},Ih=ai,Ys=function(i,e,t,r){return r&&r.enumerable?i[e]=t:Ih(i,e,t),i},Nh=ye,Ch=se,Dh=Ke,Oh=xo,za=Bo,Lh=Ys,xh=pe,ys=xh("iterator"),Mo=!1,Ve,Dr,Or;[].keys&&(Or=[].keys(),"next"in Or?(Dr=za(za(Or)),Dr!==Object.prototype&&(Ve=Dr)):Mo=!0);var Bh=!Dh(Ve)||Nh(function(){var i={};return Ve[ys].call(i)!==i});Bh?Ve={}:Ve=Oh(Ve);Ch(Ve[ys])||Lh(Ve,ys,function(){return this});var Vo={IteratorPrototype:Ve,BUGGY_SAFARI_ITERATORS:Mo},Mh=pe,Vh=Mh("toStringTag"),Fo={};Fo[Vh]="z";var zs=String(Fo)==="[object z]",Fh=zs,Uh=se,Vi=tr,jh=pe,Hh=jh("toStringTag"),Gh=Object,qh=Vi(function(){return arguments}())=="Arguments",Yh=function(i,e){try{return i[e]}catch(t){}},or=Fh?Vi:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=Yh(e=Gh(i),Hh))=="string"?t:qh?Vi(e):(r=Vi(e))=="Object"&&Uh(e.callee)?"Arguments":r},zh=zs,Wh=or,Qh=zh?{}.toString:function(){return"[object "+Wh(this)+"]"},Jh=zs,Kh=dt.f,Xh=ai,Zh=je,ef=Qh,tf=pe,Wa=tf("toStringTag"),Ws=function(i,e,t,r){if(i){var s=t?i:i.prototype;Zh(s,Wa)||Kh(s,Wa,{configurable:!0,value:e}),r&&!Jh&&Xh(s,"toString",ef)}},rf=Vo.IteratorPrototype,sf=xo,af=ar,nf=Ws,of=Ct,lf=function(){return this},uf=function(i,e,t,r){var s=e+" Iterator";return i.prototype=sf(rf,{next:af(+!r,t)}),nf(i,s,!1,!0),of[s]=lf,i},df=De,cf=Pe,Uo=Bc,hf=uf,ff=Bo,pf=Ws,Qa=Ys,mf=pe,Ja=Ct,jo=Vo,vf=Uo.PROPER;Uo.CONFIGURABLE;jo.IteratorPrototype;var Ti=jo.BUGGY_SAFARI_ITERATORS,Lr=mf("iterator"),Ka="keys",Ei="values",Xa="entries",Sf=function(){return this},bf=function(i,e,t,r,s,n,o){hf(t,e,r);var l=function(b){if(b===s&&f)return f;if(!Ti&&b in c)return c[b];switch(b){case Ka:return function(){return new t(this,b)};case Ei:return function(){return new t(this,b)};case Xa:return function(){return new t(this,b)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=i.prototype,h=c[Lr]||c["@@iterator"]||s&&c[s],f=!Ti&&h||l(s),p=e=="Array"&&c.entries||h,v,m,S;if(p&&(v=ff(p.call(new i)),v!==Object.prototype&&v.next&&(pf(v,d,!0,!0),Ja[d]=Sf)),vf&&s==Ei&&h&&h.name!==Ei&&(u=!0,f=function(){return cf(h,this)}),s)if(m={values:l(Ei),keys:n?f:l(Ka),entries:l(Xa)},o)for(S in m)(Ti||u||!(S in c))&&Qa(c,S,m[S]);else df({target:e,proto:!0,forced:Ti||u},m);return o&&c[Lr]!==f&&Qa(c,Lr,f,{name:s}),Ja[e]=f,m},gf=function(i,e){return{value:i,done:e}},yf=si,Qs=Au,Za=Ct,Ho=Eo,Tf=dt.f,Ef=bf,$i=gf,$f=go,Pf=Ue,Go="Array Iterator",kf=Ho.set,_f=Ho.getterFor(Go);Ef(Array,"Array",function(i,e){kf(this,{type:Go,target:yf(i),index:0,kind:e})},function(){var i=_f(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,$i(void 0,!0)):t=="keys"?$i(r,!1):t=="values"?$i(e[r],!1):$i([r,e[r]],!1)},"values");var en=Za.Arguments=Za.Array;Qs();Qs();Qs();if(!$f&&Pf&&en.name!=="values")try{Tf(en,"name",{value:"values"})}catch(i){}var wf=pe,Af=Ct,Rf=wf("iterator"),If=Array.prototype,Nf=function(i){return i!==void 0&&(Af.Array===i||If[Rf]===i)},Cf=or,tn=xs,Df=ir,Of=Ct,Lf=pe,xf=Lf("iterator"),qo=function(i){if(!Df(i))return tn(i,xf)||tn(i,"@@iterator")||Of[Cf(i)]},Bf=Pe,Mf=ht,Vf=Xe,Ff=sr,Uf=qo,jf=TypeError,Hf=function(i,e){var t=arguments.length<2?Uf(i):e;if(Mf(t))return Vf(Bf(t,i));throw jf(Ff(i)+" is not iterable")},Gf=Pe,rn=Xe,qf=xs,Yf=function(i,e,t){var r,s;rn(i);try{if(r=qf(i,"return"),!r){if(e==="throw")throw t;return t}r=Gf(r,i)}catch(n){s=!0,r=n}if(e==="throw")throw t;if(s)throw r;return rn(r),t},zf=nr,Wf=Pe,Qf=Xe,Jf=sr,Kf=Nf,Xf=qs,sn=Ls,Zf=Hf,ep=qo,an=Yf,tp=TypeError,Fi=function(i,e){this.stopped=i,this.result=e},nn=Fi.prototype,Js=function(i,e,t){var r=t&&t.that,s=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),d=zf(e,r),u,c,h,f,p,v,m,S=function(g){return u&&an(u,"normal",g),new Fi(!0,g)},b=function(g){return s?(Qf(g),l?d(g[0],g[1],S):d(g[0],g[1])):l?d(g,S):d(g)};if(n)u=i.iterator;else if(o)u=i;else{if(c=ep(i),!c)throw tp(Jf(i)+" is not iterable");if(Kf(c)){for(h=0,f=Xf(i);f>h;h++)if(p=b(i[h]),p&&sn(nn,p))return p;return new Fi(!1)}u=Zf(i,c)}for(v=n?i.next:u.next;!(m=Wf(v,u)).done;){try{p=b(m.value)}catch(g){an(u,"throw",g)}if(typeof p=="object"&&p&&sn(nn,p))return p}return new Fi(!1)},ip=Vs,rp=dt,sp=ar,ap=function(i,e,t){var r=ip(e);r in i?rp.f(i,r,sp(0,t)):i[r]=t},np=De,op=Js,lp=ap;np({target:"Object",stat:!0},{fromEntries:function(e){var t={};return op(e,function(r,s){lp(t,r,s)},{AS_ENTRIES:!0}),t}});var up=Os,dp=up.Object.fromEntries,cp={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},hp=cp,fp=le,pp=or,mp=ai,on=Ct,vp=pe,ln=vp("toStringTag");for(var xr in hp){var un=fp[xr],Br=un&&un.prototype;Br&&pp(Br)!==ln&&mp(Br,ln,xr),on[xr]=on.Array}var Sp=dp,bp=Sp,gp=bp,yp=gp,oi=yp,Tp=tr,lr=typeof process!="undefined"&&Tp(process)=="process",Ep=ct,$p=dt,Pp=pe,kp=Ue,dn=Pp("species"),_p=function(i){var e=Ep(i),t=$p.f;kp&&e&&!e[dn]&&t(e,dn,{configurable:!0,get:function(){return this}})},wp=Ls,Ap=TypeError,Rp=function(i,e){if(wp(e,i))return i;throw Ap("Incorrect invocation")},Ip=Ce,Np=se,Ts=Bs,Cp=Ip(Function.toString);Np(Ts.inspectSource)||(Ts.inspectSource=function(i){return Cp(i)});var Yo=Ts.inspectSource,Dp=Ce,Op=ye,zo=se,Lp=or,xp=ct,Bp=Yo,Wo=function(){},Mp=[],Qo=xp("Reflect","construct"),Ks=/^\s*(?:class|function)\b/,Vp=Dp(Ks.exec),Fp=!Ks.exec(Wo),Yt=function(e){if(!zo(e))return!1;try{return Qo(Wo,Mp,e),!0}catch(t){return!1}},Jo=function(e){if(!zo(e))return!1;switch(Lp(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Fp||!!Vp(Ks,Bp(e))}catch(t){return!0}};Jo.sham=!0;var Up=!Qo||Op(function(){var i;return Yt(Yt.call)||!Yt(Object)||!Yt(function(){i=!0})||i})?Jo:Yt,jp=Up,Hp=sr,Gp=TypeError,qp=function(i){if(jp(i))return i;throw Gp(Hp(i)+" is not a constructor")},cn=Xe,Yp=qp,zp=ir,Wp=pe,Qp=Wp("species"),Ko=function(i,e){var t=cn(i).constructor,r;return t===void 0||zp(r=cn(t)[Qp])?e:Yp(r)},Jp=Ce,Kp=Jp([].slice),Xp=TypeError,Zp=function(i,e){if(i<e)throw Xp("Not enough arguments");return i},em=rr,Xo=/(?:ipad|iphone|ipod).*applewebkit/i.test(em),fe=le,tm=Po,im=nr,hn=se,rm=je,Zo=ye,fn=Do,sm=Kp,pn=Ds,am=Zp,nm=Xo,om=lr,Es=fe.setImmediate,$s=fe.clearImmediate,lm=fe.process,Mr=fe.Dispatch,um=fe.Function,mn=fe.MessageChannel,dm=fe.String,Vr=0,Kt={},vn="onreadystatechange",ri,nt,Fr,Ur;Zo(function(){ri=fe.location});var Xs=function(i){if(rm(Kt,i)){var e=Kt[i];delete Kt[i],e()}},jr=function(i){return function(){Xs(i)}},Sn=function(i){Xs(i.data)},bn=function(i){fe.postMessage(dm(i),ri.protocol+"//"+ri.host)};(!Es||!$s)&&(Es=function(e){am(arguments.length,1);var t=hn(e)?e:um(e),r=sm(arguments,1);return Kt[++Vr]=function(){tm(t,void 0,r)},nt(Vr),Vr},$s=function(e){delete Kt[e]},om?nt=function(i){lm.nextTick(jr(i))}:Mr&&Mr.now?nt=function(i){Mr.now(jr(i))}:mn&&!nm?(Fr=new mn,Ur=Fr.port2,Fr.port1.onmessage=Sn,nt=im(Ur.postMessage,Ur)):fe.addEventListener&&hn(fe.postMessage)&&!fe.importScripts&&ri&&ri.protocol!=="file:"&&!Zo(bn)?(nt=bn,fe.addEventListener("message",Sn,!1)):vn in pn("script")?nt=function(i){fn.appendChild(pn("script"))[vn]=function(){fn.removeChild(this),Xs(i)}}:nt=function(i){setTimeout(jr(i),0)});var el={set:Es,clear:$s},tl=function(){this.head=null,this.tail=null};tl.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 il=tl,cm=rr,hm=/ipad|iphone|ipod/i.test(cm)&&typeof Pebble!="undefined",fm=rr,pm=/web0s(?!.*chrome)/i.test(fm),ut=le,gn=nr,mm=js.f,Hr=el.set,vm=il,Sm=Xo,bm=hm,gm=pm,Gr=lr,yn=ut.MutationObserver||ut.WebKitMutationObserver,Tn=ut.document,En=ut.process,Pi=ut.Promise,$n=mm(ut,"queueMicrotask"),Ps=$n&&$n.value,yt,qr,Yr,ki,Pn;if(!Ps){var _i=new vm,wi=function(){var i,e;for(Gr&&(i=En.domain)&&i.exit();e=_i.get();)try{e()}catch(t){throw _i.head&&yt(),t}i&&i.enter()};!Sm&&!Gr&&!gm&&yn&&Tn?(qr=!0,Yr=Tn.createTextNode(""),new yn(wi).observe(Yr,{characterData:!0}),yt=function(){Yr.data=qr=!qr}):!bm&&Pi&&Pi.resolve?(ki=Pi.resolve(void 0),ki.constructor=Pi,Pn=gn(ki.then,ki),yt=function(){Pn(wi)}):Gr?yt=function(){En.nextTick(wi)}:(Hr=gn(Hr,ut),yt=function(){Hr(wi)}),Ps=function(i){_i.head||yt(),_i.add(i)}}var ym=Ps,Tm=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},Zs=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},Em=le,Dt=Em.Promise,rl=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",$m=rl,Pm=lr,km=!$m&&!Pm&&typeof window=="object"&&typeof document=="object",_m=le,Xt=Dt,wm=se,Am=Ro,Rm=Yo,Im=pe,Nm=km,Cm=rl,zr=mo,kn=Xt&&Xt.prototype,Dm=Im("species"),ks=!1,sl=wm(_m.PromiseRejectionEvent),Om=Am("Promise",function(){var i=Rm(Xt),e=i!==String(Xt);if(!e&&zr===66||!(kn.catch&&kn.finally))return!0;if(!zr||zr<51||!/native code/.test(i)){var t=new Xt(function(n){n(1)}),r=function(n){n(function(){},function(){})},s=t.constructor={};if(s[Dm]=r,ks=t.then(function(){})instanceof r,!ks)return!0}return!e&&(Nm||Cm)&&!sl}),li={CONSTRUCTOR:Om,REJECTION_EVENT:sl,SUBCLASSING:ks},Ot={},_n=ht,Lm=TypeError,xm=function(i){var e,t;this.promise=new i(function(r,s){if(e!==void 0||t!==void 0)throw Lm("Bad Promise constructor");e=r,t=s}),this.resolve=_n(e),this.reject=_n(t)};Ot.f=function(i){return new xm(i)};var Bm=De,zi=lr,Je=le,ui=Pe,Mm=Ys,Vm=Ws,Fm=_p,Um=ht,_s=se,jm=Ke,Hm=Rp,Gm=Ko,al=el.set,ea=ym,qm=Tm,Ym=Zs,zm=il,nl=Eo,ws=Dt,ta=li,ol=Ot,ur="Promise",ll=ta.CONSTRUCTOR,Wm=ta.REJECTION_EVENT;ta.SUBCLASSING;var Wr=nl.getterFor(ur),Qm=nl.set,Jm=ws&&ws.prototype,Et=ws,Qr=Jm,ul=Je.TypeError,As=Je.document,ia=Je.process,Rs=ol.f,Km=Rs,Xm=!!(As&&As.createEvent&&Je.dispatchEvent),dl="unhandledrejection",Zm="rejectionhandled",wn=0,cl=1,ev=2,ra=1,hl=2,Ai,An,tv,fl=function(i){var e;return jm(i)&&_s(e=i.then)?e:!1},pl=function(i,e){var t=e.value,r=e.state==cl,s=r?i.ok:i.fail,n=i.resolve,o=i.reject,l=i.domain,d,u,c;try{s?(r||(e.rejection===hl&&rv(e),e.rejection=ra),s===!0?d=t:(l&&l.enter(),d=s(t),l&&(l.exit(),c=!0)),d===i.promise?o(ul("Promise-chain cycle")):(u=fl(d))?ui(u,d,n,o):n(d)):o(t)}catch(h){l&&!c&&l.exit(),o(h)}},ml=function(i,e){i.notified||(i.notified=!0,ea(function(){for(var t=i.reactions,r;r=t.get();)pl(r,i);i.notified=!1,e&&!i.rejection&&iv(i)}))},vl=function(i,e,t){var r,s;Xm?(r=As.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),Je.dispatchEvent(r)):r={promise:e,reason:t},!Wm&&(s=Je["on"+i])?s(r):i===dl&&qm("Unhandled promise rejection",t)},iv=function(i){ui(al,Je,function(){var e=i.facade,t=i.value,r=Rn(i),s;if(r&&(s=Ym(function(){zi?ia.emit("unhandledRejection",t,e):vl(dl,e,t)}),i.rejection=zi||Rn(i)?hl:ra,s.error))throw s.value})},Rn=function(i){return i.rejection!==ra&&!i.parent},rv=function(i){ui(al,Je,function(){var e=i.facade;zi?ia.emit("rejectionHandled",e):vl(Zm,e,i.value)})},$t=function(i,e,t){return function(r){i(e,r,t)}},kt=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=ev,ml(i,!0))},Is=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw ul("Promise can't be resolved itself");var r=fl(e);r?ea(function(){var s={done:!1};try{ui(r,e,$t(Is,s,i),$t(kt,s,i))}catch(n){kt(s,n,i)}}):(i.value=e,i.state=cl,ml(i,!1))}catch(s){kt({done:!1},s,i)}}};ll&&(Et=function(e){Hm(this,Qr),Um(e),ui(Ai,this);var t=Wr(this);try{e($t(Is,t),$t(kt,t))}catch(r){kt(t,r)}},Qr=Et.prototype,Ai=function(e){Qm(this,{type:ur,done:!1,notified:!1,parent:!1,reactions:new zm,rejection:!1,state:wn,value:void 0})},Ai.prototype=Mm(Qr,"then",function(e,t){var r=Wr(this),s=Rs(Gm(this,Et));return r.parent=!0,s.ok=_s(e)?e:!0,s.fail=_s(t)&&t,s.domain=zi?ia.domain:void 0,r.state==wn?r.reactions.add(s):ea(function(){pl(s,r)}),s.promise}),An=function(){var i=new Ai,e=Wr(i);this.promise=i,this.resolve=$t(Is,e),this.reject=$t(kt,e)},ol.f=Rs=function(i){return i===Et||i===tv?new An(i):Km(i)});Bm({global:!0,constructor:!0,wrap:!0,forced:ll},{Promise:Et});Vm(Et,ur,!1,!0);Fm(ur);var sv=pe,Sl=sv("iterator"),bl=!1;try{var av=0,In={next:function(){return{done:!!av++}},return:function(){bl=!0}};In[Sl]=function(){return this},Array.from(In,function(){throw 2})}catch(i){}var nv=function(i,e){if(!e&&!bl)return!1;var t=!1;try{var r={};r[Sl]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch(s){}return t},ov=Dt,lv=nv,uv=li.CONSTRUCTOR,gl=uv||!lv(function(i){ov.all(i).then(void 0,function(){})}),dv=De,cv=Pe,hv=ht,fv=Ot,pv=Zs,mv=Js,vv=gl;dv({target:"Promise",stat:!0,forced:vv},{all:function(e){var t=this,r=fv.f(t),s=r.resolve,n=r.reject,o=pv(function(){var l=hv(t.resolve),d=[],u=0,c=1;mv(e,function(h){var f=u++,p=!1;c++,cv(l,t,h).then(function(v){p||(p=!0,d[f]=v,--c||s(d))},n)}),--c||s(d)});return o.error&&n(o.value),r.promise}});var Sv=De,bv=li.CONSTRUCTOR,Nn=Dt;Nn&&Nn.prototype;Sv({target:"Promise",proto:!0,forced:bv,real:!0},{catch:function(i){return this.then(void 0,i)}});var gv=De,yv=Pe,Tv=ht,Ev=Ot,$v=Zs,Pv=Js,kv=gl;gv({target:"Promise",stat:!0,forced:kv},{race:function(e){var t=this,r=Ev.f(t),s=r.reject,n=$v(function(){var o=Tv(t.resolve);Pv(e,function(l){yv(o,t,l).then(r.resolve,s)})});return n.error&&s(n.value),r.promise}});var _v=De,wv=Pe,Av=Ot,Rv=li.CONSTRUCTOR;_v({target:"Promise",stat:!0,forced:Rv},{reject:function(e){var t=Av.f(this);return wv(t.reject,void 0,e),t.promise}});var Iv=Xe,Nv=Ke,Cv=Ot,yl=function(i,e){if(Iv(i),Nv(e)&&e.constructor===i)return e;var t=Cv.f(i),r=t.resolve;return r(e),t.promise},Dv=De,Ov=ct,Lv=go,xv=Dt,Bv=li.CONSTRUCTOR,Mv=yl,Vv=Ov("Promise"),Fv=!Bv;Dv({target:"Promise",stat:!0,forced:Lv},{resolve:function(e){return Mv(Fv&&this===Vv?xv:this,e)}});var Uv=De,Ns=Dt,jv=ye,Hv=ct,Gv=se,qv=Ko,Cn=yl,Yv=Ns&&Ns.prototype,zv=!!Ns&&jv(function(){Yv.finally.call({then:function(){}},function(){})});Uv({target:"Promise",proto:!0,real:!0,forced:zv},{finally:function(i){var e=qv(this,Hv("Promise")),t=Gv(i);return this.then(t?function(r){return Cn(e,i()).then(function(){return r})}:i,t?function(r){return Cn(e,i()).then(function(){throw r})}:i)}});var Wv=ct,Tl=Wv,Qv=Tl,Jv=Qv("Promise","finally"),Kv=Jv,Xv=Kv,Zv=Xv,eS=Zv,dr=eS,_t;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(_t||(_t={}));var At=(i,e=0,t=_t.OFFSET_P)=>{switch(t){case _t.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case _t.PLAYBACK_SHIFT:{if(e===0)return i;const r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}default:a.assertNever(t)}return i},P=(i,e,t=!1)=>{const r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};exports.VideoQuality=void 0;(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"})(exports.VideoQuality||(exports.VideoQuality={}));const $e={[exports.VideoQuality.Q_144P]:{width:256,height:144},[exports.VideoQuality.Q_240P]:{width:428,height:240},[exports.VideoQuality.Q_360P]:{width:640,height:360},[exports.VideoQuality.Q_480P]:{width:856,height:480},[exports.VideoQuality.Q_720P]:{width:1280,height:720},[exports.VideoQuality.Q_1080P]:{width:1920,height:1080},[exports.VideoQuality.Q_1440P]:{width:2560,height:1440},[exports.VideoQuality.Q_2160P]:{width:3840,height:2160},[exports.VideoQuality.Q_4320P]:{width:7680,height:4320}},Ui=(i,e)=>$e[i].height>$e[e].height,tS=(i,e)=>$e[i].height>=$e[e].height,Zt=(i,e)=>$e[i].height<$e[e].height,iS=(i,e)=>$e[i].height<=$e[e].height,rS=i=>i.sort((e,t)=>e===t?0:e===exports.VideoQuality.INVARIANT?1:t===exports.VideoQuality.INVARIANT?-1:Zt(e,t)?1:-1)[0],sS=Object.keys($e).sort((i,e)=>Zt(i,e)?-1:1),ft=({width:i,height:e})=>{const t=Math.min(i,e),r=Math.max(i,e);return sS.find(s=>{const n=$e[s];return n.width>=r&&n.height>=t})},aS=i=>$e[i].height,Wi=i=>i===exports.VideoQuality.INVARIANT;class K{constructor(e){this.transitionStarted$=new a.Subject,this.transitionEnded$=new a.Subject,this.transitionUpdated$=new a.Subject,this.forceChanged$=new a.Subject,this.stateChangeStarted$=a.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=a.merge(this.transitionEnded$,this.forceChanged$),this.state=e}setState(e){const t=this.transition,r=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:r,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,r=this.state;r===e||a.isNonNullable(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:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}const nS=i=>{switch(i){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return a.assertNever(i)}};var U;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(U||(U={}));const oS=5,lS=5,uS=500,Dn=7e3;class dS{constructor(e){this.subscription=new a.Subscription,this.loadMediaTimeoutSubscription=new a.Subscription,this.videoState=new K(U.STOPPED),this.syncPlayback=()=>{const r=this.videoState.getState(),s=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${r}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){r!==U.STOPPED&&(this.videoState.startTransitionTo(U.STOPPED),this.stop());return}if(!s){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===D.Requested&&r!==U.STOPPED){this.seek(l.position);return}switch(n){case exports.PlaybackState.PLAYING:{switch(r){case U.PLAYING:break;case U.PAUSED:this.videoState.startTransitionTo(U.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case U.READY:this.videoState.startTransitionTo(U.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case U.STOPPED:this.videoState.startTransitionTo(U.READY),this.prepare();break;default:a.assertNever(r)}break}case exports.PlaybackState.PAUSED:{switch(r){case U.PLAYING:this.videoState.startTransitionTo(U.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case U.PAUSED:break;case U.READY:this.videoState.startTransitionTo(U.PAUSED),this.videoState.setState(U.PAUSED);break;case U.STOPPED:this.videoState.startTransitionTo(U.READY),this.prepare();break;default:a.assertNever(r)}break}default:a.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(nS(e.format)),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 a.Subscription;this.subscription.add(e),this.subscription.add(a.merge(this.videoState.stateChangeStarted$.pipe(a.map(s=>`stateChangeStarted$ ${JSON.stringify(s)}`)),this.videoState.stateChangeEnded$.pipe(a.map(s=>`stateChangeEnded$ ${JSON.stringify(s)}`))).subscribe(s=>this.log({message:`[videoState] ${s}`})));const t=(s,n)=>this.subscription.add(s.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const s=new a.Subject;e.add(s.pipe(a.debounce(uS)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(o=>{this.logRemoteEvent(o);const l=o.value;this.params.output.position$.next(l),(this.params.desiredState.seekState.getState().state===D.Applying||Math.abs(l-n)>oS)&&s.next(l),n=l})),e.add(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemotePause():this.handleRemotePlay()}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),s=>{this.logRemoteEvent(s);const{remotePlayer:n}=this.params.connection,o=s.value,l=this.params.output.isBuffering$.getValue(),d=o===chrome.cast.media.PlayerState.BUFFERING;switch(l!==d&&this.params.output.isBuffering$.next(d),o){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&n.duration-n.currentTime<lS&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(this.params.desiredState.playbackState,exports.PlaybackState.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:a.assertNever(o)}}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({volume:s.value})}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({muted:s.value})});const r=a.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));t(r,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(U.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(U.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:D.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===U.PAUSED||e===U.PLAYING)&&(this.videoState.setState(U.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===U.PLAYING||e===U.PAUSED)&&(this.videoState.setState(U.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){const e=this.videoState.getTransition();(e==null?void 0:e.to)===U.READY&&this.videoState.setState(U.READY)}handleRemoteStop(){this.videoState.getState()!==U.STOPPED&&this.videoState.setState(U.STOPPED)}handleRemoteVolumeChange(e){var t,r;const s=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:s.volume,muted:(r=e.muted)!==null&&r!==void 0?r:s.muted};(n.volume!==s.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const r=this.params.source;let s,n,o;switch(e){case exports.VideoFormat.MPEG:{const c=r[e];a.assertNonNullable(c);const h=rS(Object.keys(c));a.assertNonNullable(h);const f=c[h];a.assertNonNullable(f),s=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=r[e];a.assertNonNullable(c),s=c.url,n="application/x-mpegurl",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:{const c=r[e];a.assertNonNullable(c),s=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS_LIVE:{const c=r[e];a.assertNonNullable(c),s=At(c.url),n="application/x-mpegurl",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const c="Unsupported format for Chromecast",h=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:a.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:h}),h}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}const l=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:s,n);l.contentUrl=s,l.streamType=o,l.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:d,subtitle:u}=this.params.meta;return a.isNonNullable(d)&&(l.metadata.title=d),a.isNonNullable(u)&&(l.metadata.subtitle=u),l}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const r=this.params.desiredState.seekState.getState();return r.state===D.Applying||r.state===D.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),r=new Promise((s,n)=>{this.loadMediaTimeoutSubscription.add(a.timeout(Dn).subscribe(()=>n(`timeout(${Dn})`)))});dr(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===D.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},s=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${s}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:a.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:s})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}function X(i,e,t,r){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function l(c){try{u(r.next(c))}catch(h){o(h)}}function d(c){try{u(r.throw(c))}catch(h){o(h)}}function u(c){c.done?n(c.value):s(c.value).then(l,d)}u((r=r.apply(i,e||[])).next())})}function I(i){return this instanceof I?(this.v=i,this):new I(i)}function Ee(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(i,e||[]),s,n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(f){r[f]&&(s[f]=function(p){return new Promise(function(v,m){n.push([f,p,v,m])>1||l(f,p)})})}function l(f,p){try{d(r[f](p))}catch(v){h(n[0][3],v)}}function d(f){f.value instanceof I?Promise.resolve(f.value.v).then(u,c):h(n[0][2],f)}function u(f){l("next",f)}function c(f){l("throw",f)}function h(f,p){f(p),n.shift(),n.length&&l(n[0][0],n[0][1])}}class On{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;const r=this.listeners[e];for(let s=0,n=r.length;s<n;s++)if(r[s].callback===t){r.splice(s,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const r=this.listeners[e.type].slice();for(let s=0,n=r.length;s<n;s++){const o=r[s];try{o.callback.call(this,e)}catch(l){Promise.resolve().then(()=>{throw l})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class El extends On{constructor(){super(),this.listeners||On.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 $l=class{constructor(){Object.defineProperty(this,"signal",{value:new El,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(s){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 r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(s){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&($l.prototype[Symbol.toStringTag]="AbortController",El.prototype[Symbol.toStringTag]="AbortSignal");function Pl(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 cS(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=i;if(!Pl({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||s)&&(n=function(u,c){let h;c&&c.signal&&(h=c.signal,delete c.signal);const f=new t(u,c);return h&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),f},n.prototype=t.prototype);const o=e;return{fetch:(d,u)=>{const c=n&&n.prototype.isPrototypeOf(d)?d.signal:u?u.signal:void 0;if(c){let h;try{h=new DOMException("Aborted","AbortError")}catch(p){h=new Error("Aborted"),h.name="AbortError"}if(c.aborted)return Promise.reject(h);const f=new Promise((p,v)=>{c.addEventListener("abort",()=>v(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,o(d,u)])}return o(d,u)},Request:n}}const cr=Pl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),kl=cr?cS({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Rt=cr?kl.fetch:window.fetch;cr?kl.Request:window.Request;const ot=cr?$l:window.AbortController,zt=i=>i.range?i.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class ei{constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){var t;const{url:r}=e.request,s=(t=this.dashJsRequestQueue.get(r))!==null&&t!==void 0?t:[];s.push(e),this.dashJsRequestQueue.set(r,s)}executeNextRequests(){return X(this,void 0,void 0,function*(){for(const[e,t]of this.dashJsRequestQueue.entries()){const r=this.activeRequests.get(e);if(r){t.length&&this.onBigRequestProgress(r);const s=t[0];if(!s||!s.request.range)continue;const[n,o]=zt(s.request);if(n>=r.from&&o<=r.to)continue;this.activeRequests.delete(e)}if(t.length){const s=this.sendBigRequest(e,t.map(({request:n})=>n));this.activeRequests.set(e,s)}}})}abort(e){var t;if(e){const{request:r}=e,s=((t=this.dashJsRequestQueue.get(r.url))!==null&&t!==void 0?t:[]).includes(e),n=this.activeRequests.get(r.url);s&&n&&n.abortController.abort()}else for(const{abortController:r}of this.activeRequests.values())r.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const r=t.map(zt),s=r[0][0];let n=r[0][1];for(let f=1;f<r.length&&n<this.params.minDataSize;f++){const p=r[f][1];p-s<=2*this.params.minDataSize&&(n=Math.max(n,p))}s===0?n=Math.max(n,s+this.params.minInitSize):n=Math.max(n,s+this.params.minDataSize);const o=new URL(e,location.href);o.searchParams.append("bytes",`${s}-${n}`);const l=o.toString(),d=new ot,u=d.signal,c={url:e,from:s,to:n,loaded:0,data:null,abortController:d};u.addEventListener("abort",()=>this.onBigRequestAbort(c));const h=f=>{var p,v;throw(v=(p=this.params).onError)===null||v===void 0||v.call(p,{id:"BigRequestParsing",category:a.ErrorCategory.PARSER,message:"Error parsing response data",thrown:f}),f};return Rt(l,{signal:u}).then(f=>{var p,v,m;if(c.response=f,!f.ok||!f.body){this.onBigRequestError(c);return}const[S,b]=f.body.tee();(v=(p=this.params).onDownloadStream)===null||v===void 0||v.call(p,b);const g=S.getReader(),k=parseInt((m=f.headers.get("Content-Length"))!==null&&m!==void 0?m:"",10)||n-s+1;c.data=new ArrayBuffer(k);const T=new Uint8Array(c.data),E=({done:w,value:x})=>X(this,void 0,void 0,function*(){w?this.onBigRequestProgress(c):x&&(T.set(x,c.loaded),c.loaded+=x.byteLength,this.onBigRequestProgress(c),yield g==null?void 0:g.read().then(E,ei.suppressStreamErrors).catch(h))});g==null||g.read().then(E,ei.suppressStreamErrors).catch(h)},ei.suppressAbort).catch(f=>this.onBigRequestError(c,f)),c}onBigRequestProgress({url:e,from:t,to:r,loaded:s,data:n,response:o}){var l,d,u,c,h,f,p,v;if(!this.activeRequests.has(e)||!n)return;const m=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const S of m){const{request:b}=S,[g,k]=zt(b),T=g>=t&&k<=t+s,E=t>=g&&t+s<k,w=n.slice(g-t,Math.min(k-t+1,s));if((T||E)&&(b.requestStartDate=(d=b.requestStartDate)!==null&&d!==void 0?d:new Date,b.firstByteDate=(u=b.firstByteDate)!==null&&u!==void 0?u:new Date,b.bytesLoaded=w.byteLength,b.bytesTotal=r-t),T){b.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((c=this.dashJsRequestQueue.get(e))!==null&&c!==void 0?c:[]).filter(C=>C!==S)),(h=S.success)===null||h===void 0||h.call(S,w,"",e);const x=o?Array.from(o.headers.entries()).map(([C,R])=>`${C}: ${R}`).join(`\r
|
|
7
|
-
`):"";(f=this.dashMetrics)===null||f===void 0||f.addHttpRequest(b,e,(p=o==null?void 0:o.status)!==null&&p!==void 0?p:200,x,[])}else E&&((v=S.progress)===null||v===void 0||v.call(S,{loaded:s,total:r-t,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:t,to:r},s){var n,o,l,d;if((o=(n=this.params).onError)===null||o===void 0||o.call(n,{id:"BigRequest",category:a.ErrorCategory.NETWORK,message:"Download error",thrown:s}),!this.activeRequests.has(e))return;const u=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const c of u){const[h,f]=zt(c.request);(h>=t&&h<r||f>t&&f<=r)&&((d=c==null?void 0:c.error)===null||d===void 0||d.call(c,c.request,String(s)))}if(this.activeRequests.delete(e),s)throw s}onBigRequestAbort({url:e,from:t,to:r}){var s,n;if(!this.activeRequests.has(e))return;const o=(s=this.dashJsRequestQueue.get(e))!==null&&s!==void 0?s:[];for(const l of o){const[d,u]=zt(l.request);(d>=t&&d<r||u>t&&u<=r)&&((n=l==null?void 0:l.abort)===null||n===void 0||n.call(l,l.request))}this.activeRequests.delete(e)}static suppressAbort(e){if(!(e instanceof DOMException)||!(e.name==="AbortError"||e.code===20))throw e}static suppressStreamErrors(){}}class Qi{constructor(e,t,r){this.baseLoader=e,this.config=r,this.bigRequest=t,t.setMetrics(r.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(Qi.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;Qi.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const hS=(i,e)=>t=>({create:r=>{const s=i(t).create(r);return new Qi(s,e,r)}}),fS=(i,e)=>{const t=new ei(e);return i.extend("SchemeLoaderFactory",function(){const{parent:r}=this,s=r.getLoader;return{getLoader:n=>{const o=s(n);return hS(o,t)}}},!0),()=>t.destroy()};var pS=i=>{let e,t=!1,r=!1;i.on("playbackTimeUpdated",({timeToEnd:s})=>{r=s<=3,t&&r&&(e==null||e())}),i.extend("MediaSourceController",function(){const{parent:s}=this,n=s.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&r&&(e==null||e())}}},!0)},mS=i=>{const e=new a.ValueSubject(1/0),t=new a.Subject,r=new a.ValueSubject(void 0),s=new a.ValueSubject(void 0);let n=NaN,o=!1;const l=()=>{n=Date.now(),o=!1},d=c=>{var h,f,p,v,m;const S=oi(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(k=>k.split(": ")));if("x-playback-duration"in S||"x-playback-duration-millis"in S){const k=parseInt((h=c.getResponseHeader("X-Playback-Duration"))!==null&&h!==void 0?h:"",10),T=parseInt((f=c.getResponseHeader("X-Playback-Duration-Millis"))!==null&&f!==void 0?f:"",10),E=(p=T!=null?T:k*1e3)!==null&&p!==void 0?p:NaN;a.isNonNullable(E)&&!isNaN(E)&&e.next(E)}const b=(v=S["x-delivery-type"])!==null&&v!==void 0?v:exports.HttpConnectionType.HTTP1,g=(m={1:!0,0:!1}[S["x-reused"]])!==null&&m!==void 0?m:void 0;r.next(b),s.next(g)},u=c=>{c.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return i.extend("XHRLoader",function(){const{parent:c}=this,h=c.load.bind(c);return{load:function(f){if(f.request.type==="MPD"){const p=f.onload,v=f.progress;f.onload=function(...m){return d(this),p(...m)},f.progress=function(...m){return u(this),v(...m)},l()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:s,connectionType$:r}},It=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},vS=i=>i.extend("RequestModifier",()=>({modifyRequestURL:It}),!0),SS=i=>{i.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:r=>{if(r.request&&r.request.range){const[s,n]=r.request.range.split("-").map(l=>parseInt(l,10)),o=new URL(r.request.url,location.href);o.searchParams.append("bytes",`${s}-${n}`),r.request.url=o.toString(),r.request.range=void 0}t(r)}}},!0)};const Ne=(i,e,t,{equal:r=(o,l)=>o===l,changed$:s,onError:n}={})=>{const o=i.getState(),l=e(),d=a.isNullable(s),u=new a.Subscription;return s&&u.add(s.subscribe(c=>{const h=i.getState();r(c,h)&&i.setState(c)},n)),r(l,o)||(t(o),d&&i.setState(o)),u.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),d&&i.setState(c.to)},n)),u},pt=(i,e,t)=>Ne(e,()=>i.loop,r=>{a.isNonNullable(r)&&(i.loop=r)},{onError:t}),He=(i,e,t,r)=>Ne(e,()=>({muted:i.muted,volume:i.volume}),s=>{a.isNonNullable(s)&&(i.muted=s.muted,i.volume=s.volume)},{equal:(s,n)=>s===n||(s==null?void 0:s.muted)===(n==null?void 0:n.muted)&&(s==null?void 0:s.volume)===(n==null?void 0:n.volume),changed$:t,onError:r}),Ze=(i,e,t,r)=>Ne(e,()=>i.playbackRate,s=>{a.isNonNullable(s)&&(i.playbackRate=s)},{changed$:t,onError:r}),bS=i=>["__",i.language,i.label].join("|"),gS=(i,e)=>{if(i.id===e)return!0;const[t,r,s]=e.split("|");return i.language===r&&i.label===s};class Oe{constructor(){this.available$=new a.Subject,this.current$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.subscription=new a.Subscription,this.externalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const s=n=>{this.error$.next({id:"TextTracksManager",category:a.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Ne(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{a.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>a.isNonNullable(n)&&a.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},d)=>l===o[d].id),changed$:this.available$.pipe(a.map(n=>n.filter(({type:o})=>o==="external"))),onError:s})),this.subscription.add(Ne(t.currentTextTrack,()=>{if(this.video)return;const n=this.htmlTextTracksAsArray().find(({mode:o})=>o==="showing");return n&&this.htmlTextTrackToITextTrack(n).id},n=>this.select(n),{changed$:this.current$,onError:s})),this.subscription.add(Ne(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){a.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(a.fromEvent(e,"addtrack").subscribe(()=>{const r=this.current$.getValue();this.select(r)})),this.subscription.add(a.merge(a.fromEvent(e,"addtrack"),a.fromEvent(e,"removetrack"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),a.filterChanged((r,s)=>r.length===s.length&&r.every(({id:n},o)=>n===s[o].id))).subscribe(this.available$)),this.subscription.add(a.merge(a.fromEvent(e,"change"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),a.map(r=>r&&this.htmlTextTrackToITextTrack(r).id),a.filterChanged()).subscribe(this.current$));const t=r=>{var s,n;return this.applyCueSettings((n=(s=r.target)===null||s===void 0?void 0:s.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(a.fromEvent(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)===null||s===void 0||s.addEventListener("cuechange",t);const o=l=>{var d,u,c,h,f;const p=(u=(d=l.target)===null||d===void 0?void 0:d.cues)!==null&&u!==void 0?u:null;p&&p.length&&(this.applyCueSettings((h=(c=l.target)===null||c===void 0?void 0:c.cues)!==null&&h!==void 0?h:null),(f=l.target)===null||f===void 0||f.removeEventListener("cuechange",o))};(n=r.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(a.fromEvent(e,"removetrack").subscribe(r=>{var s;(s=r.track)===null||s===void 0||s.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const r of Array.from(e)){const s=r;a.isNonNullable(t.align)&&(s.align=t.align),a.isNonNullable(t.position)&&(s.position=t.position),a.isNonNullable(t.size)&&(s.size=t.size),a.isNonNullable(t.line)&&(s.line=t.line)}}htmlTextTracksAsArray(e=!1){a.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Oe.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:r}=e,s=e.id!==""?e.id:bS(e);return this.externalTracks.has(s)?{id:s,type:"external",language:t,label:r,url:this.externalTracks.get(s).url}:{id:s,type:"internal",language:t,label:r}}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(r=>r.id===t)).forEach(t=>this.detach(t))}select(e){a.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))a.isNonNullable(e)&&gS(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){a.assertNonNullable(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){a.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e);t&&this.video.removeChild(t),this.externalTracks.delete(e)}}var Ge=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 sa{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 _l=()=>{const{userAgent:i}=window.navigator;return!/chrome/i.test(i)&&/webkit|safari|khtml/i.test(i)};const Cs=3;class yS{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,r=this._source.buffered.length;t<r;t++){let s=this._source.buffered.start(t);const n=this._source.buffered.end(t);s>e&&s-e<Cs&&(s=e),this._buffer.push({from:s,to:n,i:t})}return this._buffer.sort(function(t,r){return t.from-r.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const r=this.getNext(e);if(r&&r.from-e.to<(t||Cs))return r}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,r){this._buffer.forEach(({from:s,to:n})=>{const o=s>=e&&s<t,l=n>=e&&n<t;o&&l||(o?r(t,n):l?r(s,e):s<e&&n>t?(r(t,n),r(s,e)):r(s,n))})}destroy(){this._buffer=[]}}var wl=(i,e,t=Cs)=>{let r=0,s=0;for(let n=0;n<i.length;n++){const o=i.start(n),l=i.end(n);if(o<=e&&e<=l){if(r=o,s=l,!t)return{from:r,to:s};for(let d=n-1;d>=0;d--)i.end(d)+t>=r&&(r=i.start(d));for(let d=n+1;d<i.length;d++)i.start(d)-t<=s&&(s=i.end(d))}}return{from:r,to:s}};const qe=i=>{const e=p=>a.fromEvent(i,p).pipe(a.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],r=a.merge(...t.map(p=>a.fromEvent(i,p))).pipe(a.map(p=>p.type==="ended"?i.readyState<2:i.readyState<3),a.filterChanged()),s=a.merge(a.fromEvent(i,"progress"),a.fromEvent(i,"timeupdate")).pipe(a.map(()=>wl(i.buffered,i.currentTime))),n=_l()?a.combine({play:e("play").pipe(a.once()),playing:e("playing")}).pipe(a.mapTo(void 0)):e("playing"),o=a.fromEvent(i,"volumechange").pipe(a.map(()=>({muted:i.muted,volume:i.volume}))),l=a.fromEvent(i,"ratechange").pipe(a.map(()=>i.playbackRate)),d=a.fromEvent(i,"error").pipe(a.filter(()=>Boolean(i.error||i.played.length)),a.map(()=>{var p;const v=i.error;return{id:v?`MediaError#${v.code}`:"HtmlVideoError",category:a.ErrorCategory.VIDEO_PIPELINE,message:v?v.message:"Error event from HTML video element",thrown:(p=i.error)!==null&&p!==void 0?p:void 0}})),u=a.fromEvent(i,"timeupdate").pipe(a.map(()=>i.currentTime)),c=new a.Subject,h=.3;let f;return u.subscribe(p=>{i.loop&&a.isNonNullable(f)&&a.isNonNullable(p)&&f>=i.duration-h&&p<=h&&c.next(f),f=p}),{playing$:n,pause$:e("pause").pipe(a.filter(()=>!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$:u,durationChange$:a.fromEvent(i,"durationchange").pipe(a.map(()=>i.duration)),isBuffering$:r,currentBuffer$:s,volumeState$:o,playbackRateState$:l}},aa=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var TS=De,ES=Ms,$S=qs,PS=Gs;TS({target:"Array",proto:!0},{at:function(e){var t=ES(this),r=$S(t),s=PS(e),n=s>=0?s:r+s;return n<0||n>=r?void 0:t[n]}});var kS=Tl,_S=kS("Array","at"),wS=_S,AS=wS,RS=AS,IS=RS,xe=IS;let na=!1,Be={};const NS=i=>{na=i},CS=()=>{Be={}},DS=i=>{i(Be)},Ri=(i,e)=>{var t;na&&(Be.meta=(t=Be.meta)!==null&&t!==void 0?t:{},Be.meta[i]=e)};class Ie{constructor(e){this.name=e}next(e){var t,r;if(!na)return;Be.series=(t=Be.series)!==null&&t!==void 0?t:{};const s=(r=Be.series[this.name])!==null&&r!==void 0?r:[];s.push([Date.now(),e]),Be.series[this.name]=s}}const OS=new Ie("best_bitrate"),LS=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class xS{constructor(){this.history={}}recordSelection(e){this.history[e.id]=a.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const di=(i,{container:e,throughput:t,tuning:r,limits:s,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:d,history:u})=>{var c,h,f,p;const v=r.usePixelRatio&&(c=window.devicePixelRatio)!==null&&c!==void 0?c:1,m=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*v*r.containerSizeFactor,height:e.height*v*r.containerSizeFactor},S=m&&ft(m),b=r.considerPlaybackRate&&a.isNonNullable(l)?l:1,g=i.filter(N=>!Wi(N.quality)).sort((N,A)=>Ui(N.quality,A.quality)?-1:1),k=(h=xe(g,-1))===null||h===void 0?void 0:h.quality,T=(f=xe(g,0))===null||f===void 0?void 0:f.quality,E=a.isNullable(s)||a.isNonNullable(s.min)&&a.isNonNullable(s.max)&&Zt(s.max,s.min)||a.isNonNullable(s.min)&&T&&Ui(s.min,T)||a.isNonNullable(s.max)&&k&&Zt(s.max,k),w=b*LS(o!=null?o:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),C=g.filter(N=>{const A=S?Zt(N.quality,S):!0,B=a.isNonNullable(t)&&isFinite(t)&&a.isNonNullable(N.bitrate)?t-n>=N.bitrate*w:!0,F=r.lazyQualitySwitch&&a.isNonNullable(r.minBufferToSwitchUp)&&d&&!Wi(d.quality)&&(o!=null?o:0)<r.minBufferToSwitchUp&&Ui(N.quality,d.quality),Y=E||(a.isNullable(s.max)||iS(N.quality,s.max))&&(a.isNullable(s.min)||tS(N.quality,s.min));return A&&B&&!F&&Y})[0];C&&C.bitrate&&OS.next(C.bitrate);const R=(p=C!=null?C:g[Math.ceil((g.length-1)/2)])!==null&&p!==void 0?p:i[0],V=R&&u&&u.history[R.id]&&a.now()-u.history[R.id]<=r.trackCooldown&&(!u.last||R.id!==u.last.id);if(R!=null&&R.id&&u&&!V&&u.recordSelection(R),V&&(u!=null&&u.last)){const N=u.last;return u==null||u.recordSwitch(N),N}return u==null||u.recordSwitch(R),R};var de=i=>new URL(i).hostname;const BS=300,Ji=(i,e=BS)=>new a.Observable(t=>{const{width:r,height:s}=i.getBoundingClientRect();if(t.next({width:r,height:s}),!window.ResizeObserver)return;const n=new ResizeObserver(uu(o=>{const l=o[0];if(!l)return;let d,u;l.contentBoxSize&&l.contentBoxSize[0]?(u=l.contentBoxSize[0].blockSize,d=l.contentBoxSize[0].inlineSize):l.contentRect&&(d=l.contentRect.width,u=l.contentRect.height),a.isNonNullable(d)&&a.isNonNullable(u)&&t.next({width:d,height:u})},e));return n.observe(i),()=>n.disconnect()}),MS=5e3,Wt={};var j;(function(i){i.DOWNLOADING_LIB="downloading_lib",i.STOPPED="stopped",i.STREAM_INITIALIZED="stream_initialized",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(j||(j={}));const re=(i,e)=>new a.Observable(t=>{const r=s=>t.next(s);return i.on(e,r),()=>i.off(e,r)});class VS{constructor(e){this.subscription=new a.Subscription,this.videoState=new K(j.DOWNLOADING_LIB),this.textTracksManager=new Oe,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new a.ValueSubject(void 0),this.maxSeekBackTime$=new a.ValueSubject(1/0),this.availableFrom$=new a.ValueSubject(void 0),this.elementSize$=new a.ValueSubject(void 0),this.liveOffset=new sa,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState(),o=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===j.DOWNLOADING_LIB||t===j.STREAM_INITIALIZED))switch((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===D.Requested&&t!==j.STOPPED&&r!==exports.PlaybackState.STOPPED&&(o?this.seek(n.position-this.liveOffset.getTotalPausedTime()):this.seek(n.position)),r){case exports.PlaybackState.STOPPED:{switch(t){case j.STOPPED:break;case j.PLAYING:case j.PAUSED:case j.READY:this.stop();break;default:a.assertNever(t)}break}case exports.PlaybackState.PLAYING:{switch(t){case j.PLAYING:break;case j.PAUSED:o&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case j.READY:this.play();break;case j.STOPPED:this.prepare();break;default:a.assertNever(t)}break}case exports.PlaybackState.PAUSED:{switch(t){case j.PLAYING:this.pause(),this.liveOffset.pause();break;case j.PAUSED:break;case j.READY:this.videoState.setState(j.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case j.STOPPED:this.prepare();break;default:a.assertNever(t)}break}default:a.assertNever(r)}},this.video=Ge(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=s=>{var n;e||this.params.output.error$.next({id:s==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:a.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${(n=s==null?void 0:s.toString)===null||n===void 0?void 0:n.call(s)}`,thrown:s}),e=!0},r=window.setTimeout(()=>t("timeout"),MS);dr(import("dashjs/dist/dash.mediaplayer.min.js").then(s=>{e||(Wt.MediaPlayer=s.MediaPlayer,Wt.Debug=s.Debug,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){a.assertNonNullable(Wt.MediaPlayer,"dashjs not loaded"),a.assertNonNullable(Wt.Debug,"dashjs not loaded"),this.player=Wt.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?aa(t.frameRate+""):void 0),!0)),(this.params.format===exports.VideoFormat.DASH_WEBM||this.params.format===exports.VideoFormat.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=fS(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&&SS(this.player),pS(this.player),this.params.tuning.requestQuick&&vS(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(j.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,r=m=>{e.error$.next({id:"DashIFProvider",category:a.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:m})},s=(m,S)=>this.subscription.add(m.subscribe(S,r));s(Ji(this.video),this.elementSize$),s(re(this.player,"error").pipe(a.map(m=>{const S=typeof m.error=="object"?m.error.code:m.error,b=typeof m.error=="object"?m.error.message:void 0;return{id:`DashJS#${S}`,message:b}})),e.error$),s(re(this.player,"playbackError").pipe(a.map(m=>({id:"DashJSPlayback",message:m.error}))),e.error$);const n=re(this.player,"qualityChangeRendered").pipe(a.filter(({mediaType:m})=>m==="video"),a.map(({newQuality:m})=>{var S;return(S=this.videoTracks.find(({bitrateInfo:b})=>b.qualityIndex===m))===null||S===void 0?void 0:S.track}));n.pipe(a.filter(a.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(a.filter(({to:m})=>m===j.STREAM_INITIALIZED),a.once()).subscribe(()=>{this.subscription.add(Ne(t.videoTrack,()=>{var m,S;const b=this.player.getQualityFor("video");return(S=(m=this.videoTracks.find(({bitrateInfo:g})=>g.qualityIndex===b))===null||m===void 0?void 0:m.track)===null||S===void 0?void 0:S.id},m=>{var S;if(a.isNullable(m))return;const b=(S=this.videoTracks.find(({track:g})=>g.id===m))===null||S===void 0?void 0:S.bitrateInfo;b&&this.player.setQualityFor("video",b.qualityIndex)},{changed$:n.pipe(a.map(m=>m==null?void 0:m.id)),onError:r}))},r)),this.subscription.add(Ne(t.autoVideoTrackSwitching,()=>{var m,S,b;return(b=(S=(m=this.player.getSettings().streaming)===null||m===void 0?void 0:m.abr)===null||S===void 0?void 0:S.autoSwitchBitrate)===null||b===void 0?void 0:b.video},m=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:m}}}}),{onError:r})),s(re(this.player,"bufferStateChanged").pipe(a.filter(({mediaType:m})=>m==="video"),a.map(({state:m})=>m==="bufferStalled")),e.isBuffering$),s(re(this.player,"fragmentLoadingStarted"),({mediaType:m,request:{url:S}})=>{var b,g;const k=this.player.getDashMetrics(),T=k.getLatestFragmentRequestHeaderValueByID(m,"X-Reused"),E=(b=k.getLatestFragmentRequestHeaderValueByID(m,"X-Delivery-Type"))!==null&&b!==void 0?b:exports.HttpConnectionType.HTTP1,w=(g={1:!0,0:!1}[T])!==null&&g!==void 0?g:void 0;this.params.output.httpConnectionType$.next(E),this.params.output.httpConnectionReused$.next(w),e.hostname$.next(de(S))}),s(re(this.player,"streamInitialized"),({streamInfo:{duration:m,manifestInfo:{isDynamic:S,availableFrom:b}}})=>{this.isLive$.next(S),this.availableFrom$.next(b.getTime()),S||e.duration$.next(m),this.videoTracks=[];const g=this.player.getQualityFor("video");let k;for(const T of this.player.getBitrateInfoListFor("video")){const E=T.qualityIndex.toString(10),w=ft(T),x=T.bitrate/1e3,C={width:T.width,height:T.height},R=this.frameRatesByFrameHeight[T.height];if(w){const V={id:E,quality:w,bitrate:x,size:C,fps:R};this.videoTracks.push({track:V,bitrateInfo:T}),T.qualityIndex===g&&(k=V)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:T})=>T)),k&&e.currentVideoTrack$.next(k),this.videoState.setState(j.STREAM_INITIALIZED),this.videoState.startTransitionTo(j.READY)}),s(re(this.player,"fragmentLoadingCompleted"),({request:m})=>{if(!m.requestEndDate||!m.firstByteDate||!m.bytesLoaded)return;const S=m.requestEndDate.getTime()-m.firstByteDate.getTime(),b=m.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(b,S)}),s(a.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const m=this.params.dependencies.throughputEstimator.throughput$.getValue(),S=di(this.videoTracks.map(({track:g})=>g),{container:this.elementSize$.getValue(),throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),b=this.videoTracks.find(({track:g})=>g===S);b!=null&&b.bitrateInfo&&this.player.setQualityFor("video",b==null?void 0:b.bitrateInfo.qualityIndex,!1)}),s(a.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(a.filter(a.isNonNullable))}).pipe(a.filter(({isLive:m})=>m),a.map(({maxSeekBackTime:m})=>-m/1e3)),this.params.output.duration$);const o=re(this.player,"playbackTimeUpdated").pipe(a.map(({time:m})=>m!=null?m:0));s(a.combine({availableFrom:this.availableFrom$.pipe(a.filter(a.isNonNullable)),currentTime:o}),({availableFrom:m,currentTime:S})=>this.params.output.liveTime$.next(m+S*1e3)),s(o.pipe(a.filter(()=>this.isLive$.getValue()===!1)),e.position$),s(re(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),s(re(this.player,"playbackEnded"),e.endedEvent$),s(re(this.player,"playbackProgress").pipe(a.map(()=>wl(this.video.buffered,this.video.currentTime))),e.currentBuffer$),s(re(this.player,"playbackPlaying"),()=>{this.videoState.setState(j.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)}),s(re(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(j.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),s(re(this.player,"playbackPaused"),()=>{this.videoState.setState(j.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)}),s(re(this.player,"canPlay"),()=>{var m;((m=this.videoState.getTransition())===null||m===void 0?void 0:m.to)===j.READY&&this.videoState.setState(j.READY)}),s(this.isLive$,e.isLive$),s(Ji(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const l=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));s(l,this.syncPlayback);const{playbackDuration$:d,ping$:u,connectionType$:c,connectionReused$:h}=mS(this.player);s(c,this.params.output.httpConnectionType$),s(h,this.params.output.httpConnectionReused$),s(d,this.maxSeekBackTime$),s(u.pipe(a.once()),e.firstBytesEvent$),s(re(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&s(a.combine({isLive:this.isLive$,isShort:e.duration$.pipe(a.map(m=>m<60))}),({isLive:m,isShort:S})=>{const b=!m&&S;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:b}}})}),s(o.pipe(a.filter(m=>m>this.params.tuning.insufficientBufferRuleMargin),a.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(re(this.player,"manifestLoaded").pipe(a.once()).subscribe(()=>{this.subscription.add(re(this.player,"playbackPlaying").pipe(a.once(),a.mapTo(void 0)).subscribe(e.firstFrameEvent$,r))},r)),this.subscription.add(pt(this.video,t.isLooped,r));const{volumeState$:f,looped$:p,playbackRateState$:v}=qe(this.video);this.subscription.add(He(this.video,t.volume,f,r)),this.subscription.add(f.subscribe(e.volume$,r)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(Ze(this.video,t.playbackRate,v,r))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(j.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(j.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3);const s=At(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,_t.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(j.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(j.PAUSED),this.video.pause()}destroy(){var e,t;this.subscription.unsubscribe(),this.textTracksManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(r){}this.video.remove(),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var ci=i=>{switch(i){case"mobile":return exports.VideoQuality.Q_144P;case"lowest":return exports.VideoQuality.Q_240P;case"low":return exports.VideoQuality.Q_360P;case"sd":case"medium":return exports.VideoQuality.Q_480P;case"hd":case"high":return exports.VideoQuality.Q_720P;case"fullhd":case"full":return exports.VideoQuality.Q_1080P;case"quadhd":case"quad":return exports.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return exports.VideoQuality.Q_2160P}},et=i=>X(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(r){return i.muted=!1,console.warn(r),!1}}return!0});function oe(){return a.now()}function Al(i){return oe()-i}function Ln(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,s=o=>r.test(o);return{resolve:(o,l,d=!1)=>{s(o)||(o.startsWith("/")||(o="/"+o),o=t+o);let u=o.indexOf("?")>-1?"&":"?";return d&&(o+=u+"lowLat=1",u="&"),l&&(o+=u+"_rnd="+Math.floor(999999999*Math.random())),o}}}function FS(i,e,t){const r=(...s)=>{t.apply(null,s),i.removeEventListener(e,r)};i.addEventListener(e,r)}function ji(i,e,t,r){const s=window.XMLHttpRequest;let n,o,l,d=!1,u=0,c,h,f=!1,p="arraybuffer",v=7e3,m=2e3,S=()=>{if(d)return;a.assertNonNullable(c);const A=Al(c);let B;if(A<m){B=m-A,setTimeout(S,B);return}m*=2,m>v&&(m=v),o&&o.abort(),o=new s,w()};const b=A=>(n=A,N),g=A=>(h=A,N),k=()=>(p="json",N),T=()=>{if(!d){if(--u>=0){S(),r&&r();return}d=!0,h&&h(),t&&t()}},E=A=>(f=A,N),w=()=>{c=oe(),o=new s,o.open("get",i);let A=0,B,F=0;const Y=()=>(a.assertNonNullable(c),Math.max(c,Math.max(B||0,F||0)));if(n&&o.addEventListener("progress",$=>{const O=oe();n.updateChunk&&$.loaded>A&&(n.updateChunk(Y(),$.loaded-A),A=$.loaded,B=O)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>T())),o.addEventListener("load",()=>{if(d)return;a.assertNonNullable(o);const $=o.status;if($>=200&&$<300){if(o.response.byteLength&&n){const O=o.response.byteLength-A;O&&n.updateChunk&&n.updateChunk(Y(),O)}h&&h(),o&&e(o.response)}else T()}),o.addEventListener("error",()=>{T()}),f){const $=()=>{a.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(F=oe(),o.removeEventListener("readystatechange",$))};o.addEventListener("readystatechange",$)}return o.responseType=p,o.send(),N},N={withBitrateReporting:b,withParallel:E,withJSONResponse:k,withRetryCount:A=>(u=A,N),withRetryInterval:(A,B)=>(a.isNonNullable(A)&&(m=A),a.isNonNullable(B)&&(v=B),N),withTimeout:A=>(l=A,N),withFinally:g,send:w,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return N}const US=100,jS=2e3,HS=500;let GS=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,r){return{start:e,end:t,bytes:r}}_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-HS;if(t-e>jS){let r=0,s=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)r+=n.end-n.start,s+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,l=n.end-n.start;r+=o;const d=n.bytes*o/l;s+=d,n.start=t,n.bytes-=d}}}if(s>0&&r>0){const n=s*8/(r/1e3);return this._updateRate(n),this.logger(`rate updated, new=${Math.round(n/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(s)}/${Math.round(r)} 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,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>US&&(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 qS{constructor(e,t,r,s,n){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=r,this.MAX_PARALLEL_REQUESTS=s,this.logger=n}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 r=oe(),s=d=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=d,e._errorCB?e._errorCB(d):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=d=>{e._complete=1,e._responseData=d,e._downloadTime=oe()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(d,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},o=()=>{e._finallyCB&&e._finallyCB()},l=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=ji(t,n,()=>s("error"),l),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(o),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=oe()}_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=oe();if(Object.keys(this.activeRequests).length>=e)return!1;const r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!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,r,s){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=r,o._retryCB=s,o._finallyCB=n._finallyCB,o._error||o._complete?(this._removeFromActive(e),setTimeout(()=>{o._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(o._responseData,o._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(o._errorMsg)),n._finallyCB&&n._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const l=this.pendingQueue.indexOf(e);l!==-1&&this.pendingQueue.splice(l,1),this.logger(`Request not prefetched, starting new request, url=${e}${l===-1?"":"; removed pending"}`),this._sendRequest(n,e)}},n._cb=t,n._errorCB=r,n._retryCB=s,n.abort=function(){n.request&&n.request.abort()},n.withFinally=o=>(n._finallyCB=o,n),n}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Ii=1e4,Ni=3,YS=300,zS=2e3,WS=6e4,QS=10,JS=1,KS=500;class XS{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 GS(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Ln(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],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=Ln(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 r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-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 r;Boolean(e.error)&&!this.destroyed&&(t(`Video element error: ${(r=e.error)===null||r===void 0?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.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,r=t.buffered.length;let s;r!==0&&(s=t.buffered.start(r-1),t.currentTime<s&&(e("Fixup stall"),t.currentTime=s))}_selectQuality(e){const{videoElement:t}=this.params;let r,s,n;const o=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let l=0;l<this.manifest.length;++l)n=this.manifest[l],!(this.maxAutoQuality&&n.video.height>this.maxAutoQuality)&&(n.bitrate<e&&o>Math.min(n.video.height,n.video.width)?(!s||n.bitrate>s.bitrate)&&(s=n):(!r||r.bitrate>n.bitrate)&&(r=n));return s||r}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||a.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:r,videoElement:s,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,s.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{FS(s,"progress",()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),n({name:"playing"})):o()})};o()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new qS(Ni,Ii,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:r,playerCallback:s}=this.params;let n=!1,o=null,l=null,d=null,u=null,c=!1;const h=()=>{const T=n&&(!c||c===this.rep);return T||t("Not running!"),T},f=(T,E,w)=>{d&&d.abort(),d=ji(this.urlResolver.resolve(T,!1),E,w,()=>this._retryCallback()).withTimeout(Ii).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ni).withFinally(()=>{d=null}).send()},p=(T,E,w)=>{a.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),E,w,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},v=T=>{const E=r.playbackRate;r.playbackRate!==T&&(t(`Playback rate switch: ${E}=>${T}`),r.playbackRate=T)},m=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),S()},S=()=>{if(!this.lowLatency)v(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){v(1);return}const w=oe()-6e4;let x=0;for(let R=0;R<this.bufferStates.length;R++){const V=this.bufferStates[R];T=Math.min(T,V.buf),V.ts<w&&x++}this.bufferStates.splice(0,x),t(`update playback rate; minBuffer=${T} drop=${x} jitter=${this.sourceJitter}`);let C=T-JS;this.sourceJitter>=0?C-=this.sourceJitter/2:this.sourceJitter-=1,C>3?v(1.15):C>1?v(1.1):C>.3?v(1.01):v(1)}},b=T=>{let E;const w=()=>E&&E.start?E.start.length:0,x=$=>E.start[$]/1e3,C=$=>E.dur[$]/1e3,R=$=>E.fragIndex+$,V=($,O)=>({chunkIdx:R($),startTS:x($),dur:C($),discontinuity:O}),N=()=>{let $=0;if(E&&E.dur){let O=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,Q=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,te=O;this.sourceJitter>1&&(te+=this.sourceJitter-1);let ie=E.dur.length-1;for(;ie>=0&&(te-=E.dur[ie],!(te<=0));--ie);$=Math.min(ie,E.dur.length-1-Q),$=Math.max($,0)}return V($,!0)},A=$=>{const O=w();if(!(O<=0)){if(a.isNonNullable($)){for(let Q=0;Q<O;Q++)if(x(Q)>$)return V(Q)}return N()}},B=$=>{const O=w(),Q=$?$.chunkIdx+1:0,te=Q-E.fragIndex;if(!(O<=0)){if(!$||te<0||te-O>QS)return t(`Resync: offset=${te} bChunks=${O} chunk=`+JSON.stringify($)),N();if(!(te>=O))return V(Q-E.fragIndex,!1)}},F=($,O,Q)=>{u&&u.abort(),u=ji(this.urlResolver.resolve($,!0,this.lowLatency),O,Q,()=>this._retryCallback()).withTimeout(Ii).withRetryCount(Ni).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:($,O)=>{F(T,Q=>{if(!h())return;E=Q;const te=Boolean(E.lowLatency);te!==this.lowLatency&&m(te);let ie=0;for(let ce=0;ce<E.dur.length;++ce)ie+=E.dur[ce];ie>0&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ie/E.dur.length)),s({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,$(A(O))},()=>this._handleNetworkError())},nextChunk:B}},g=()=>{n=!1,l&&l.abort(),d&&d.abort(),u&&u.abort(),a.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:T=>{const{videoElement:E,logger:w}=this.params;let x=b(e.jidxUrl),C,R,V,N,A=0,B,F,Y;const $=()=>{B&&(clearTimeout(B),B=void 0);const H=Math.max(KS,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ae=A+H,ue=oe(),me=Math.min(1e4,ae-ue);A=ue;const tt=()=>{u||h()&&x.seek(()=>{h()&&(A=oe(),O(),$())})};me>0?B=window.setTimeout(()=>{this.paused?$():tt()},me):tt()},O=()=>{let H;for(;H=x.nextChunk(N);)N=H,ke(H);const ae=x.nextChunk(V);if(ae){if(V&&ae.discontinuity){w("Detected discontinuity; restarting playback"),this.paused?$():(g(),this._initPlayerWith(e));return}ce(ae)}else $()},Q=(H,ae)=>{if(!h()||!this.sourceBuffer)return;let ue,me,tt;const _e=Ye=>{window.setTimeout(()=>{h()&&Q(H,ae)},Ye)};if(this.sourceBuffer.updating)w("Source buffer is updating; delaying appendBuffer"),_e(100);else{const Ye=oe(),it=E.currentTime;!this.paused&&E.buffered.length>1&&F===it&&Ye-Y>500&&(w("Stall suspected; trying to fix"),this._fixupStall()),F!==it&&(F=it,Y=Ye);const xt=this._getBufferSizeSec();if(xt>30)w(`Buffered ${xt} seconds; delaying appendBuffer`),_e(2e3);else try{this.sourceBuffer.appendBuffer(H),this.videoPlayStarted?(this.bufferStates.push({ts:Ye,buf:xt}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ae&&ae()}catch(mt){if(mt.name==="QuotaExceededError")w("QuotaExceededError; delaying appendBuffer"),tt=this.sourceBuffer.buffered.length,tt!==0&&(ue=this.sourceBuffer.buffered.start(0),me=it,me-ue>4&&this.sourceBuffer.remove(ue,me-3)),_e(1e3);else throw mt}}},te=()=>{R&&C&&(w([`Appending chunk, sz=${R.byteLength}:`,JSON.stringify(V)]),Q(R,function(){R=null,O()}))},ie=H=>e.fragUrlTemplate.replace("%%id%%",H.chunkIdx),ce=H=>{h()&&p(ie(H),(ae,ue)=>{if(h()){if(ue/=1e3,R=ae,V=H,o=H.startTS,ue){const me=Math.min(10,H.dur/ue);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*me:me}te()}},()=>this._handleNetworkError())},ke=H=>{h()&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ie(H),!1)))},Lt=H=>{h()&&(e.cachedHeader=H,Q(H,()=>{C=!0,te()}))};n=!0,x.seek(H=>{if(h()){if(A=oe(),!H){$();return}N=H,!a.isNullable(T)||H.startTS>T?ce(H):(V=H,O())}},T),e.cachedHeader?Lt(e.cachedHeader):f(e.headerUrl,Lt,()=>this._handleNetworkError())},stop:g,getTimestampSec:()=>o},c}_switchToQuality(e){const{logger:t,playerCallback:r}=this.params;let s;e.bitrate!==this.bitrate&&(this.rep&&(s=this.rep.getTimestampSec(),a.isNonNullable(s)&&(s+=.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,a.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(s),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return a.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,r=h=>{if(!this.autoQuality)return;let f,p,v;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(p=this._getBufferSizeSec(),v=h/this.bitrate,p>10&&v>.8||p>15&&v>.5||p>20&&v>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}f=this._selectQuality(h),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${h}`)},n=(()=>({updateChunk:(f,p)=>{const v=oe();if(this.chunkRateEstimator.addInterval(f,v,p)){const S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:v-f,speed:S}),!0}},get:()=>{const f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}}))();let o=-1/0,l,d=!0;const u=()=>{let h=n.get();if(h&&l&&this.autoQuality){if(d&&h>l&&Al(o)<3e4)return;r(h)}d=this.autoQuality};return{updateChunk:(h,f)=>{const p=n.updateChunk(h,f);return p&&u(),p},notifySwitch:h=>{const f=oe();h<l&&(o=f),l=h}}}_fetchManifest(e,t,r){this.manifestRequest=ji(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Ii).withRetryCount(Ni).withRetryInterval(YS,zS).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;et(t).then(r=>{r||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:r,videoElement:s}=this.params,n=o=>{const l=[];return o!=null&&o.length?(o.forEach((d,u)=>{d.video&&s.canPlayType(d.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(d.codecs)&&(d.index=u,l.push(d))}),l.sort(function(d,u){return d.video&&u.video?u.video.height-d.video.height:u.bitrate-d.bitrate}),l):(this.params.playerCallback({name:"error",type:"partial_metadata"}),[])};this.manifest=n(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({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))},WS))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var L;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(L||(L={}));const ZS=[L.PAUSED,L.PLAYING,L.READY],eb=[L.PAUSED,L.PLAYING,L.READY];class tb{constructor(e){this.subscription=new a.Subscription,this.videoState=new K(L.STOPPED),this.representations$=new a.ValueSubject([]),this.textTracksManager=new Oe,this.maxSeekBackTime$=new a.ValueSubject(1/0),this.zeroTime$=new a.ValueSubject(void 0),this.liveOffset=new sa,this._dashCb=s=>{var n,o,l,d;switch(s.name){case"buffering":{const u=s.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${s.type}`,category:a.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=s.manifest,c=[];for(const h of u){const f=(n=h.name)!==null&&n!==void 0?n:h.index.toString(10),p=(o=ci(h.name))!==null&&o!==void 0?o:ft(h.video),v=h.bitrate/1e3,m=Object.assign({},h.video);if(!p)continue;const S={id:f,quality:p,bitrate:v,size:m};c.push({track:S,representation:h})}this.representations$.next(c),this.params.output.availableVideoTracks$.next(c.map(({track:h})=>h)),((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===L.MANIFEST_READY&&this.videoState.setState(L.MANIFEST_READY);break}case"qualitySwitch":{const u=s.quality,c=(d=this.representations$.getValue().find(({representation:h})=>h===u))===null||d===void 0?void 0:d.track;this.params.output.hostname$.next(new URL(u.headerUrl,this.params.source.url).hostname),a.isNonNullable(c)&&this.params.output.currentVideoTrack$.next(c);break}case"bandwidth":{const{size:u,duration:c}=s;this.params.dependencies.throughputEstimator.addRawSpeed(u,c);break}case"index":{this.maxSeekBackTime$.next(s.shiftDuration),this.zeroTime$.next(s.zeroTime);break}}},this.syncPlayback=()=>{var s;const n=this.videoState.getState(),o=this.videoState.getTransition(),l=this.params.desiredState.playbackState.getState(),d=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${n}; videoTransition: ${JSON.stringify(o)}; desiredPlaybackState: ${l}; seekState: ${JSON.stringify(u)};`}),l===exports.PlaybackState.STOPPED){n!==L.STOPPED&&(this.videoState.startTransitionTo(L.STOPPED),this.dash.destroy(),this.video.setAttribute("src",""),this.video.load(),this.videoState.setState(L.STOPPED));return}if(!o){if(eb.includes(n)){const c=(s=this.params.desiredState.videoTrack.getTransition())===null||s===void 0?void 0:s.to;a.isNonNullable(c)&&this.setVideoTrack(c);const h=this.params.desiredState.autoVideoTrackSwitching.getTransition();h&&this.setAutoQuality(h.to)}if((d==null?void 0:d.to)!==exports.PlaybackState.PAUSED&&u.state===D.Requested&&ZS.includes(n)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(n){case L.STOPPED:this.videoState.startTransitionTo(L.MANIFEST_READY),this.dash.attachSource(At(this.params.source.url));return;case L.MANIFEST_READY:this.videoState.startTransitionTo(L.READY),this.prepare();break;case L.READY:l===exports.PlaybackState.PAUSED?this.videoState.setState(L.PAUSED):l===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(L.PLAYING),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(L.PAUSED)}));return;case L.PLAYING:l===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(L.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case L.PAUSED:l===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(L.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(L.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return a.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=s=>{e.output.error$.next({id:"DashLiveProvider",category:a.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:s})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(s)}`})}),this.video=Ge(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(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const r=qe(this.video);this.subscription.add(r.canplay$.subscribe(()=>{var s;((s=this.videoState.getTransition())===null||s===void 0?void 0:s.to)===L.READY&&this.videoState.setState(L.READY)},t)).add(r.pause$.subscribe(()=>{this.videoState.setState(L.PAUSED)},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===D.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(L.PLAYING)},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(s=>-s/1e3)).subscribe(this.params.output.duration$)).add(a.combine({zeroTime:this.zeroTime$.pipe(a.filter(a.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:s,position:n})=>this.params.output.liveTime$.next(s+n*1e3),t)).add(pt(this.video,this.params.desiredState.isLooped,t)).add(He(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ze(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:s}})=>{const n=s&&aS(s);this.dash.setMaxAutoQuality(n)})).add(this.videoState.stateChangeEnded$.subscribe(s=>{switch(s.to){case L.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case L.MANIFEST_READY:case L.READY:break;case L.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case L.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(s.to)}},t)).add(a.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const e=new XS({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},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,r,s,n,o;const l=this.representations$.getValue(),d=(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(),u=(s=(r=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||r===void 0?void 0:r.to)!==null&&s!==void 0?s:this.params.desiredState.autoVideoTrackSwitching.getState(),c=!u&&a.isNonNullable(d)?d:(n=di(l.map(({track:f})=>f),{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||n===void 0?void 0:n.id,h=(o=l.find(({track:f})=>f.id===c))===null||o===void 0?void 0:o.representation;a.assertNonNullable(h,"Representations missing"),this.dash.startPlay(h,u),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(c),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(u)}setVideoTrack(e){var t;const r=(t=this.representations$.getValue().find(({track:s})=>s.id===e))===null||t===void 0?void 0:t.representation;a.assertNonNullable(r,`No such representation ${e}`),this.dash.switchByName(r.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,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.dash.reinit(At(this.params.source.url,r))}}var Rl=i=>{var e,t;const r=i.get("X-Delivery-Type"),s=i.get("X-Reused"),n=r===null?exports.HttpConnectionType.HTTP1:(e=r)!==null&&e!==void 0?e:void 0,o=s===null?void 0:(t={1:!0,0:!1}[s])!==null&&t!==void 0?t:void 0;return{type:n,reused:o}},wt=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){const s=i.start(r)*1e3,n=i.end(r)*1e3;s<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const ib=i=>{const e=document.createElement("a");return e.href=i,e.origin},rb=i=>{const e=document.createElement("a");return e.href=i,e.host};class Il{constructor(e,t=[],r,s,n,o){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=r,this._progressCb=s,this._headersCb=n,this._errorCb=o,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,r,s,n,o,l,d,u;if(a.assertNonNullable(this._xhr),((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(r=this._errorCb)===null||r===void 0||r.call(this,`Http${(s=this._xhr)===null||s===void 0?void 0:s.status}`,`XHR response code ${(n=this._xhr)===null||n===void 0?void 0:n.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const c=oi(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(h=>h.split(":").map(f=>f.trim())));(o=this._headersCb)===null||o===void 0||o.call(this,new Headers(c))}else this._xhr.readyState===4?(l=this._completeCb)===null||l===void 0||l.call(this,this._xhr.response):this._xhr.readyState===3&&((d=this._progressCb)===null||d===void 0||d.call(this,this._xhr.response))}catch(c){throw(u=this._errorCb)===null||u===void 0||u.call(this,"XHR2CallbackError",`xhr2 callback threw ${String(c)}`,c),c}},this._xhr.onerror=()=>{var t;(t=this._xhr)===null||t===void 0||t.abort(),this._retryTimeout=window.setTimeout(()=>{var r;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(r=this._errorCb)===null||r===void 0||r.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let s;this._failoverIndex>=this._failoverHosts.length?(s=this._url,this._failoverIndex=0):(s=this._url.replace(rb(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",s,!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 Ki{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(r){if(r.name==="QuotaExceededError"){this._isFull=!0;const s=this._sourceBuffer.buffered;let n=0;for(let o=0,l=s.length;o<l;o++)n+=s.end(o)-s.start(o);n&&(this._maxBufferDuration=Math.round(n))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",r),r}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,r,s,n,o,l){this.abort(()=>{let d=0;const u=Date.now();let c=0,h=0,f=0;const p=m=>{s(Ki._str2ua(m.substr(d))),d=m.length};let v=e.baseURL+"&bytes="+t+"-"+r;this._params.requestQuic&&(v=It(v)),this._lastXhr=new Il(v,e.failoverHosts,m=>{this._lastXhr=void 0,p(m);const S=Date.now()-u;this._params.onBandwidthChange({size:m.length,duration:S,speed:8*m.length/(S/1e3)}),this._onDashCallback("loading",{size:m.length,done:!0}),n==null||n()},m=>{if(m.length-d>l&&p(m),h===0){h=Date.now();return}f=m.length-c;const S=Date.now()-h;f>=100*1024&&S>=1e3&&(this._params.onBandwidthChange({size:f,duration:S,speed:8*f/(S/1e3)}),f=0,c=m.length,h=Date.now()),this._onDashCallback("loading",{size:m.length,done:!1})},o,(m,S,b)=>this._params.onError(m,S,b))})}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(r){throw this._params.onError("SourceBuffer","Source Buffer update error",r),r}};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=Ki._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 r=new Uint8Array(e.byteLength+t.byteLength);return r.set(e,0),r.set(t,e.byteLength),r}static _str2ua(e){const t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);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 sb{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)?)?$/,r=(l,d)=>{const u=l?parseFloat(l.replace(",",".")):NaN;return(isNaN(u)?0:u)*d},s=t.exec(e),n=(s==null?void 0:s[1])==="-"?-1:1,o={years:r(s==null?void 0:s[2],n),months:r(s==null?void 0:s[3],n),weeks:r(s==null?void 0:s[4],n),days:r(s==null?void 0:s[5],n),hours:r(s==null?void 0:s[6],n),minutes:r(s==null?void 0:s[7],n),seconds:r(s==null?void 0:s[8],n)};return o.hours*3600+o.minutes*60+o.seconds}getRepresentations(){return this._representations}attachSource(e,t){let r=e;this._config.REQUEST_QUIC&&(r=It(r)),new Il(r,t,s=>{this.attachManifest(s,t,ib(r))},void 0,s=>{this._params.onResponseHeaders(s)},(s,n,o)=>this._params.onError(s,n,o))}attachManifest(e,t,r){const n=new DOMParser().parseFromString(e,"text/xml").documentElement,o=(u,c)=>{const h=u.attributes.getNamedItem(c);return h?h.value:null};this._duration=this._parseDurationFromISO8601(String(o(n,"mediaPresentationDuration")));const l=[],d=[];if(Array.prototype.forEach.call(n.getElementsByTagName("Representation"),u=>{var c,h,f,p,v,m,S,b,g,k,T,E,w,x,C,R,V,N,A;const B=u.getElementsByTagName("SegmentBase")[0],F=B&&o(B,"indexRange").split("-"),Y=B&&B.getElementsByTagName("Initialization")[0],$=Y&&o(Y,"range").split("-");if(!$||!F){const ke=u.parentElement;if((ke==null?void 0:ke.getAttribute("contentType"))==="text"){const Lt=(c=u.getAttribute("id"))!==null&&c!==void 0?c:void 0,H=(r?r+"/":"")+((v=(p=(f=(h=u.getElementsByTagName("BaseURL"))===null||h===void 0?void 0:h[0])===null||f===void 0?void 0:f.childNodes)===null||p===void 0?void 0:p[0])===null||v===void 0?void 0:v.data),ae=(m=ke.getAttribute("lang"))!==null&&m!==void 0?m:void 0;H&&d.push({id:Lt,url:H,language:ae})}return}const O=.1,Q=Number((S=u.attributes.getNamedItem("bandwidth"))===null||S===void 0?void 0:S.value),te=(r?r+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ie;const ce=(g=(b=u.attributes.getNamedItem("frameRate"))===null||b===void 0?void 0:b.value)!==null&&g!==void 0?g:void 0;ie=ce?aa(ce):void 0,l.push({width:Number((k=u.attributes.getNamedItem("width"))===null||k===void 0?void 0:k.value),height:Number((T=u.attributes.getNamedItem("height"))===null||T===void 0?void 0:T.value),bandwidth:Q,baseURL:te,failoverHosts:t,indexFrom:Number(F[0]),indexTo:Number(F[1]),initFrom:Number($[0]),initTo:Number($[1]),codecs:(w=(E=u.attributes.getNamedItem("codecs"))===null||E===void 0?void 0:E.value)!==null&&w!==void 0?w:void 0,mimeType:(C=(x=u.attributes.getNamedItem("mimeType"))===null||x===void 0?void 0:x.value)!==null&&C!==void 0?C:void 0,fps:ie,bufferSize:O*Q/8,bufferLength:O,name:(V=(R=u.attributes.getNamedItem("okQuality"))===null||R===void 0?void 0:R.value)!==null&&V!==void 0?V:void 0,id:(A=(N=u.attributes.getNamedItem("id"))===null||N===void 0?void 0:N.value)!==null&&A!==void 0?A:void 0})}),l.length)this._representations=l;else{this._onDashCallback("error");return}d.forEach(({id:u,language:c,url:h})=>{const f=document.createElement("track");f.setAttribute("src",h),u&&f.setAttribute("id",u),c&&f.setAttribute("srclang",c),this._video.appendChild(f)}),this._representations.sort((u,c)=>c.bandwidth-u.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 r=Date.now();this._stream.load(e,e.initFrom,e.indexTo,s=>{let n=e.initTo-e.initFrom+1;if(!s.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(s.buffer,0,n);const o=new DataView(s.buffer);n+=12;const l=o.getUint32(n+4,!1);n+=8;let d=o.getUint32(n,!1),u=o.getUint32(n+4,!1)+(e.indexTo+1);n+=8;const c=o.getUint16(n+2,!1);n+=4,e.refs=[];for(let f=0;f<c;f+=1){const p=u+(o.getUint32(n,!1)&2147483647),v=d+o.getUint32(n+4,!1);n+=12,e.refs.push({fromTime:d/l,toTime:v/l,fromOffset:u,toOffset:p-1}),u=p,d=v}const h=e.refs[e.refs.length-1];h.toTime-h.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,s=>{this._params.onResponseHeaders(s),this._params.onIdxRequestPing(Date.now()-r)},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 r=new t;let s,n;const o=()=>{const u=this._findRef(this._video.currentTime);if(!u||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const p=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),p)}const c=this._appendVector[String(u.fromTime)];c!==s&&(s=c,this._params.onRepresentationPlay(c));let h;if(this._findRef(u.toTime)){const p=this._buffer.getByTime(this._video.currentTime);if(!p){this._onDashCallback("buffering");return}h=p.to-this._video.currentTime,h<e.bufferLength&&(this._onDashCallback("buffering"),n!==p.to&&(n=p.to,window.setTimeout(()=>{try{const v=this._buffer.getNextWithGap(p);v&&(this._video.currentTime=v.from)}catch(v){throw this._params.onError("GapSyncError",`Seek Error ${String(v)}`,v),v}},h*1e3)))}},l=()=>{this._loopTimeout=window.setTimeout(()=>{try{o()}catch(u){throw this._params.onError("LoopError",`Dash Loop exception ${String(u)}`,u),u}l()},250)},d=()=>{if(!this._stream)try{const u=r.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Ki({mediaSource:r,sourceBuffer:u,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(u){throw this._params.onError("DashSourceOpen",`Source open exception ${String(u)}`,u),u}this._loadInitAndSidx(e),r.duration||(r.duration=this._duration),this._loopTimeout||l(),r.removeEventListener("sourceopen",d),r.removeEventListener("webkitsourceopen",d)};r.addEventListener("sourceopen",d,!1),r.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(r),this._video.addEventListener("waiting",()=>{const u=this._video&&this._video.played.length;u&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(u-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,r=!1,s=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const n=this._findRef(t);if(n){if(r){this._isLastRef(n)&&t>=n.toTime&&(t=n.fromTime);const o=this._findRef(this._video.currentTime),l=Math.abs(this._video.currentTime-t),d=s||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||n===o||l<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=d?t:n.fromTime}this._appendVector[String(n.fromTime)]=e,this._stream.load(e,n.fromOffset,n.toOffset,(o,l)=>this._stream.append(o,l),()=>{this._lastLoadOffset=n.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},o=>this._params.onResponseHeaders(o),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const r=this._buffer.getByTime(this._video.currentTime),s=this._findRef(this._video.currentTime);if(!r||!s){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(s.toTime<r.to+n){const o=this._findRef(s.toTime);o&&o.toTime<r.to+n?(this._buffer.smartRemove(s.fromTime-n,o.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(s.fromTime-n,s.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,s.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||a.isNullable(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const r=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!r)return;if(Array.isArray(r)&&r.length===0){this._params.onError("emptyrefs","Empty refs");return}let s;for(let n=0;n<r.length;n++){const o=r[n];if(o.fromTime<=e&&o.toTime>e)return o;o.fromTime>e&&(!s||o.fromTime<s.fromTime)&&(s=o)}if(!s){const n=r[r.length-1];if(e>n.toTime)return n}return s}_isLastRef(e){var t;const r=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!r)return!1;const s=r[r.length-1];return e.fromTime===s.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const r=this._video.buffered.start(t),s=this._video.buffered.end(t);if(e>r&&e<s)return Math.round(s*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var M;(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"})(M||(M={}));const ab=[M.PAUSED,M.PLAYING];class nb{constructor(e){this.videoState=new K(M.STOPPED),this.subscription=new a.Subscription,this.representations$=new a.ValueSubject([]),this.currentRepresentation$=new a.ValueSubject(void 0),this.textTracksManager=new Oe,this.elementSize$=new a.ValueSubject(void 0),this.dashLiteEvents={idxRequestPing$:new a.Subject,responseHeaders$:new a.Subject,manifestReady$:new a.Subject,representationPlay$:new a.Subject,error$:new a.Subject},this.handleManifestReady=t=>{var r,s,n;const o=[];for(const l of t){const d=(s=(r=l.name)!==null&&r!==void 0?r:l.id)!==null&&s!==void 0?s:l.height.toString(10),u=(n=l.name&&ci(l.name))!==null&&n!==void 0?n:ft(l),c=l.bandwidth/1e3,h={width:l.width,height:l.height},f=l.fps;if(!u)continue;const p={id:d,quality:u,bitrate:c,size:h,fps:f};o.push({track:p,representation:l})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:l})=>l)),this.videoState.setState(M.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var r;const s=(r=this.representations$.getValue().find(({representation:n})=>n===t))===null||r===void 0?void 0:r.track;s&&(this.params.output.currentVideoTrack$.next(s),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(s.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return a.assertNonNullable(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${s}; seekState: ${JSON.stringify(o)};`}),s===exports.PlaybackState.STOPPED){t!==M.STOPPED&&(this.videoState.startTransitionTo(M.STOPPED),this.dash.destroy(),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(M.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!r)switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&o.state===D.Requested&&ab.includes(t)&&this.seek(o.position,o.forcePrecise),t){case M.STOPPED:this.videoState.startTransitionTo(M.MANIFEST_LOADED),this.prepare();return;case M.MANIFEST_LOADED:this.videoState.startTransitionTo(M.INITIAL_REPRESENTATION_SELECTED);return;case M.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(M.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case M.METADATA_LOADED:this.videoState.startTransitionTo(M.READY),this.dash.updateRefsForCurrentTime();return;case M.READY:s===exports.PlaybackState.PAUSED?(this.videoState.setState(M.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(M.PLAYING),this.playIfAllowed());return;case M.PLAYING:s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(M.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case M.PAUSED:s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(M.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),a.merge(this.videoState.stateChangeStarted$.pipe(a.map(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:r})=>{this.log({message:`[videoState change] ${r}: ${JSON.stringify(t)}`})}),this.video=Ge(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.source.type==="url"&&this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new yS(this.video),this.dash=new sb({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,r,s)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:r,thrown:s,category:a.ErrorCategory.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,r=l=>{e.error$.next({id:"DashProvider",category:a.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:l})},s=()=>{const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:l},n=qe(this.video),o=(l,d)=>this.subscription.add(l.subscribe(d,r));o(n.timeUpdate$,e.position$),o(n.durationChange$,e.duration$),o(n.ended$,e.endedEvent$),o(n.looped$,e.loopedEvent$),o(n.error$,e.error$),o(n.isBuffering$,e.isBuffering$),o(n.playing$,e.firstFrameEvent$),o(n.canplay$,e.canplay$),this.subscription.add(n.seeking$.subscribe(()=>{a.isNullable(this.params.desiredState.seekState.getState().state!==D.Applying)&&(this.videoState.getState()===M.PLAYING||this.videoState.getState()===M.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(pt(this.video,t.isLooped,r)),this.subscription.add(He(this.video,t.volume,n.volumeState$,r)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ze(this.video,t.playbackRate,n.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),o(Ji(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===M.READY&&this.videoState.setState(M.READY)},r)).add(n.pause$.subscribe(()=>{this.videoState.setState(M.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(M.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},r)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(M.METADATA_LOADED)},r)).add(n.currentBuffer$.subscribe(l=>{this.buffer.fill(),e.currentBuffer$.next(l)},r)).add(this.dashLiteEvents.error$.pipe(a.map(({id:l,message:d,thrown:u})=>({id:`DashLite_${l}`,category:a.ErrorCategory.WTF,message:d,thrown:u}))).subscribe(this.params.output.error$)).add(a.merge(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$,a.fromEvent(this.video,"progress")).pipe(a.map(()=>{var l,d,u;const c=this.currentRepresentation$.getValue(),h=this.representations$.getValue(),f=this.params.desiredState.autoVideoTrackSwitching.getTransition(),p=this.params.desiredState.videoTrack.getState(),v=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),m=this.elementSize$.getValue(),S=s();f&&this.params.desiredState.autoVideoTrackSwitching.setState(f.to);let b;if(!S&&a.isNonNullable(p))b=p;else{const g=wt(this.video.buffered,this.video.currentTime*1e3),k=S?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,T=Math.min(g/k,1);b=(d=di(h.map(({track:E})=>E),{container:m,throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:T,playbackRate:this.video.playbackRate,current:(l=h.find(({representation:E})=>E===c))===null||l===void 0?void 0:l.track}))===null||d===void 0?void 0:d.id}return a.isNonNullable(b)?(u=h.find(({track:g})=>g.id===b))===null||u===void 0?void 0:u.representation:void 0}),a.filterChanged()).subscribe(this.currentRepresentation$,r)).add(a.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(a.filter(l=>l.to===M.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(a.filter(a.isNonNullable))}).pipe(a.once()).subscribe(()=>this.videoState.setState(M.INITIAL_REPRESENTATION_SELECTED),r)).add(this.currentRepresentation$.pipe(a.filter(a.isNonNullable),a.filterChanged((l,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&s()?l.height<=d.height:l===d)).subscribe(l=>{const d=wt(this.video.buffered,this.video.currentTime*1e3),u=Math.min(d/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||u<=.5||!s())&&(this.dash.setQualityByRepresentation(l,!0),this.params.output.hostname$.next(de(l.baseURL)))},r)).add(this.dashLiteEvents.responseHeaders$.subscribe(l=>{const{type:d,reused:u}=Rl(l);this.params.output.httpConnectionType$.next(d),this.params.output.httpConnectionReused$.next(u)})).add(this.dashLiteEvents.idxRequestPing$.pipe(a.once(),a.mapTo(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(l=>this.params.dependencies.throughputEstimator.addRawRtt(l))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,r)).add(this.dashLiteEvents.representationPlay$.pipe(a.filter(a.isNonNullable)).subscribe(this.handleRepresentationPlay,r)).add(a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return a.assertNever(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){et(this.video).then(e=>{e||(this.videoState.setState(M.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}}var Se;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(Se||(Se={}));var Xi;(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"})(Xi||(Xi={}));var be;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(be||(be={}));var G;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(G||(G={}));var Nt;(function(i){i.MP4="mp4",i.WEBM="webm"})(Nt||(Nt={}));var xn=(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 ob=(i,e={})=>{const r=e.timeout||1,s=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-s-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-s))}})},1)},lb=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Bn=lb?ob:window.requestIdleCallback;var Jr,Kr;let Nl=!1;try{Nl=_l()&&parseInt((Kr=(Jr=navigator.userAgent.match(/Version\/(\d+)/))===null||Jr===void 0?void 0:Jr[1])!==null&&Kr!==void 0?Kr:"",10)<16}catch(i){console.error(i)}class ub{constructor(e){this.bufferFull$=new a.Subject,this.error$=new a.Subject,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const r=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!r),this.currentTask=null}this.queue.length&&this.pull()}catch(r){this.error$.next({id:"BufferTaskQueueUnknown",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:r})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return X(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(r=>{const s={operation:"append",data:e,signal:t,callback:r};this.queue.push(s),this.pull()})})}remove(e,t,r){return X(this,void 0,void 0,function*(){return r&&r.aborted?!1:new Promise(s=>{const n={operation:"remove",from:e,to:t,signal:r,callback:s};this.queue.unshift(n),this.pull()})})}abort(e){return X(this,void 0,void 0,function*(){return new Promise(t=>{let r;Nl&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(const{callback:s}of this.queue)s(!1);r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask)}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:r}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&r==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"&&r==="remove"||this.error$.next({id:`BufferTaskQueue:${r}`,category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:n}),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:a.assertNever(t)}}}var Mn=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};const Cl=new TextDecoder("ascii"),Dl=i=>{let e=0,t=i.getUint32(e);e+=4;const r=new DataView(i.buffer,i.byteOffset+e,4),s=Cl.decode(r);e+=4,t===0?t=1/0:t===1&&(e+=8,t=1/0);const n=Math.min(t,i.byteLength)-e,o=new DataView(i.buffer,i.byteOffset+e,n);return{id:s,size:t,contents:o}},db=i=>Cl.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",cb=i=>{const e=Dl(i),t=[];let r=0;const s=()=>{const p=e.contents.getUint32(r);return r+=4,p};if((s()&4278190080)!==0)throw new SyntaxError("Unsupported sidx version");s();const l=s(),d=s(),u=s(),c=s()&4294967295;let h=d/l*1e3,f=i.byteOffset+i.byteLength+u;for(let p=0;p<c;p++){const v=s(),m=v>>>31,S=v<<1>>>1,b=s();if(s(),m!==0)throw new Error("Unsupported multilevel sidx");const g=b/l*1e3;t.push({status:G.NONE,time:{from:h,to:h+g},byte:{from:f,to:f+S-1}}),h+=g,f+=S}return t},hb=i=>{let e=0,t=!1,r=!1;for(;e<=i.byteLength&&!t;){const s=new DataView(i.buffer,i.byteOffset+e);try{const n=Dl(s);if(r||(r=n.id==="mdat"),e+n.size<=i.byteLength)e+=n.size;else break}catch(n){t=!0}}return e>0&&e<=i.byteLength&&r?new DataView(i.buffer,i.byteOffset,e):null},fb={validateData:db,parseInit:()=>null,getIndexRange:()=>{},parseSegments:cb,parseFeedableSegmentChunk:hb};var y;(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"})(y||(y={}));var _;(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"})(_||(_={}));const Vn={[y.EBML]:{type:_.Master},[y.EBMLVersion]:{type:_.UnsignedInteger},[y.EBMLReadVersion]:{type:_.UnsignedInteger},[y.EBMLMaxIDLength]:{type:_.UnsignedInteger},[y.EBMLMaxSizeLength]:{type:_.UnsignedInteger},[y.DocType]:{type:_.String},[y.DocTypeVersion]:{type:_.UnsignedInteger},[y.DocTypeReadVersion]:{type:_.UnsignedInteger},[y.Void]:{type:_.Binary},[y.Segment]:{type:_.Master},[y.SeekHead]:{type:_.Master},[y.Seek]:{type:_.Master},[y.SeekID]:{type:_.Binary},[y.SeekPosition]:{type:_.UnsignedInteger},[y.Info]:{type:_.Master},[y.TimestampScale]:{type:_.UnsignedInteger},[y.Duration]:{type:_.Float},[y.Tracks]:{type:_.Master},[y.Chapters]:{type:_.Master},[y.Cluster]:{type:_.Master},[y.Timestamp]:{type:_.UnsignedInteger},[y.SilentTracks]:{type:_.Master},[y.SilentTrackNumber]:{type:_.UnsignedInteger},[y.Position]:{type:_.UnsignedInteger},[y.PrevSize]:{type:_.UnsignedInteger},[y.SimpleBlock]:{type:_.Binary},[y.BlockGroup]:{type:_.Master},[y.EncryptedBlock]:{type:_.Binary},[y.Attachments]:{type:_.Master},[y.Tags]:{type:_.Master},[y.Cues]:{type:_.Master},[y.CuePoint]:{type:_.Master},[y.CueTime]:{type:_.UnsignedInteger},[y.CueTrackPositions]:{type:_.Master},[y.CueTrack]:{type:_.UnsignedInteger},[y.CueClusterPosition]:{type:_.UnsignedInteger},[y.CueRelativePosition]:{type:_.UnsignedInteger},[y.CueDuration]:{type:_.UnsignedInteger},[y.CueBlockNumber]:{type:_.UnsignedInteger},[y.CueCodecState]:{type:_.UnsignedInteger},[y.CueReference]:{type:_.Master},[y.CueRefTime]:{type:_.UnsignedInteger}},Ol=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 r=Zi(i,t),s=r in Vn,n=s?Vn[r].type:_.Binary,o=i.getUint8(t);let l=0;o&128?l=1:o&64?l=2:o&32?l=3:o&16?l=4:o&8?l=5:o&4?l=6:o&2?l=7:o&1&&(l=8);const d=new DataView(i.buffer,i.byteOffset+t+1,l-1),u=((o&255>>l)<<(l-1)*8)+Zi(d),c=t+l;let h;return c+u>i.byteLength?h=new DataView(i.buffer,i.byteOffset+c):h=new DataView(i.buffer,i.byteOffset+c,u),{tag:s?r:"0x"+r.toString(16).toUpperCase(),type:n,tagHeaderSize:c,tagSize:c+u,value:h,valueSize:u}},Zi=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint16(0)<<8|i.getUint8(2);case 4:return i.getUint32(0);case 5:return i.getUint32(0)<<8|i.getUint8(4);case 6:return i.getUint32(0)<<16|i.getUint16(4);case 7:return i.getUint32(0)<<32|i.getUint16(4)<<8|i.getUint8(6);case 8:return i.getUint32(0)<<32|i.getUint32(4)}return 0},Me=(i,e)=>{switch(e){case _.SignedInteger:return i.getInt8(0);case _.UnsignedInteger:return Zi(i);case _.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case _.String:return new TextDecoder("ascii").decode(i);case _.UTF8:return new TextDecoder("utf-8").decode(i);case _.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case _.Master:return i;case _.Binary:return i;default:a.assertNever(e)}},hi=(i,e)=>{let t=0;for(;t<i.byteLength;){const r=new DataView(i.buffer,i.byteOffset+t),s=Ol(r);if(!e(s))return;s.type===_.Master&&hi(s.value,e),t=s.value.byteOffset-i.byteOffset+s.valueSize}},pb=i=>{if(i.getUint32(0)!==y.EBML)return!1;let e,t,r;const s=Ol(i);return hi(s.value,({tag:n,type:o,value:l})=>(n===y.EBMLReadVersion?e=Me(l,o):n===y.DocType?t=Me(l,o):n===y.DocTypeReadVersion&&(r=Me(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)},Ll=[y.Info,y.SeekHead,y.Tracks,y.Chapters,y.Cluster,y.Cues,y.Attachments,y.Tags],mb=[y.Timestamp,y.SilentTracks,y.SilentTrackNumber,y.Position,y.PrevSize,y.SimpleBlock,y.BlockGroup,y.EncryptedBlock],vb=i=>{let e,t,r,s,n=!1,o=!1,l=!1,d,u;return hi(i,({tag:c,type:h,value:f,valueSize:p})=>{if(c===y.SeekID){const v=Me(f,h);u=Zi(v)}else c!==y.SeekPosition&&(u=void 0);return c===y.Segment?(e=f.byteOffset,t=f.byteOffset+p):c===y.Info?n=!0:c===y.SeekHead?o=!0:c===y.TimestampScale?r=Me(f,h):c===y.Duration?s=Me(f,h):c===y.SeekPosition&&u===y.Cues?d=Me(f,h):n&&o&&Ll.includes(c)&&(l=!0),!l}),a.assertNonNullable(e,"Failed to parse webm Segment start"),a.assertNonNullable(t,"Failed to parse webm Segment end"),a.assertNonNullable(s,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(s/1e9*r*1e3),cuesSeekPosition:d}},Sb=i=>{if(a.isNullable(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},bb=(i,e)=>{let t=!1,r=!1;const s=l=>a.isNonNullable(l.time)&&a.isNonNullable(l.position),n=[];let o;return hi(i,({tag:l,type:d,value:u})=>{switch(l){case y.Cues:t=!0;break;case y.CuePoint:o&&s(o)&&n.push(o),o={};break;case y.CueTime:o&&(o.time=Me(u,d));break;case y.CueTrackPositions:break;case y.CueClusterPosition:o&&(o.position=Me(u,d));break;default:t&&Ll.includes(l)&&(r=!0)}return!(t&&r)}),o&&s(o)&&n.push(o),n.map((l,d)=>{const{time:u,position:c}=l,h=n[d+1];return{status:G.NONE,time:{from:u,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},gb=i=>{let e=0,t=!1;try{hi(i,r=>r.tag===y.Cluster?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):mb.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||(t=[y.SimpleBlock,y.BlockGroup,y.EncryptedBlock].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},yb={validateData:pb,parseInit:vb,getIndexRange:Sb,parseSegments:bb,parseFeedableSegmentChunk:gb};class Fn{constructor(e,t,r,s,{fetcher:n,tuning:o,getCurrentPosition:l,compatibilityMode:d=!1}){switch(this.onLastSegment$=new a.ValueSubject(!1),this.fullyBuffered$=new a.ValueSubject(!1),this.playingRepresentation$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.gaps=[],this.subscription=new a.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new ot,this.destroyAbortController=new ot,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=a.abortable(this.destroyAbortController.signal,function(u){return Ee(this,arguments,function*(){const c=this.representations.get(u);a.assertNonNullable(c,`Cannot find representation ${u}`),this.playingRepresentationId=u,this.downloadingRepresentationId=u,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${c.mime}; codecs="${c.codecs}"`),this.sourceBufferTaskQueue=new ub(this.sourceBuffer),this.subscription.add(a.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>this.checkEjectedSegments(),v=>this.error$.next({id:"SegmentEjection",category:a.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:v}))),this.subscription.add(a.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:a.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(v=>{if(!this.sourceBuffer)return;const m=Math.min(this.bufferLimit,Mn(this.sourceBuffer.buffered));this.bufferLimit=m,this.pruneBuffer(v)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(v=>this.error$.next(v))),yield yield I(this.loadInit(c,"high",!0));const h=this.initData.get(c.id),f=this.segments.get(c.id);if(a.assertNonNullable(h,"No init buffer for starting representation"),a.assertNonNullable(f,"No segments for starting representation"),!(h instanceof ArrayBuffer))return yield I(void 0);let p=0;for(const v of f)v.time.from-p>0&&this.gaps.push({representation:c.id,from:p,to:v.time.from}),p=v.time.to;a.isNonNullable(c.duration)&&c.duration-p>0&&this.gaps.push({representation:c.id,from:p,to:c.duration}),yield yield I(this.sourceBufferTaskQueue.append(h,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId)})}.bind(this)),this.switchTo=a.abortable(this.destroyAbortController.signal,function(u){return Ee(this,arguments,function*(){if(u===this.downloadingRepresentationId||u===this.switchingToRepresentationId)return yield I(void 0);this.switchingToRepresentationId=u;const c=this.representations.get(u);a.assertNonNullable(c,`No such representation ${u}`);let h=this.initData.get(u);if(a.isNullable(h)?yield yield I(this.loadInit(c,"high",!1)):h instanceof Promise&&(yield yield I(h)),h=this.initData.get(u),!h||!(h instanceof ArrayBuffer)||!this.sourceBuffer)return yield I(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=u,this.abort(),yield yield I(this.sourceBufferTaskQueue.append(h,this.downloadAbortController.signal));const f=this.getCurrentPosition();a.isNonNullable(f)&&this.maintain(f)})}.bind(this)),this.fetcher=n,this.tuning=o,this.compatibilityMode=d,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=l,this.container=r,r){case Nt.MP4:this.containerParser=fb;break;case Nt.WEBM:this.containerParser=yb;break;default:a.assertNever(r)}this.initData=new Map(s.map(u=>[u.id,null])),this.segments=new Map,this.representations=new Map(s.map(u=>[u.id,u])),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 ot,this.abortBuffer()}maintain(e){if(a.isNullable(this.downloadingRepresentationId)||a.isNullable(this.playingRepresentationId)||a.isNullable(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(a.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;const s=r.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=wt(this.sourceBuffer.buffered,e),h=s?s.time.to+100:-1/0;s&&c>=s.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&Mn(this.sourceBuffer.buffered)>=this.bufferLimit*.8&&(this.pruneBuffer(1/0),s&&s.status!==G.NONE))return;let l=[];if(!this.activeSegments.size&&(l=this.selectForwardBufferSegments(r,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&s)if(l.includes(s))u="high";else{const c=xe(l,0);c&&c.time.from-s.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}!this.allInitsLoaded&&s&&s.status===G.FED&&!l.length&&wt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=xe(r,-1);d&&d.status===G.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===d))}findSegmentStartTime(e){var t,r,s;const n=(r=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&r!==void 0?r:this.playingRepresentationId;if(!n)return;const o=this.segments.get(n);if(!o)return;const l=o.find(d=>d.time.from<=e&&d.time.to>=e);return(s=l==null?void 0:l.time.from)!==null&&s!==void 0?s:void 0}setTarget(e){this.forwardBufferTarget=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,r){const s=e.findIndex(({status:d,time:{from:u,to:c}})=>d===G.NONE&&(u>r||u<=r&&c>=r)&&c<=r+this.forwardBufferTarget);if(s===-1)return[];if(t!==be.BYTE_RANGE)return e.slice(s,s+1);const n=e;let o=0;const l=[];for(let d=s;d<n.length&&o<=this.tuning.dash.segmentRequestSize;d++){const u=n[d];if(o+=u.byte.to+1-u.byte.from,u.status===G.NONE||u.status===G.PARTIALLY_EJECTED)l.push(u);else break}return l}loadSegments(e,t,r="auto"){return X(this,void 0,void 0,function*(){if(!e.length)return;let s,n,o=e;const{type:l}=t.segmentReference;switch(l){case be.BYTE_RANGE:{s=t.segmentReference.url,n={from:xe(e,0).byte.from,to:xe(e,-1).byte.to};break}case be.TEMPLATE:{const u=xe(e,0);s=new URL(u.url,t.segmentReference.baseUrl).toString(),o=[u];break}default:a.assertNever(l)}for(const u of o)u.status=G.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(yield a.abortable(d,function(){return Ee(this,arguments,function*(){const u=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield I(new Promise(c=>setTimeout(c,u)))})}.bind(this))(),d.aborted))for(const u of this.activeSegments)e.includes(u.segment)&&this.abortSegment(u.segment);return void this.fetcher.fetch(s,{range:n,onProgress:(u,c)=>{if(!d.aborted)try{this.onSomeDataLoaded(u,t.id,n?n.from:0,c,d)}catch(h){this.error$.next({id:"SegmentFeeding",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}},signal:d,priority:r}).then(()=>this.failedDownloads=0,u=>{for(const c of this.activeSegments)e.includes(c.segment)&&this.abortSegment(c.segment);this.onSegmentDownloadError(u)})})}onSegmentDownloadError(e){var t;let r=!1;const s=this.getCurrentPosition();this.sourceBuffer&&a.isNonNullable(s)&&(r=wt((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,s)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,r||this.error$.next({id:"SegmentDownload",category:a.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,r,s,n){if(!this.activeSegments.size)return;const o=h=>{this.abortSegment(h.segment)},l=h=>{var f;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),h.segment.status=G.FED,"size"in h.segment&&(h.segment.size=h.fedBytes);for(const p of this.representations.values())if(p.id!==t)for(const v of(f=this.segments.get(p.id))!==null&&f!==void 0?f:[])v.status===G.FED&&v.time.from===h.segment.time.from&&v.time.to===h.segment.time.to&&(v.status=G.NONE);this.activeSegments.delete(h),this.detectGapsWhenIdle(t,[h.segment])},d=this.representations.get(t);if(!d)return;const u=d.segmentReference.type,c=e.byteLength;for(const h of this.activeSegments){const{segment:f}=h,p=u===be.BYTE_RANGE,v=p?f.byte.to-f.byte.from+1:c;if(h.representationId!==t||!(!p||f.byte.from>=r&&f.byte.to<r+e.byteLength))continue;if(n.aborted){o(h);continue}const S=p?f.byte.from-r:0,b=p?f.byte.to-r:e.byteLength,g=S<s,k=b<=s;if(f.status===G.DOWNLOADING&&g&&k){f.status=G.DOWNLOADED,this.activeSegments.delete(h);const T=new DataView(e.buffer,e.byteOffset+S,v);this.sourceBufferTaskQueue.append(T,n).then(E=>E&&!n.aborted?l(h):o(h))}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&g&&(h.loadedBytes=Math.min(v,s-S),h.loadedBytes>h.feedingBytes)){const T=new DataView(e.buffer,e.byteOffset+S+h.feedingBytes,h.loadedBytes-h.feedingBytes),E=h.loadedBytes===v?T:this.containerParser.parseFeedableSegmentChunk(T);E!=null&&E.byteLength&&(f.status=G.PARTIALLY_FED,h.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,n).then(w=>{if(n.aborted)o(h);else if(w)h.fedBytes+=E.byteLength,h.fedBytes===v&&l(h);else{if(h.feedingBytes<v)return;o(h)}}))}}}abortSegment(e){e.status===G.PARTIALLY_FED||e.status===G.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=G.NONE),e.status=G.PARTIALLY_EJECTED):e.status=G.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[s,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const r=this.representations.get(e);r&&(this.initLoadIdleCallback=Bn(()=>dr(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return X(this,void 0,void 0,function*(){const s=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!r&&this.failedDownloads>0?a.abortable(this.destroyAbortController.signal,function(){return Ee(this,arguments,function*(){const l=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield I(new Promise(d=>setTimeout(d,l)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s)).then(l=>{if(!l)return;const{dataView:d,segments:u}=l,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c),this.segments.set(e.id,u)}).then(()=>this.failedDownloads=0,l=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:a.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o})}pruneBuffer(e){return X(this,void 0,void 0,function*(){const t=this.getCurrentPosition();if(!this.sourceBuffer||!this.playingRepresentationId||a.isNullable(t)||this.sourceBuffer.updating)return!1;const r=this.segments.get(this.playingRepresentationId);if(!r)return!1;let s=0,n=1/0,o=-1/0,l=!1;const d=u=>{var c;n=Math.min(n,u.time.from),o=Math.max(o,u.time.to);const h="size"in u?(c=u.size)!==null&&c!==void 0?c:0:u.byte.to-u.byte.from;s+=h};for(const u of r){if(u.time.to>=t||s>=e)break;u.status===G.FED&&d(u)}if(l=isFinite(n)&&isFinite(o),!l){s=0,n=1/0,o=-1/0;for(const u of r){if(u.time.from<t+this.forwardBufferTarget||s>e)break;u.status===G.FED&&d(u)}}if(l=isFinite(n)&&isFinite(o),!l)for(let u=0;u<this.sourceBuffer.buffered.length;u++){const c=this.sourceBuffer.buffered.start(u)*1e3,h=this.sourceBuffer.buffered.end(u)*1e3;for(const f of r)if(f.status===G.NONE&&Math.round(f.time.from)<=Math.round(c)&&Math.round(f.time.to)>=Math.round(h)){n=c,o=h;break}}return l=isFinite(n)&&isFinite(o),l?this.sourceBufferTaskQueue.remove(n,o):!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 r of t){let s={representation:e,from:r.time.from,to:r.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3;if(!(l<=r.time.from||o>=r.time.to)){if(o<=r.time.from&&l>=r.time.to){s=void 0;break}l>r.time.from&&l<r.time.to&&(s.from=l),o<r.time.to&&o>r.time.from&&(s.to=o)}}s&&s.to-s.from>=1&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Bn(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:a.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(a.isNullable(this.sourceBuffer)||a.isNullable(this.playingRepresentationId))return;const e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){const s=Math.round(this.sourceBuffer.buffered.start(r)*1e3),n=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:s,to:n})}const t=1;for(const r of this.segments.values())for(const s of r){const{status:n}=s;if(n!==G.FED&&n!==G.PARTIALLY_EJECTED)continue;const o=Math.floor(s.time.from),l=Math.ceil(s.time.to),d=e.some(c=>c.from-t<=o&&c.to+t>=l),u=e.some(c=>o>=c.from-t&&o<=c.to+t||l>=c.from-t&&l<=c.to+t);d||(u?s.status=G.PARTIALLY_EJECTED:s.status=G.NONE)}}}var Pt;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(Pt||(Pt={}));class Tb{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.abortAllController=new ot,this.subscription=new a.Subscription,this.fetchManifest=a.abortable(this.abortAllController.signal,function(s){return Ee(this,arguments,function*(){let n=s;this.requestQuic&&(n=It(n));const o=yield yield I(Rt(n,{signal:this.abortAllController.signal}).catch(Qt));return o?(this.onHeadersReceived(o.headers),yield I(o.text())):yield I(null)})}.bind(this)),this.fetch=a.abortable(this.abortAllController.signal,function(s,{rangeMethod:n=this.compatibilityMode?Pt.HEADER:Pt.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0}={}){var h,f,p,v;return Ee(this,arguments,function*(){let m=s;const S=new Headers;if(o)switch(n){case Pt.HEADER:{S.append("Range",`${o.from}-${o.to}`);break}case Pt.PARAM:{const $=new URL(m,location.href);$.searchParams.append("bytes",`${o.from}-${o.to}`),m=$.toString();break}default:a.assertNever(n)}this.requestQuic&&(m=It(m));let b=this.abortAllController.signal;if(u){const $=new ot;if(this.subscription.add(a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.fromEvent(u,"abort")).subscribe(()=>{try{$.abort()}catch(O){Qt(O)}})),this.abortAllController.signal.aborted||u.aborted)try{$.abort()}catch(O){Qt(O)}b=$.signal}const g=a.now(),k=yield yield I(Rt(m,{priority:d,headers:S,signal:b}).catch(Qt)),T=a.now();if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(T-g),!k)return yield I(null);if(!k.ok||!k.body)return yield I(Promise.reject(new Error(`Fetch error ${k.status}: ${k.statusText}`)));this.onHeadersReceived(k.headers);const E=parseInt((f=k.headers.get("Content-Length"))!==null&&f!==void 0?f:"",10)||o&&o.to-o.from+1||NaN;if(!E){const $=yield yield I(k.arrayBuffer());return(p=this.throughputEstimator)===null||p===void 0||p.addRawSpeed($.byteLength,a.now()-T),l==null||l(new DataView($),$.byteLength),yield I($)}if(!l&&!c)return yield I(k.arrayBuffer());const[w,x]=k.body.tee(),C=w.getReader();c&&((v=this.throughputEstimator)===null||v===void 0||v.trackStream(x));let R=0;const V=new ArrayBuffer(E),N=new Uint8Array(V),A=new DataView(V);let B=!1;const F=$=>{B=!0,Qt($)},Y=a.abortable(b,function({done:$,value:O}){return Ee(this,arguments,function*(){if(R===0&&this.lastRequestFirstBytes$.next(a.now()-g),b.aborted)return yield I(void 0);$?l==null||l(A,R):O&&(N.set(O,R),R+=O.byteLength,l==null||l(A,R),yield yield I(C==null?void 0:C.read().then(Y,F)))})}.bind(this));return yield yield I(C==null?void 0:C.read().then(Y,F)),yield I(B?null:V)})}.bind(this)),this.fetchByteRangeRepresentation=a.abortable(this.abortAllController.signal,function(s,n,o){return Ee(this,arguments,function*(){if(s.type!==be.BYTE_RANGE)return yield I(null);const{from:l,to:d}=s.initRange;let u=l,c=d,h=!1,f,p;s.indexRange&&(f=s.indexRange.from,p=s.indexRange.to,h=d+1===f,h&&(u=Math.min(f,l),c=Math.max(p,d))),u=Math.min(u,0);const v=yield yield I(this.fetch(s.url,{range:{from:u,to:c},priority:o,measureThroughput:!1}));if(!v)return yield I(null);const m=new DataView(v,l-u,d-u+1);if(!n.validateData(m))throw new Error("Invalid media file");const S=n.parseInit(m);let b;if(h&&f!==void 0&&p!==void 0)b=new DataView(v,f-u,p-f+1);else{const k=n.getIndexRange(S);if(k){const T=yield yield I(this.fetch(s.url,{range:k,priority:o,measureThroughput:!1}));if(!T)return yield I(null);b=new DataView(T)}}if(!b)throw new ReferenceError("No way to load representation index");const g=n.parseSegments(b,S);return yield I({dataView:new DataView(v),segments:g})})}.bind(this)),this.fetchTemplateRepresentation=a.abortable(this.abortAllController.signal,function(s,n){return Ee(this,arguments,function*(){if(s.type!==be.TEMPLATE)return yield I(null);const o=new URL(s.initUrl,s.baseUrl).toString(),l=yield yield I(this.fetch(o,{priority:n,measureThroughput:!1}));if(!l)return yield I(null);const d=s.segments.map(u=>Object.assign(Object.assign({},u),{status:G.NONE,size:void 0}));return yield I({segments:d,dataView:new DataView(l)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r}onHeadersReceived(e){const{type:t,reused:r}=Rl(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){var s,n;return X(this,void 0,void 0,function*(){const{type:o}=e;switch(o){case be.BYTE_RANGE:return(s=yield this.fetchByteRangeRepresentation(e,t,r))!==null&&s!==void 0?s:null;case be.TEMPLATE:return(n=yield this.fetchTemplateRepresentation(e,r))!==null&&n!==void 0?n:null;default:a.assertNever(o)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Qt=i=>{if(!(i instanceof DOMException)||!(i.name==="AbortError"||i.code===20))throw i},Un=i=>{if(!i.startsWith("P"))return;const e=(o,l)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*l},r=/^(-|\+)?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),s=(r==null?void 0:r[1])==="-"?-1:1,n={days:e(r==null?void 0:r[5],s),hours:e(r==null?void 0:r[6],s),minutes:e(r==null?void 0:r[7],s),seconds:e(r==null?void 0:r[8],s)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},Xr=(i,e)=>{let t=i;t=t.replaceAll("$$","$");const r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,n]of Object.entries(r)){const o=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(o,(l,d)=>a.isNullable(n)?l:a.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},Eb=(i,e)=>{var t,r,s,n,o,l,d,u,c,h,f,p,v,m,S,b,g,k,T,E,w,x,C,R,V,N,A,B,F,Y,$,O,Q,te,ie,ce,ke;const H=new DOMParser().parseFromString(i,"application/xml"),ae={video:[],audio:[],text:[]},ue=H.children[0],me=ue.getElementsByTagName("Period")[0],tt=me.children;let _e;const Ye=ue.getAttribute("mediaPresentationDuration"),it=me.getAttribute("duration");if(Ye)_e=Un(Ye);else if(it){const we=Un(it);a.isNonNullable(we)&&(_e=we)}let xt=0;const mt=(r=(t=ue.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&r!==void 0?r:[],Vl=mt.includes(Xi.WEBM_AS_IN_FFMPEG)||mt.includes(Xi.WEBM_AS_IN_SPEC)?Nt.WEBM:Nt.MP4;for(const we of tt){const fi=we.getAttribute("mimeType"),Fl=we.getAttribute("codecs"),oa=(s=we.getAttribute("contentType"))!==null&&s!==void 0?s:fi==null?void 0:fi.split("/")[0],Ul=(o=(n=we.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],jl=we.querySelectorAll("Representation"),Hl=we.querySelector("SegmentTemplate");if(oa!=="text")for(const ne of jl){const Bt=(l=ne.getAttribute("mimeType"))!==null&&l!==void 0?l:fi,la=(u=(d=ne.getAttribute("codecs"))!==null&&d!==void 0?d:Fl)!==null&&u!==void 0?u:"",pi=(h=(c=ne.getAttribute("contentType"))!==null&&c!==void 0?c:Bt==null?void 0:Bt.split("/")[0])!==null&&h!==void 0?h:oa,Gl=(p=(f=we.getAttribute("profiles"))===null||f===void 0?void 0:f.split(","))!==null&&p!==void 0?p:[],ql=parseInt((v=ne.getAttribute("width"))!==null&&v!==void 0?v:"",10),ua=parseInt((m=ne.getAttribute("height"))!==null&&m!==void 0?m:"",10),da=parseInt((S=ne.getAttribute("bandwidth"))!==null&&S!==void 0?S:"",10)/1e3,ca=(b=ne.getAttribute("frameRate"))!==null&&b!==void 0?b:"",Yl=(g=ne.getAttribute("quality"))!==null&&g!==void 0?g:void 0,zl=ca?aa(ca):void 0,Wl=(k=ne.getAttribute("id"))!==null&&k!==void 0?k:(xt++).toString(10),Ql=pi==="video"?`${ua}p`:pi==="audio"?`${da}Kbps`:la,Jl=`${Wl}@${Ql}`,Kl=(w=(E=(T=ne.querySelector("BaseURL"))===null||T===void 0?void 0:T.textContent)===null||E===void 0?void 0:E.trim())!==null&&w!==void 0?w:"",ha=new URL(Kl,e).toString(),Xl=[...mt,...Ul,...Gl];let fr;const Zl=ne.querySelector("SegmentBase"),rt=(x=ne.querySelector("SegmentTemplate"))!==null&&x!==void 0?x:Hl;if(Zl){const Mt=(R=(C=ne.querySelector("SegmentBase Initialization"))===null||C===void 0?void 0:C.getAttribute("range"))!==null&&R!==void 0?R:"",[Vt,mr]=Mt.split("-").map(st=>parseInt(st,10)),Ft={from:Vt,to:mr},Ut=(V=ne.querySelector("SegmentBase"))===null||V===void 0?void 0:V.getAttribute("indexRange"),[vr,mi]=Ut?Ut.split("-").map(st=>parseInt(st,10)):[],jt=Ut?{from:vr,to:mi}:void 0;fr={type:be.BYTE_RANGE,url:ha,initRange:Ft,indexRange:jt}}else if(rt){const Mt={representationId:(N=ne.getAttribute("id"))!==null&&N!==void 0?N:void 0,bandwidth:(A=ne.getAttribute("bandwidth"))!==null&&A!==void 0?A:void 0},Vt=parseInt((B=rt.getAttribute("timescale"))!==null&&B!==void 0?B:"",10),mr=(F=rt.getAttribute("initialization"))!==null&&F!==void 0?F:"",Ft=rt.getAttribute("media"),Ut=($=parseInt((Y=rt.getAttribute("startNumber"))!==null&&Y!==void 0?Y:"",10))!==null&&$!==void 0?$:1,vr=Xr(mr,Mt);if(!Ft)throw new ReferenceError("No media attribute in SegmentTemplate");const mi=(O=rt.querySelectorAll("SegmentTimeline S"))!==null&&O!==void 0?O:[],jt=[];if(mi.length){let st=Ut,at=0;for(const Ht of mi){const vt=parseInt((Q=Ht.getAttribute("d"))!==null&&Q!==void 0?Q:"",10)*1e3,Gt=parseInt((te=Ht.getAttribute("r"))!==null&&te!==void 0?te:"",10)||0,qt=(ce=parseInt((ie=Ht.getAttribute("t"))!==null&&ie!==void 0?ie:"",10))!==null&&ce!==void 0?ce:void 0;for(let fa=0;fa<Gt+1;fa++){const eu=Xr(Ft,Object.assign(Object.assign({},Mt),{segmentNumber:st.toString(10),segmentTime:qt.toString(10)})),tu=qt?qt/Vt:at;at+=vt/Vt;const iu=at;st++,jt.push({time:{from:tu,to:iu},url:eu})}}}else if(a.isNonNullable(_e)){const at=parseInt((ke=rt.getAttribute("duration"))!==null&&ke!==void 0?ke:"",10)/Vt*1e3,Ht=Math.ceil(_e/at);let vt=0;for(let Gt=1;Gt<Ht;Gt++){const qt=Xr(Ft,Object.assign(Object.assign({},Mt),{segmentNumber:Gt.toString(10),segmentTime:vt.toString(10)}));jt.push({time:{from:vt,to:vt+at},url:qt}),vt+=at}}fr={type:be.TEMPLATE,baseUrl:ha,initUrl:vr,segments:jt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!pi||!Bt)continue;const pr={video:Se.VIDEO,audio:Se.AUDIO,text:Se.TEXT}[pi];pr&&ae[pr].push({id:Jl,kind:pr,segmentReference:fr,profiles:Xl,duration:_e,bitrate:da,mime:Bt,codecs:la,width:ql,height:ua,fps:zl,quality:Yl})}}return{duration:_e,container:Vl,representations:ae}},$b=["timeupdate","progress","play","seeked","stalled"];var ve;(function(i){i.NONE="none",i.MANIFEST_LOADED="manifest_loaded",i.REPRESENTATION_SELECTED="representation_selected"})(ve||(ve={}));let Pb=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new a.Subscription,this.state$=new K(ve.NONE),this.currentVideoRepresentation$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.forceEnded$=new a.Subject,this.gapWatchdogStarted=!1,this.destroyController=new ot,this.initManifest=a.abortable(this.destroyController.signal,function(t,r){return Ee(this,arguments,function*(){this.element=t,this.state$.startTransitionTo(ve.MANIFEST_LOADED);const s=yield yield I(this.fetcher.fetchManifest(r).catch(l=>this.error$.next({id:"LoadManifest",category:a.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:l})));if(!s)return yield I(null);let n;try{n=Eb(s!=null?s:"",r)}catch(l){this.error$.next({id:"ManifestParsing",category:a.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:l})}if(!n)return yield I(null);const o=({mime:l,codecs:d})=>{var u,c,h;return Boolean(((u=t.canPlayType)===null||u===void 0?void 0:u.call(t,l))&&((h=(c=window.MediaSource)===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0?void 0:h.call(c,`${l}; codecs="${d}"`)))};return this.manifest=Object.assign(Object.assign({},n),{representations:oi(Object.entries(n.representations).map(([l,d])=>[l,d.filter(o)]))}),this.manifest.representations.video.length?this.state$.setState(ve.MANIFEST_LOADED):this.error$.next({id:"NoRepresentations",category:a.ErrorCategory.PARSER,message:"No playable video representations"}),yield I(this.manifest)})}.bind(this)),this.initRepresentations=a.abortable(this.destroyController.signal,function(t,r){return Ee(this,arguments,function*(){a.assertNonNullable(this.manifest),a.assertNonNullable(this.element),this.state$.startTransitionTo(ve.REPRESENTATION_SELECTED),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0};this.videoBufferManager=new Fn(Se.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(r)&&(this.audioBufferManager=new Fn(Se.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,s),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 n=a.merge(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(a.map(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),o=a.merge(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(a.map(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.subscription.add(a.merge(this.forceEnded$,a.combine({allBuffersFull:n,someBufferEnded:o}).pipe(a.filter(({allBuffersFull:l,someBufferEnded:d})=>l&&d))).subscribe(()=>{var l;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{(l=this.source)===null||l===void 0||l.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.subscription.add(a.merge(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.source.readyState!=="open"&&(yield yield I(new Promise(l=>{var d;return(d=this.source)===null||d===void 0?void 0:d.addEventListener("sourceopen",l)}))),a.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&a.isNonNullable(r)?yield yield I(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(r)])):yield yield I(this.videoBufferManager.startWith(t)),this.state$.setState(ve.REPRESENTATION_SELECTED),a.assertNonNullable(this.element),this.subscription.add(a.merge(...$b.map(l=>a.fromEvent(this.element,l)),a.fromEvent(window,"online")).subscribe(this.tick,l=>{this.error$.next({id:"DashVKPlayer",category:a.ErrorCategory.WTF,message:"Internal logic error",thrown:l})})),this.subscription.add(a.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(a.fromEvent(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&xn(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()})}.bind(this)),this.tick=()=>{var t,r;if(!this.element||!this.videoBufferManager)return;const s=this.element.currentTime*1e3;this.videoBufferManager.maintain(s),(t=this.audioBufferManager)===null||t===void 0||t.maintain(s),(this.videoBufferManager.gaps.length||!((r=this.audioBufferManager)===null||r===void 0)&&r.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=a.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),n=>{this.error$.next({id:"GapWatchdog",category:a.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Tb({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}switchRepresentation(e,t){return X(this,void 0,void 0,function*(){const r={[Se.VIDEO]:this.videoBufferManager,[Se.AUDIO]:this.audioBufferManager,[Se.TEXT]:null}[e];return r==null?void 0:r.switchTo(t)})}seek(e,t){var r,s,n,o,l;a.assertNonNullable(this.element),a.assertNonNullable(this.videoBufferManager);let d;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?d=e:d=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!==null&&r!==void 0?r:e,(n=(s=this.audioBufferManager)===null||s===void 0?void 0:s.findSegmentStartTime(e))!==null&&n!==void 0?n:e),xn(this.element.buffered,d)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)===null||o===void 0||o.abort()),this.videoBufferManager.maintain(d),(l=this.audioBufferManager)===null||l===void 0||l.maintain(d),this.element.currentTime=d/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(ve.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}destroy(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3,t=[];for(const r of this.bufferManagers)for(const s of r.gaps)r.playingRepresentation$.getValue()===s.representation&&s.from<=e&&s.to>e&&(this.element.duration*1e3-s.to<this.tuning.endGapTolerance?t.push(1/0):t.push(s.to));if(t.length){const r=Math.max(...t);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=r/1e3}}};var Z;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(Z||(Z={}));const kb=({id:i,width:e,height:t,bitrate:r,fps:s,quality:n})=>{var o;const l=(o=n?ci(n):void 0)!==null&&o!==void 0?o:ft({width:e,height:t});return l&&{id:i,quality:l,bitrate:r,size:{width:e,height:t},fps:s}},_b=(i,e,t)=>{var r;const s=e.indexOf(t);return(r=xe(i,Math.round(i.length*s/e.length)))!==null&&r!==void 0?r:xe(i,-1)};class wb{constructor(e){this.subscription=new a.Subscription,this.videoState=new K(Z.STOPPED),this.elementSize$=new a.ValueSubject(void 0),this.textTracksManager=new Oe,this.videoTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new xS,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(n.state===D.Requested&&(s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&t!==Z.STOPPED&&r!==exports.PlaybackState.STOPPED&&this.seek(n.position,n.forcePrecise),r===exports.PlaybackState.STOPPED){t!==Z.STOPPED&&(this.videoState.startTransitionTo(Z.STOPPED),this.player.stop(),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Z.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(t===Z.STOPPED){this.videoState.startTransitionTo(Z.READY),this.prepare();return}switch(t){case Z.READY:r===exports.PlaybackState.PAUSED?(this.videoState.setState(Z.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed());return;case Z.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Z.PAUSED),this.video.pause()):(s==null?void 0:s.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Z.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}}},this.params=e,this.video=Ge(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Pb({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,r=qe(this.video),s=d=>{e.error$.next({id:"DashVKProvider",category:a.ErrorCategory.WTF,message:"DashVKProvider internal logic error",thrown:d})},n=(d,u)=>this.subscription.add(d.subscribe(u,s));n(r.timeUpdate$,e.position$),n(r.durationChange$,e.duration$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.lastRequestFirstBytes$.pipe(a.filter(a.isNonNullable),a.once(),a.mapTo(void 0)),e.firstBytesEvent$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(pt(this.video,t.isLooped,s)),this.subscription.add(He(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Ze(this.video,t.playbackRate,r.playbackRateState$,s)),n(Ji(this.video),this.elementSize$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(Z.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(Z.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(r.canplay$.subscribe(()=>{this.videoState.getState()===Z.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(a.filter(({to:d})=>d===ve.REPRESENTATION_SELECTED)).subscribe(()=>{this.videoState.setState(Z.READY)}));const o=d=>e.error$.next({id:"RepresentationSwitch",category:a.ErrorCategory.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(a.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,a.fromEvent(this.video,"progress")).subscribe(()=>{var d,u,c,h,f,p,v,m;const S=this.player.state$.getState(),b=this.player.state$.getTransition();if(S===ve.NONE||!this.videoTracks.length)return;const g=S===ve.MANIFEST_LOADED&&!b,k=S===ve.REPRESENTATION_SELECTED&&!b,T=t.autoVideoTrackSwitching.getState(),E=t.videoTrack.getState(),w=(d=this.videoTracks.find(({track:{id:F}})=>F===E))===null||d===void 0?void 0:d.track,x=e.currentVideoTrack$.getValue(),C=wt(this.video.buffered,this.video.currentTime*1e3),R=T?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,V=Math.min(C/Math.min(R,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),N=Math.max(w&&!T&&(c=(u=this.audioRepresentations.get(w.id))===null||u===void 0?void 0:u.bitrate)!==null&&c!==void 0?c:0,x&&(f=(h=this.audioRepresentations.get(x.id))===null||h===void 0?void 0:h.bitrate)!==null&&f!==void 0?f:0),A=di(this.videoTracks.map(({track:F})=>F),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),reserve:N,forwardBufferHealth:V,current:x,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),B=T?A!=null?A:w:w!=null?w:A;if(t.autoVideoTrackSwitching.getTransition()&&(t.autoVideoTrackSwitching.setState(T),this.player.setBufferTarget(R)),g){const F=B&&((p=this.videoTracks.find(({track:Y})=>Y===B))===null||p===void 0?void 0:p.representation);a.assertNonNullable(F),this.player.initRepresentations(F.id,(v=this.audioRepresentations.get(F.id))===null||v===void 0?void 0:v.id)}else if(k){const F=B&&((m=this.videoTracks.find(({track:Y})=>Y===B))===null||m===void 0?void 0:m.representation);if(F){const Y=this.audioRepresentations.get(F.id);this.player.switchRepresentation(Se.VIDEO,F.id).catch(o),Y&&this.player.switchRepresentation(Se.AUDIO,Y.id).catch(o)}}},s)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(a.filterChanged(),a.map(d=>{var u;return d&&((u=this.videoTracks.find(({representation:{id:c}})=>c===d))===null||u===void 0?void 0:u.track)})).subscribe(e.currentVideoTrack$,s)),this.textTracksManager.connect(this.video,t,e);const l=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(l.subscribe(this.syncPlayback,s))}prepare(){return X(this,void 0,void 0,function*(){const e=yield this.player.initManifest(this.video,this.params.source.url);if(!e)return;this.videoTracks=[];const t=Array.from(e.representations.audio).sort((s,n)=>n.bitrate-s.bitrate),r=Array.from(e.representations.video).sort((s,n)=>n.bitrate-s.bitrate);for(const s of r){const n=kb(s);if(n){this.videoTracks.push({track:n,representation:s});const o=_b(t,r,s);o&&this.audioRepresentations.set(s.id,o)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:s})=>s))})}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){et(this.video).then(e=>{e||(this.videoState.setState(Z.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}}const Ab=5e3,Le={};var q;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(q||(q={}));const Ci=(i,e)=>new a.Observable(t=>{const r=(s,n)=>t.next(n);return i.on(e,r),()=>i.off(e,r)});class Rb{constructor(e){this.subscription=new a.Subscription,this.videoState=new K(q.INITIALIZING),this.textTracksManager=new Oe,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(t!==q.INITIALIZING)switch((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===D.Requested&&this.seek(n.position),r){case exports.PlaybackState.STOPPED:switch(t){case q.STOPPED:break;case q.READY:case q.PLAYING:case q.PAUSED:this.stop();break;default:a.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case q.PLAYING:break;case q.STOPPED:this.prepare();break;case q.READY:case q.PAUSED:this.playIfAllowed();break;default:a.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case q.PAUSED:break;case q.STOPPED:this.prepare();break;case q.READY:this.videoState.setState(q.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case q.PLAYING:this.pause();break;default:a.assertNever(t)}break;default:a.assertNever(r)}},this.video=Ge(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(de(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)===null||e===void 0||e.detachMedia(),(t=this.hls)===null||t===void 0||t.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:a.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:s}),e=!0},r=window.setTimeout(()=>t("timeout"),Ab);dr(import("hls.js").then(s=>{e||(Le.Hls=s.default,Le.Events=s.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){a.assertNonNullable(Le.Hls,"hls.js not loaded"),this.hls=new Le.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(q.STOPPED)}subscribe(){a.assertNonNullable(Le.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:a.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},s=qe(this.video),n=(u,c)=>this.subscription.add(u.subscribe(c,r));n(s.timeUpdate$,t.position$),n(s.durationChange$,t.duration$),n(s.ended$,t.endedEvent$),n(s.looped$,t.loopedEvent$),n(s.error$,t.error$),n(s.isBuffering$,t.isBuffering$),n(s.currentBuffer$,t.currentBuffer$),n(s.loadStart$,t.firstBytesEvent$),n(s.playing$,t.firstFrameEvent$),n(s.canplay$,t.canplay$),n(s.seeked$,t.seekedEvent$),this.subscription.add(pt(this.video,e.isLooped,r)),this.subscription.add(He(this.video,e.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ze(this.video,e.playbackRate,s.playbackRateState$,r)),this.subscription.add(Ci(this.hls,Le.Events.ERROR).subscribe(u=>{var c;u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:a.ErrorCategory.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${(c=u.err)===null||c===void 0?void 0:c.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(q.PLAYING),P(e.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(q.PAUSED),P(e.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===q.READY&&this.videoState.setState(q.READY),this.videoState.getState()===q.PLAYING&&this.playIfAllowed()},r)),n(Ci(this.hls,Le.Events.MANIFEST_PARSED).pipe(a.map(({levels:u})=>u.reduce((c,h)=>{var f,p;const v=h.name||h.height.toString(10),{width:m,height:S}=h,b=(p=ci((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&p!==void 0?p:ft({width:m,height:S});if(!b)return c;const g=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,k={id:v.toString(),quality:b,bitrate:h.bitrate/1e3,size:{width:m,height:S},fps:g};return this.trackLevels.set(v,{track:k,level:h}),c.push(k),c},[]))),t.availableVideoTracks$),n(Ci(this.hls,Le.Events.LEVEL_LOADING).pipe(a.map(({url:u})=>de(u))),t.hostname$),this.subscription.add(Ne(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:r}));const o=u=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:h})=>h===u))===null||c===void 0?void 0:c.track},l=Ci(this.hls,Le.Events.LEVEL_SWITCHED).pipe(a.map(({level:u})=>o(this.hls.levels[u])));l.pipe(a.filter(a.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Ne(e.videoTrack,()=>{var u;return(u=o(this.hls.levels[this.hls.currentLevel]))===null||u===void 0?void 0:u.id},u=>{var c;if(a.isNullable(u))return;const h=(c=this.trackLevels.get(u))===null||c===void 0?void 0:c.level;if(!h)return;const f=this.hls.levels.indexOf(h),p=this.hls.currentLevel,v=this.hls.levels[p];!v||h.bitrate>v.bitrate?this.hls.nextLevel=f:(this.hls.loadLevel=f,this.hls.loadLevel=f)},{changed$:l.pipe(a.map(u=>u==null?void 0:u.id)),onError:r})),n(s.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=a.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo(q.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return X(this,void 0,void 0,function*(){this.videoState.startTransitionTo(q.PLAYING),(yield et(this.video))||(this.videoState.setState(q.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(q.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.setAttribute("src",""),this.video.load(),this.videoState.setState(q.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const jn="X-Playback-Duration";var Hn=i=>X(void 0,void 0,void 0,function*(){const e=yield Rt(i,{method:"HEAD"});return e.headers.has(jn)?parseInt(e.headers.get(jn),10):void 0});const Ib=i=>{let e=null;if(i.QUALITY&&(e=ci(i.QUALITY)),!e&&i.RESOLUTION){const[t,r]=i.RESOLUTION.split("x").map(s=>parseInt(s,10));e=ft({width:t,height:r})}return e!=null?e:null},xl=(i,e=i)=>X(void 0,void 0,void 0,function*(){var t;const n=(yield(yield Rt(i)).text()).split(`
|
|
8
|
-
`),o=[];for(let l=0;l<n.length;l++){const u=n[l].match(/^#EXT-X-STREAM-INF:(.+)/);if(!u)continue;const c=oi(u[1].split(",").map(b=>b.split("="))),h=(t=c.QUALITY)!==null&&t!==void 0?t:`stream-${c.BANDWIDTH}`,f=Ib(c);let p;c.BANDWIDTH&&(p=parseInt(c.BANDWIDTH,10)/1e3||void 0),!p&&c["AVERAGE-BANDWIDTH"]&&(p=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const v=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0;let m;if(c.RESOLUTION){const[b,g]=c.RESOLUTION.split("x").map(k=>parseInt(k,10));b&&g&&(m={width:b,height:g})}const S=new URL(n[++l],e).toString();f&&o.push({id:h,quality:f,url:S,bandwidth:p,size:m,fps:v})}return o});var z;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(z||(z={}));class Nb{constructor(e){var t;this.subscription=new a.Subscription,this.videoState=new K(z.STOPPED),this.textTracksManager=new Oe,this.manifests$=new a.ValueSubject([]),this.liveOffset=new sa,this.manifestStartTime$=new a.ValueSubject(void 0),this.syncPlayback=()=>{const s=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(n===exports.PlaybackState.STOPPED){s!==z.STOPPED&&(this.videoState.startTransitionTo(z.STOPPED),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(z.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(s===z.STOPPED){this.videoState.startTransitionTo(z.READY),this.prepare();return}if(l||d){const h=this.videoState.getState();this.videoState.setState(z.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),c.state===D.None&&this.params.desiredState.seekState.setState({state:D.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&c.state===D.Requested){this.videoState.startTransitionTo(z.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(s){case z.READY:n===exports.PlaybackState.PAUSED?(this.videoState.setState(z.PAUSED),this.liveOffset.pause(),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):n===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed());return;case z.PLAYING:n===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(z.PAUSED),this.liveOffset.pause(),this.video.pause()):(o==null?void 0:o.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case z.PAUSED:n===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(z.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())):(o==null?void 0:o.to)===exports.PlaybackState.PAUSED&&(P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case z.CHANGING_MANIFEST:break;default:return a.assertNever(s)}},this.params=e,this.video=Ge(e.container),this.params.output.element$.next(this.video);const r={id:"master",quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([r]),xl(At(this.params.source.url),this.params.source.url).then(s=>{this.manifests$.next([r,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.maxSeekBackTime$=new a.ValueSubject((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:r,videoTrack:s}=this.params.desiredState,n=r.getState(),o=s.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:s.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d)return;const u=n?"master":l;return n&&!o&&s.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,r=l=>{e.error$.next({id:"HlsLiveProvider",category:a.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:l})},s=qe(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,r));n(s.ended$,e.endedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(He(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ze(this.video,t.playbackRate,s.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(z.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===z.READY&&this.videoState.setState(z.READY),this.videoState.getState()===z.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(l=>-l/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(s.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&a.isNonNullable(u.to)){const h=u.to;this.params.desiredState.videoTrack.setState(h);const f=this.manifests$.getValue().find(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(de(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===z.CHANGING_MANIFEST&&this.videoState.setState(d.to),l&&l.state===D.Requested&&this.seek(l.position)},r)),this.subscription.add(s.loadedData$.subscribe(()=>{var l,d,u;const c=(u=(d=(l=this.video)===null||l===void 0?void 0:l.getStartDate)===null||d===void 0?void 0:d.call(l))===null||u===void 0?void 0:u.getTime();this.manifestStartTime$.next(c||void 0)},r)),this.subscription.add(a.combine({startTime:this.manifestStartTime$.pipe(a.filter(a.isNonNullable)),currentTime:s.timeUpdate$}).subscribe(({startTime:l,currentTime:d})=>this.params.output.liveTime$.next(l+d*1e3),r)),this.subscription.add(this.manifests$.pipe(a.map(l=>l.map(({id:d,quality:u,size:c,bandwidth:h,fps:f})=>({id:d,quality:u,size:c,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,r));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();if(a.isNullable(e))return;const t=At(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),Hn(t).then(r=>{var s;if(!a.isNullable(r))this.maxSeekBackTime$.next(r);else{const n=(s=this.params.source.maxSeekBackTime)!==null&&s!==void 0?s:this.maxSeekBackTime$.getValue();if(a.isNullable(n)||!isFinite(n))try{Rt(t).then(o=>o.text()).then(o=>{var l;const d=(l=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(o))===null||l===void 0?void 0:l[1];if(d){const u=new URL(d,t).toString();Hn(u).then(c=>{a.isNullable(c)||this.maxSeekBackTime$.next(c)})}})}catch(o){}}})}playIfAllowed(){et(this.video).then(e=>{e||(this.videoState.setState(z.PAUSED),this.liveOffset.pause(),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next();const t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}}var J;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(J||(J={}));class Cb{constructor(e){this.subscription=new a.Subscription,this.videoState=new K(J.STOPPED),this.textTracksManager=new Oe,this.manifests$=new a.ValueSubject([]),this.syncPlayback=()=>{const r=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s===exports.PlaybackState.STOPPED){r!==J.STOPPED&&(this.videoState.startTransitionTo(J.STOPPED),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(J.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.seekState.getState();if(r===J.STOPPED){this.videoState.startTransitionTo(J.READY),this.prepare();return}if(o||l){const c=this.videoState.getState();this.videoState.setState(J.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),u.state===D.None&&this.params.desiredState.seekState.setState({state:D.Requested,position:h*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&u.state===D.Requested&&this.seek(u.position),r){case J.READY:s===exports.PlaybackState.PAUSED?(this.videoState.setState(J.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed());return;case J.PLAYING:s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(J.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case J.PAUSED:s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case J.CHANGING_MANIFEST:break;default:return a.assertNever(r)}},this.params=e,this.video=Ge(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([t]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(de(this.params.source.url)),xl(this.params.source.url).then(r=>{this.manifests$.next([t,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:r,videoTrack:s}=this.params.desiredState,n=r.getState(),o=s.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:s.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d)return;const u=n?"master":l;return n&&!o&&s.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,r=l=>{e.error$.next({id:"HlsProvider",category:a.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:l})},s=qe(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d));n(s.timeUpdate$,e.position$),n(s.durationChange$,e.duration$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.seeked$,e.seekedEvent$),this.subscription.add(pt(this.video,t.isLooped,r)),this.subscription.add(He(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ze(this.video,t.playbackRate,s.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(J.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===J.READY&&this.videoState.setState(J.READY),this.videoState.getState()===J.PLAYING&&this.playIfAllowed()},r).add(s.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&a.isNonNullable(u.to)){const h=u.to;this.params.desiredState.videoTrack.setState(h);const f=this.manifests$.getValue().find(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(de(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===J.CHANGING_MANIFEST&&this.videoState.setState(d.to),l.state===D.Requested&&this.seek(l.position)},r))),this.subscription.add(this.manifests$.pipe(a.map(l=>l.map(({id:d,quality:u,size:c,bandwidth:h,fps:f})=>({id:d,quality:u,size:c,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,r));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();a.isNullable(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){et(this.video).then(e=>{e||(this.videoState.setState(J.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var ee;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(ee||(ee={}));class Db{constructor(e){this.subscription=new a.Subscription,this.videoState=new K(ee.STOPPED),this.trackUrls={},this.textTracksManager=new Oe,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(r===exports.PlaybackState.STOPPED){t!==ee.STOPPED&&(this.videoState.startTransitionTo(ee.STOPPED),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ee.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.seekState.getState();if(t===ee.STOPPED){this.videoState.startTransitionTo(ee.READY),this.prepare();return}if(o){const{currentTime:d}=this.video;this.prepare(),l.state===D.None&&this.params.desiredState.seekState.setState({state:D.Requested,position:d*1e3,forcePrecise:!0});return}switch((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&l.state===D.Requested&&this.seek(l.position),t){case ee.READY:r===exports.PlaybackState.PAUSED?(this.videoState.setState(ee.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed());return;case ee.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(ee.PAUSED),this.video.pause()):(s==null?void 0:s.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case ee.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.params=e,this.video=Ge(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach(([t,r],s)=>{const n=s.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:r}}),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.isLive$.next(!1),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,r=l=>{e.error$.next({id:"MpegProvider",category:a.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:l})},s=qe(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,r));n(s.timeUpdate$,e.position$),n(s.durationChange$,e.duration$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.seeked$,e.seekedEvent$),this.subscription.add(pt(this.video,t.isLooped,r)),this.subscription.add(He(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ze(this.video,t.playbackRate,s.playbackRateState$,r)),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(ee.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(ee.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===ee.READY&&this.videoState.setState(ee.READY);const d=this.params.desiredState.videoTrack.getTransition();d&&a.isNonNullable(d.to)&&(this.params.desiredState.videoTrack.setState(d.to),this.params.output.currentVideoTrack$.next(this.trackUrls[d.to].track)),this.videoState.getState()===ee.PLAYING&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);const o=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){var e,t;const r=(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();a.assertNonNullable(r,"MpegProvider: track is not selected");let{url:s}=this.trackUrls[r];a.assertNonNullable(s,`MpegProvider: No url for ${r}`),this.params.tuning.requestQuick&&(s=It(s)),this.video.setAttribute("src",s),this.video.load(),this.params.output.hostname$.next(de(s))}playIfAllowed(){et(this.video).then(e=>{e||(this.videoState.setState(ee.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}const Gn=["stun:videostun.mycdn.me:80"],Ob=1e3,Lb=3,Zr=()=>null;class xb{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=Zr,this.externalStopCallback=Zr,this.externalErrorCallback=Zr,this.options=this.normalizeOptions(t);const r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.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 X(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 X(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:Gn}]};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 X(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 X(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:a.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return X(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 X(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),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))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),Ob)}normalizeOptions(e={}){const t={stunServerList:Gn,maxRetryNumber:Lb,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var W;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(W||(W={}));class Bb{constructor(e){this.videoState=new K(W.STOPPED),this.maxSeekBackTime$=new a.ValueSubject(0),this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(r===exports.PlaybackState.STOPPED){t!==W.STOPPED&&(this.videoState.startTransitionTo(W.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(W.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition();if(t===W.STOPPED){this.videoState.startTransitionTo(W.READY),this.prepare();return}if(o){this.prepare();return}switch(t){case W.READY:r===exports.PlaybackState.PAUSED?(this.videoState.setState(W.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed());return;case W.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(W.PAUSED),this.video.pause()):(s==null?void 0:s.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case W.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ge(e.container),this.liveStreamClient=new xb(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.video.remove(),this.params.output.element$.next(void 0),this.liveStreamClient.disconnect()}subscribe(){const{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"WebRTCLiveProvider",category:a.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:l})=>{this.log({message:`[videoState change] ${l}: ${JSON.stringify(o)}`})});const s=qe(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,r));n(s.timeUpdate$,e.liveTime$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),this.subscription.add(s.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(s.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===W.READY&&this.videoState.setState(W.READY)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED)},r)).add(s.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING)},r)).add(s.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(He(this.video,t.volume,s.volumeState$,r)).add(s.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case W.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case W.READY:break;case W.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case W.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(o.to)}},r)).add(a.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}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(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:exports.VideoQuality.INVARIANT}),this.video.srcObject=e,P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(W.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:a.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){et(this.video).then(e=>{e||(this.videoState.setState(W.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}prepare(){this.liveStreamClient.connect()}}class qn{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 Mb=()=>{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")},es,ts,is,rs,ss,as,Di,ns,Oi,os,Li,ls,xi,us,Bi,ds;const Bl=Mb(),We=document.createElement("video"),ze={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&((ts=(es=window.SourceBuffer)===null||es===void 0?void 0:es.prototype)===null||ts===void 0?void 0:ts.appendBuffer)),hls:Boolean(((is=We.canPlayType)===null||is===void 0?void 0:is.call(We,"application/x-mpegurl"))||((rs=We.canPlayType)===null||rs===void 0?void 0:rs.call(We,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection)},Re={mp4:Boolean((ss=We.canPlayType)===null||ss===void 0?void 0:ss.call(We,"video/mp4")),webm:Boolean((as=We.canPlayType)===null||as===void 0?void 0:as.call(We,"video/webm"))},Qe={h264:Boolean((ns=(Di=window.MediaSource)===null||Di===void 0?void 0:Di.isTypeSupported)===null||ns===void 0?void 0:ns.call(Di,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean((os=(Oi=window.MediaSource)===null||Oi===void 0?void 0:Oi.isTypeSupported)===null||os===void 0?void 0:os.call(Oi,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean((ls=(Li=window.MediaSource)===null||Li===void 0?void 0:Li.isTypeSupported)===null||ls===void 0?void 0:ls.call(Li,'video/webm; codecs="vp9"')),aac:Boolean((us=(xi=window.MediaSource)===null||xi===void 0?void 0:xi.isTypeSupported)===null||us===void 0?void 0:us.call(xi,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean((ds=(Bi=window.MediaSource)===null||Bi===void 0?void 0:Bi.isTypeSupported)===null||ds===void 0?void 0:ds.call(Bi,'audio/webm; codecs="opus"'))},Jt=(Qe.h264||Qe.h265)&&Qe.aac,hr=ze.hls&&Re.mp4,Vb=Boolean(window.WebSocket),Fb=()=>Object.keys(Qe).filter(i=>Qe[i]),Ub=(i,e=!1)=>i.filter(t=>{switch(t){case exports.VideoFormat.DASH:return ze.mse&&Re.mp4&&Jt;case exports.VideoFormat.DASH_SEP:return ze.mse&&Re.mp4&&Jt;case exports.VideoFormat.DASH_WEBM:return ze.mse&&Re.webm&&Qe.vp9&&Qe.opus;case exports.VideoFormat.DASH_LIVE:return ze.mse&&Re.mp4&&Jt;case exports.VideoFormat.DASH_ONDEMAND:return ze.mse&&Re.mp4&&Jt;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_ONDEMAND:return hr||e&&ze.mse&&Re.mp4&&Jt;case exports.VideoFormat.MPEG:return Re.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return ze.webrtc&&Vb&&Qe.h264&&(Re.mp4||Re.webm);default:return a.assertNever(t)}}),jb=()=>Bl?[exports.VideoFormat.MPEG,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND]:hr?[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG],Hb=()=>Bl?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE]:hr?[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.DASH_LIVE]:[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.HLS_LIVE],Yn=i=>i?[exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var Gb=i=>new a.Observable(e=>{const t=new a.Subscription,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(a.map(({from:u,to:c})=>`${u}-${c}`)),s=i.desiredPlaybackState$.stateChangeEnded$,n=i.providerChanged$,o=new a.Subject;let l=0,d="unknown";return t.add(r.subscribe(u=>{l&&window.clearTimeout(l),d=u,l=window.setTimeout(()=>o.next(u),i.maxTransitionInterval)})),t.add(s.subscribe(()=>{window.clearTimeout(l),d="provider change",l=0})),t.add(n.subscribe(()=>{l&&(window.clearTimeout(l),l=window.setTimeout(()=>o.next(d),i.maxTransitionInterval))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const zn={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},qb={cacheDuration:12e4},Yb={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},zb={maxPausedTime:3e4},Wb={maxPausedTime:3e4};class Qb{constructor(e){this.current$=new a.ValueSubject({type:void 0}),this.providerError$=new a.Subject,this.noAvailableProvidersError$=new a.Subject,this.providerOutput={position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),volume$:new a.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new a.ValueSubject(void 0),availableVideoTracks$:new a.ValueSubject([]),autoVideoTrackLimitingAvailable$:new a.ValueSubject(!1),currentBuffer$:new a.ValueSubject(void 0),isBuffering$:new a.ValueSubject(!0),error$:new a.Subject,willSeekEvent$:new a.Subject,seekedEvent$:new a.Subject,loopedEvent$:new a.Subject,endedEvent$:new a.Subject,firstBytesEvent$:new a.Subject,firstFrameEvent$:new a.Subject,canplay$:new a.Subject,isLive$:new a.ValueSubject(void 0),liveTime$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),element$:new a.ValueSubject(void 0)},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Ub([...Hb(),...jb()],this.params.tuning.useHlsJs).filter(o=>a.isNonNullable(e.sources[o])),{formatsToAvoid:r}=this.params.tuning,s=r.length?[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:t;this.screenFormatsIterator=new qn(s);const n=[...Yn(!0),...Yn(!1)];this.chromecastFormatsIterator=new qn(n.filter(o=>a.isNonNullable(e.sources[o])))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(a.isNullable(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(s){this.providerError$.next({id:"ProviderNotConstructed",category:a.ErrorCategory.WTF,message:"Failed to create provider",thrown:s})}r?this.current$.next({type:t,provider:r,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const e=this.current$.getValue().destination;a.assertNonNullable(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,r=this.params.desiredState.seekState.getState(),s=r.state!==D.None;this.params.desiredState.seekState.setState({state:D.Requested,position:s?r.position:t,forcePrecise:s?r.forcePrecise:!1}),e.destroy();const n=this.providerOutput.isBuffering$;n.getValue()||n.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case he.SCREEN:return this.createScreenProvider(t);case he.CHROMECAST:return this.createChromecastProvider(t);default:return a.assertNever(e)}}createScreenProvider(e){const{sources:t,container:r,desiredState:s}=this.params,n=this.providerOutput,o={container:r,source:null,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new nb(Object.assign(Object.assign({},o),{source:l,config:qb}))}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),this.params.tuning.useDashJs?new VS(Object.assign(Object.assign({},o),{source:l,format:e,config:Wb})):new wb(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),hr||!this.params.tuning.useHlsJs?new Cb(Object.assign(Object.assign({},o),{source:l})):new Rb(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.HLS_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Nb(Object.assign(Object.assign({},o),{source:l,config:zb}))}case exports.VideoFormat.MPEG:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Db(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new tb(Object.assign(Object.assign({},o),{source:l,config:Yb}))}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Bb({container:r,source:l,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:r,desiredState:s,meta:n}=this.params,o=this.providerOutput,l=this.params.dependencies.chromecastInitializer.connection$.getValue();return a.assertNonNullable(l),new dS({connection:l,meta:n,container:r,source:t,format:e,desiredState:s,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?he.CHROMECAST:he.SCREEN}chooseFormat(e){switch(e){case he.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case he.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return a.assertNever(e)}}skipFormat(e){switch(e){case he.SCREEN:return this.screenFormatsIterator.next();case he.CHROMECAST:return this.chromecastFormatsIterator.next();default:return a.assertNever(e)}}handleNoFormatsError(e){switch(e){case he.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case he.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return a.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const r=s=>{const n=new URL(s);return n.host=t,n.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:r(e.url)})}return oi(Object.entries(e).map(([s,n])=>[s,r(n)]))}initProviderErrorHandling(){const e=new a.Subscription;let t=!1,r=0;return e.add(a.merge(this.providerOutput.error$,Gb({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:zn.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(a.filter(({type:s})=>s!==void 0))}).pipe(a.map(s=>({id:`ProviderHangup:${s}`,category:a.ErrorCategory.WTF,message:`A ${s} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const s=this.params.desiredState.playbackState.transitionEnded$.pipe(a.filter(({to:n})=>n===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>t=!0);e.add(s)})),e.add(this.providerError$.subscribe(s=>{if(this.current$.getValue().destination===he.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=s.category===a.ErrorCategory.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=r<zn.providerErrorLimit;o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(r++,this.reinitProvider()):this.switchToNextProvider()}})),e}}const Wn=(i,e,t)=>t*e+(1-t)*i;class Qn{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.slow=this.fast=this.smoothed=this.prevReported=e.initial,this.smoothed$=new a.ValueSubject(e.initial),this.debounced$=new a.ValueSubject(e.initial);const r=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ie(`raw_${r}`),this.smoothedSeries$=new Ie(`smoothed_${r}`),this.reportedSeries$=new Ie(`reported_${r}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let d=0;d<this.pastMeasures.length;d++)this.pastMeasures[d]!==void 0&&(t+=Math.pow(this.pastMeasures[d]-this.smoothed,2),r++);t/=r;const s=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*s,o=this.smoothed-this.params.deviationFactor*s;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.slow=Wn(this.slow,e,this.params.emaAlphaSlow),this.fast=Wn(this.fast,e,this.params.emaAlphaFast);const l=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=l(this.slow,this.fast),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>n||this.smoothed<o)&&(a.isNullable(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))}}var ge;(function(i){i[i.LOCAL_STORAGE=0]="LOCAL_STORAGE",i[i.SESSION_STORAGE=1]="SESSION_STORAGE",i[i.RUNTIME=2]="RUNTIME"})(ge||(ge={}));const Ml=new Map;let lt=ge.RUNTIME;const cs=`vk-videoplayer-dummy-key-${Math.random()}`,Jb=()=>{try{localStorage.setItem(cs,"test"),localStorage.removeItem(cs),lt=ge.LOCAL_STORAGE}catch(i){if(i instanceof DOMException||i instanceof TypeError)try{sessionStorage.getItem(cs),lt=ge.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)lt=ge.RUNTIME;else throw e}else throw i}};Jb();const Kb=i=>{var e,t;switch(lt){case ge.LOCAL_STORAGE:return(e=localStorage.getItem(i))!==null&&e!==void 0?e:void 0;case ge.SESSION_STORAGE:return(t=sessionStorage.getItem(i))!==null&&t!==void 0?t:void 0;case ge.RUNTIME:return Ml.get(i);default:a.assertNever(lt)}},Jn=(i,e)=>{switch(lt){case ge.LOCAL_STORAGE:try{localStorage.setItem(i,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case ge.SESSION_STORAGE:try{sessionStorage.setItem(i,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case ge.RUNTIME:return void Ml.set(i,e);default:a.assertNever(lt)}},Xb=5e3,Kn="one_video_throughput",Xn="one_video_rtt",Fe=window.navigator.connection,Zn=()=>{const i=Fe==null?void 0:Fe.downlink;if(a.isNonNullable(i)&&i!==10)return i*1e3},eo=()=>{const i=Fe==null?void 0:Fe.rtt;if(a.isNonNullable(i)&&i!==3e3)return i},to=(i,e,t)=>{const r=t*8,s=r/i;return r/(s+e)};class ti{constructor(e){var t,r;this.subscription=new a.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const s=ti.load(Kn)||(e.useBrowserEstimation?Zn():void 0)||Xb,n=(r=(t=ti.load(Xn))!==null&&t!==void 0?t:e.useBrowserEstimation?eo():void 0)!==null&&r!==void 0?r:0;if(this.throughput$=new a.ValueSubject(s),this.rtt$=new a.ValueSubject(n),this.rttAdjustedThroughput$=new a.ValueSubject(to(s,n,e.rttPenaltyRequestSize)),this.throughput=new Qn({initial:s,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:"throughput"}),this.rtt=new Qn({initial:n,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:"rtt"}),e.useBrowserEstimation){const o=()=>{const d=Zn();d&&this.throughput.next(d);const u=eo();a.isNonNullable(u)&&this.rtt.next(u)};Fe&&"onchange"in Fe&&this.subscription.add(a.fromEvent(Fe,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{Jn(Kn,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{Jn(Xn,o.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(a.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(a.map(({throughput:o,rtt:l})=>to(o,l,e.rttPenaltyRequestSize)),a.filter(o=>{const l=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(o-l)/l>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=a.now();const s=new a.Subscription;switch(this.subscription.add(s),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:s.add(a.fromEvent(e,"progress").pipe(a.once()).subscribe(n=>{t=n.loaded,r=a.now()}));break;case 1:case 0:s.add(a.fromEvent(e,"loadstart").subscribe(()=>{t=0,r=a.now()}));break}s.add(a.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,l=a.now(),d=o-t,u=l-r;this.addRawSpeed(d,u,1)}this.concurrentDownloads.delete(e),s.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let r=0;const s=a.now();let n=0,o=a.now();const l=u=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${u}`).catch(()=>{})},d=({done:u,value:c})=>X(this,void 0,void 0,function*(){u?(this.addRawSpeed(r,a.now()-s,1),this.concurrentDownloads.delete(e)):c&&(r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&a.now()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,a.now()-o,this.concurrentDownloads.size),n=0,o=a.now()),yield t==null?void 0:t.read().then(d,l))});this.concurrentDownloads.add(e),t==null||t.read().then(d,l)}addRawSpeed(e,t,r=1){if(ti.sanityCheck(e,t)){const s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||e<10*1024||t<=20)}static load(e){var t;const r=Kb(e);if(a.isNonNullable(r))return(t=parseInt(r,10))!==null&&t!==void 0?t:void 0}}const io={throughputEstimator:{emaAlphaSlow:.2,emaAlphaFast:.7,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:10,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.3,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},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,webrtc:{connectionRetryMaxNumber:3}},Zb=i=>{const e={};for(const t of Object.keys(io)){const r=io[t],s=i[t];Array.isArray(r)&&Array.isArray(s)?e[t]=s:typeof r=="object"&&typeof s=="object"?e[t]=Object.assign(Object.assign({},r),s):e[t]=s!=null?s:r}return e};var eg=({seekState:i,position$:e})=>a.merge(i.stateChangeEnded$.pipe(a.map(({to:t})=>{var r;return t.state===D.None?void 0:((r=t.position)!==null&&r!==void 0?r:NaN)/1e3}),a.filter(a.isNonNullable)),e.pipe(a.filter(()=>i.getState().state===D.None))),tg=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return a.assertNonNullable(e,`Wrong container or containerId {${i.container}}`),e};const ro=({playbackState:i,seekState:e,playbackAbort$:t,looped$:r,position$:s})=>new a.Observable(n=>{let o;const l=i.transitionEnded$.pipe(a.filter(p=>(p.from===exports.PlaybackState.PAUSED||p.from===exports.PlaybackState.STOPPED)&&p.to===exports.PlaybackState.PLAYING)),d=i.stateChangeEnded$.pipe(a.filter(p=>p.from===exports.PlaybackState.PLAYING&&p.to===exports.PlaybackState.PAUSED)),u=e.stateChangeEnded$.pipe(a.filter(({to:p})=>{var v,m;return p.state===D.Requested&&((m=(v=i.getTransition())===null||v===void 0?void 0:v.from)!==null&&m!==void 0?m:i.getState())===exports.PlaybackState.PLAYING})),c=e.stateChangeEnded$.pipe(a.filter(({from:p,to:v})=>{var m,S;return p.state===D.Applying&&v.state===D.None&&((S=(m=i.getTransition())===null||m===void 0?void 0:m.from)!==null&&S!==void 0?S:i.getState())===exports.PlaybackState.PLAYING})),h=a.merge(l,c).pipe(a.map(()=>s.getValue()),a.filter(a.isNonNullable)),f=a.merge(a.merge(d,u,t),r).pipe(a.map(()=>s.getValue()),a.filter(a.isNonNullable));return new a.Subscription().add(h.subscribe(p=>{o=p})).add(f.subscribe(p=>{if(a.isNullable(o)||o===p)return;const v={from:o,to:p};o=void 0,n.next(v)}))});class ig{constructor(e={}){if(this.subscription=new a.Subscription,this.logger=new a.Logger,this.isPlaybackStarted=!1,this.desiredState={playbackState:new K(exports.PlaybackState.STOPPED),seekState:new K({state:D.None}),volume:new K({volume:1,muted:!1}),videoTrack:new K(void 0),autoVideoTrackSwitching:new K(!0),autoVideoTrackLimits:new K({}),isLooped:new K(!1),playbackRate:new K(1),externalTextTracks:new K([]),currentTextTrack:new K(void 0),textTrackCuesSettings:new K({})},this.info={playbackState$:new a.ValueSubject(exports.PlaybackState.STOPPED),position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),muted$:new a.ValueSubject(!1),volume$:new a.ValueSubject(1),availableQualities$:new a.ValueSubject([]),availableQualitiesFps$:new a.ValueSubject({}),currentQuality$:new a.ValueSubject(void 0),isAutoQualityEnabled$:new a.ValueSubject(!0),autoQualityLimitingAvailable$:new a.ValueSubject(!1),autoQualityLimits$:new a.ValueSubject({}),currentPlaybackRate$:new a.ValueSubject(1),currentBuffer$:new a.ValueSubject({start:0,end:0}),isBuffering$:new a.ValueSubject(!0),isStalled$:new a.ValueSubject(!1),isEnded$:new a.ValueSubject(!1),isLooped$:new a.ValueSubject(!1),isLive$:new a.ValueSubject(void 0),liveTime$:new a.ValueSubject(void 0),currentFormat$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),throughputEstimation$:new a.ValueSubject(void 0),rttEstimation$:new a.ValueSubject(void 0),videoBitrate$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),chromecastState$:new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new a.ValueSubject(void 0),intrinsicVideoSize$:new a.ValueSubject(void 0)},this.events={inited$:new a.Subject,started$:new a.Subject,willPause$:new a.Subject,willResume$:new a.Subject,willDestruct$:new a.Subject,watchCoverageRecord$:new a.Subject,watchCoverageLive$:new a.Subject,managedError$:new a.Subject,fatalError$:new a.Subject,ended$:new a.Subject,looped$:new a.Subject,seeked$:new a.Subject,willSeek$:new a.Subject,firstBytes$:new a.Subject,firstFrame$:new a.Subject,canplay$:new a.Subject,log$:new a.Subject},this.experimental={element$:new a.ValueSubject(void 0),enableDebugTelemetry$:new a.ValueSubject(!1),dumpTelemetry:DS},this.initLogs(),this.tuning=Zb(e),this.chromecastInitializer=new fu({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new ti(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,r,s)=>{const n=Reflect.get(t,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(l){const d=o.map(h=>JSON.stringify(h,(f,p)=>{const v=typeof p;return["number","string","boolean"].includes(v)?p:p===null?null:`<${v}>`})),u=`Player.${String(r)}`,c=`Exception calling ${u} (${d.join(", ")})`;throw this.events.fatalError$.next({id:u,category:a.ErrorCategory.WTF,message:c,thrown:l}),l}}}})}initVideo(e){var t,r,s;return this.config=e,this.domContainer=tg(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Qb({sources:e.sources,meta:(r=e.meta)!==null&&r!==void 0?r:{},failoverHosts:(s=e.failoverHosts)!==null&&s!==void 0?s:[],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.initDebugTelemetry(),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()}play(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PLAYING&&e.startTransitionTo(exports.PlaybackState.PLAYING),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PAUSED&&e.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(e,t=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:D.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){return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:this.desiredState.volume.getState().muted}),this}setMuted(e){return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(e):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:e}),this}setQuality(e){a.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const r=t.find(s=>s.quality===e);return r&&this.desiredState.videoTrack.startTransitionTo(r.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.setState(e),this}setPlaybackRate(e){var t;a.assertNonNullable(this.providerContainer);const r=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return r&&(this.desiredState.playbackRate.setState(e),r.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(r=>r.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(){a.assertNonNullable(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(a.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),r=t.state===D.None?void 0:t.position;return a.isNonNullable(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}initDesiredStateSubscriptions(){this.subscription.add(a.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(a.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(a.filter(()=>!this.isPlaybackStarted),a.filter(e=>e.to===exports.PlaybackState.PLAYING)).subscribe(()=>{this.isPlaybackStarted=!0,this.events.started$.next()})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():(this.initedAt=a.now(),this.events.inited$.next());break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const d=this.desiredState.seekState.getState();d.state===D.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},d),{state:D.Applying})):this.events.managedError$.next({id:`WillSeekIn${d.state}`,category:a.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===D.Applying&&(this.desiredState.seekState.setState({state:D.None}),this.events.seeked$.next())})).add(e.current$.pipe(a.map(d=>d.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(a.map(d=>d.destination),a.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(a.map(d=>d.map(({quality:u})=>u).sort((u,c)=>Wi(u)?1:Wi(c)?-1:Ui(c,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(d=>{const u={};for(const c of d)c.fps&&(u[c.quality]=c.fps);this.info.availableQualitiesFps$.next(u)})).add(e.providerOutput.currentVideoTrack$.subscribe(d=>{this.info.currentQuality$.next(d==null?void 0:d.quality),this.info.videoBitrate$.next(d==null?void 0:d.bitrate);const u=e.providerOutput.element$.getValue();u&&this.info.intrinsicVideoSize$.next({width:u.videoWidth,height:u.videoHeight})})).add(e.providerOutput.hostname$.pipe(a.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(a.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(a.filterChanged()).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(a.map(d=>d?{start:d.from,end:d.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(a.map(d=>d.muted),a.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(a.map(d=>d.volume),a.filterChanged()).subscribe(this.info.volume$)).add(eg({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(a.merge(e.providerOutput.endedEvent$.pipe(a.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(a.mapTo(!1))).pipe(a.filterChanged()).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(a.map(d=>({id:"NoProviders",category:a.ErrorCategory.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(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(a.once(),a.map(()=>a.now()-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 a.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const r=new a.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(a.filter(({to:d})=>d===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>r.next(!1)));let s=0;const n=a.merge(e.providerOutput.isBuffering$,t,r).pipe(a.map(()=>{const d=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||r.getValue();return d&&!u}),a.filterChanged());this.subscription.add(n.subscribe(d=>{d?s=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(s),this.info.isStalled$.next(!1))}));const o=new a.Subscription;this.subscription.add(o);const l=a.merge(a.fromEvent(window,"beforeunload"),this.events.willDestruct$,e.current$.pipe(a.filter(d=>Boolean(d==null?void 0:d.provider))));e.providerOutput.isLive$.pipe(a.filterChanged()).subscribe(d=>{switch(a.assertNonNullable(this.providerContainer),o.unsubscribe(),d){case!0:{const u=new a.ValueSubject(void 0);o.add(this.providerContainer.providerOutput.liveTime$.subscribe(c=>u.next(c&&Math.floor(c/1e3)))),o.add(ro({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:l,looped$:this.events.looped$,position$:u}).pipe(a.map(({from:c,to:h})=>({start:c,end:h}))).subscribe(this.events.watchCoverageLive$));break}case!1:o.add(ro({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:l,position$:this.providerContainer.providerOutput.position$}).pipe(a.map(({from:u,to:c})=>({start:u,end:c}))).subscribe(this.events.watchCoverageRecord$));break}})}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(a.map(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 a.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(a.filterChanged((r,s)=>r.provider===s.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(a.filter(r=>r.length>0),a.once()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:r})=>r===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=di(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(a.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(a.map(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;a.assertNonNullable(this.providerContainer),a.assertNonNullable(t),CS(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>NS(r)),this.providerContainer.current$.subscribe(({type:r})=>Ri("provider",r)),t.duration$.subscribe(r=>Ri("duration",r)),t.availableVideoTracks$.pipe(a.filter(r=>!!r.length),a.once()).subscribe(r=>Ri("tracks",r)),this.events.fatalError$.subscribe(new Ie("fatalError")),this.events.managedError$.subscribe(new Ie("managedError")),t.position$.subscribe(new Ie("position")),t.currentVideoTrack$.pipe(a.map(r=>r==null?void 0:r.quality)).subscribe(new Ie("quality")),this.info.currentBuffer$.subscribe(new Ie("buffer")),t.isBuffering$.subscribe(new Ie("isBuffering"))].forEach(r=>this.subscription.add(r)),Ri("codecs",Fb())}}const rg=`${cu}@${du}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return a.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return a.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return a.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return a.ValueSubject}});exports.Player=ig;exports.SDK_VERSION=rg;
|
|
6
|
+
"use strict";var ru=Object.create;var pa=Object.defineProperty;var su=Object.getOwnPropertyDescriptor;var au=Object.getOwnPropertyNames;var nu=Object.getPrototypeOf,ou=Object.prototype.hasOwnProperty;var lu=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of au(e))!ou.call(i,s)&&s!==t&&pa(i,s,{get:()=>e[s],enumerable:!(r=su(e,s))||r.enumerable});return i};var ma=(i,e,t)=>(t=i!=null?ru(nu(i)):{},lu(e||!i||!i.__esModule?pa(t,"default",{value:i,enumerable:!0}):t,i));var a=require("@vkontakte/videoplayer-shared/es2015.cjs.js"),uu=require("lodash/debounce.js");const du="2.0.79",cu="@vkontakte/videoplayer-core";exports.PlaybackState=void 0;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(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_WEBM="DASH_LIVE_WEBM",i.HLS="HLS",i.HLS_ONDEMAND="HLS_ONDEMAND",i.HLS_JS="HLS",i.HLS_LIVE="HLS_LIVE",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(exports.VideoFormat||(exports.VideoFormat={}));var he;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(he||(he={}));exports.ChromecastState=void 0;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var C;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(C||(C={}));var hu=i=>new Promise((e,t)=>{const r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});class fu{constructor(e){var t;this.connection$=new a.ValueSubject(void 0),this.castState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new a.Subject,this.realCastState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const r="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${r}`}),e.isDisabled||!r)return;const s=a.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=Boolean(window.__onGCastApiAvailable);s?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||hu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:a.ErrorCategory.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 r,s,n;(n=(s=(r=cast.framework.CastContext.getInstance())===null||r===void 0?void 0:r.getCurrentSession())===null||s===void 0?void 0:s.getMediaSession())===null||n===void 0||n.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){a.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();a.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();a.isNullable(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),r=cast.framework.CastContext.getInstance();this.subscription.add(a.fromEvent(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(s=>{var n,o;switch(s.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=r.getCurrentSession())===null||n===void 0?void 0:n.getMediaSession())===null||o===void 0?void 0:o.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 a.assertNever(s.sessionState)}})).add(a.merge(a.fromEvent(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(a.tap(s=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(s)}`})}),a.map(s=>s.castState)),a.observableFrom([r.getCastState()])).pipe(a.filterChanged(),a.map(pu),a.tap(s=>{this.log({message:`realCastState$: ${s}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(s=>{var n;const o=s===exports.ChromecastState.CONNECTED,l=a.isNonNullable(this.connection$.getValue());if(o&&!l){const d=r.getCurrentSession();a.assertNonNullable(d);const u=d.getCastDevice(),c=(n=d.getMediaSession())===null||n===void 0?void 0:n.media.contentId;(a.isNullable(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:d,castDevice:u}))}else!o&&l&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(s===exports.ChromecastState.CONNECTED?a.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:s)}))}initializeCastApi(){var e;let t,r,s;try{t=cast.framework.CastContext.getInstance(),r=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,s=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:r,autoJoinPolicy:s}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:a.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const pu=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return exports.ChromecastState.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return exports.ChromecastState.AVAILABLE;case cast.framework.CastState.CONNECTING:return exports.ChromecastState.CONNECTING;case cast.framework.CastState.CONNECTED:return exports.ChromecastState.CONNECTED;default:return a.assertNever(i)}};var va=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},ye=function(i){try{return!!i()}catch(e){return!0}},mu=ye,er=!mu(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),so=er,ao=Function.prototype,hs=ao.call,vu=so&&ao.bind.bind(hs,hs),Ce=so?vu:function(i){return function(){return hs.apply(i,arguments)}},no=Ce,Su=no({}.toString),bu=no("".slice),tr=function(i){return bu(Su(i),8,-1)},gu=Ce,yu=ye,Tu=tr,Sr=Object,Eu=gu("".split),$u=yu(function(){return!Sr("z").propertyIsEnumerable(0)})?function(i){return Tu(i)=="String"?Eu(i,""):Sr(i)}:Sr,ir=function(i){return i==null},Pu=ir,ku=TypeError,oo=function(i){if(Pu(i))throw ku("Can't call method on "+i);return i},wu=$u,_u=oo,si=function(i){return wu(_u(i))},Au=function(){},Ct={},vi=function(i){return i&&i.Math==Math&&i},le=vi(typeof globalThis=="object"&&globalThis)||vi(typeof window=="object"&&window)||vi(typeof self=="object"&&self)||vi(typeof va=="object"&&va)||function(){return this}()||Function("return this")(),fs=typeof document=="object"&&document.all,Ru=typeof fs=="undefined"&&fs!==void 0,lo={all:fs,IS_HTMLDDA:Ru},uo=lo,Iu=uo.all,se=uo.IS_HTMLDDA?function(i){return typeof i=="function"||i===Iu}:function(i){return typeof i=="function"},Nu=le,Cu=se,Sa=Nu.WeakMap,Du=Cu(Sa)&&/native code/.test(String(Sa)),ba=se,co=lo,Ou=co.all,Ke=co.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:ba(i)||i===Ou}:function(i){return typeof i=="object"?i!==null:ba(i)},Lu=ye,Ue=!Lu(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),ct={},xu=le,ga=Ke,ps=xu.document,Bu=ga(ps)&&ga(ps.createElement),Ds=function(i){return Bu?ps.createElement(i):{}},Mu=Ue,Vu=ye,Fu=Ds,ho=!Mu&&!Vu(function(){return Object.defineProperty(Fu("div"),"a",{get:function(){return 7}}).a!=7}),Uu=Ue,ju=ye,fo=Uu&&ju(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Hu=Ke,Gu=String,qu=TypeError,Xe=function(i){if(Hu(i))return i;throw qu(Gu(i)+" is not an object")},Yu=er,Si=Function.prototype.call,Pe=Yu?Si.bind(Si):function(){return Si.apply(Si,arguments)},Os={},br=Os,gr=le,zu=se,ya=function(i){return zu(i)?i:void 0},ht=function(i,e){return arguments.length<2?ya(br[i])||ya(gr[i]):br[i]&&br[i][e]||gr[i]&&gr[i][e]},Wu=Ce,Ls=Wu({}.isPrototypeOf),rr=typeof navigator!="undefined"&&String(navigator.userAgent)||"",po=le,yr=rr,Ta=po.process,Ea=po.Deno,$a=Ta&&Ta.versions||Ea&&Ea.version,Pa=$a&&$a.v8,Te,Hi;Pa&&(Te=Pa.split("."),Hi=Te[0]>0&&Te[0]<4?1:+(Te[0]+Te[1]));!Hi&&yr&&(Te=yr.match(/Edge\/(\d+)/),(!Te||Te[1]>=74)&&(Te=yr.match(/Chrome\/(\d+)/),Te&&(Hi=+Te[1])));var mo=Hi,ka=mo,Qu=ye,vo=!!Object.getOwnPropertySymbols&&!Qu(function(){var i=Symbol();return!String(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&ka&&ka<41}),Ju=vo,So=Ju&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Ku=ht,Xu=se,Zu=Ls,ed=So,td=Object,bo=ed?function(i){return typeof i=="symbol"}:function(i){var e=Ku("Symbol");return Xu(e)&&Zu(e.prototype,td(i))},id=String,sr=function(i){try{return id(i)}catch(e){return"Object"}},rd=se,sd=sr,ad=TypeError,ft=function(i){if(rd(i))return i;throw ad(sd(i)+" is not a function")},nd=ft,od=ir,xs=function(i,e){var t=i[e];return od(t)?void 0:nd(t)},Tr=Pe,Er=se,$r=Ke,ld=TypeError,ud=function(i,e){var t,r;if(e==="string"&&Er(t=i.toString)&&!$r(r=Tr(t,i))||Er(t=i.valueOf)&&!$r(r=Tr(t,i))||e!=="string"&&Er(t=i.toString)&&!$r(r=Tr(t,i)))return r;throw ld("Can't convert object to primitive value")},Gi={},dd={get exports(){return Gi},set exports(i){Gi=i}},go=!0,wa=le,cd=Object.defineProperty,hd=function(i,e){try{cd(wa,i,{value:e,configurable:!0,writable:!0})}catch(t){wa[i]=e}return e},fd=le,pd=hd,_a="__core-js_shared__",md=fd[_a]||pd(_a,{}),Bs=md,Aa=Bs;(dd.exports=function(i,e){return Aa[i]||(Aa[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 vd=oo,Sd=Object,Ms=function(i){return Sd(vd(i))},bd=Ce,gd=Ms,yd=bd({}.hasOwnProperty),je=Object.hasOwn||function(e,t){return yd(gd(e),t)},Td=Ce,Ed=0,$d=Math.random(),Pd=Td(1 .toString),yo=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Pd(++Ed+$d,36)},kd=le,wd=Gi,Ra=je,_d=yo,Ad=vo,Rd=So,Et=kd.Symbol,Pr=wd("wks"),Id=Rd?Et.for||Et:Et&&Et.withoutSetter||_d,pe=function(i){return Ra(Pr,i)||(Pr[i]=Ad&&Ra(Et,i)?Et[i]:Id("Symbol."+i)),Pr[i]},Nd=Pe,Ia=Ke,Na=bo,Cd=xs,Dd=ud,Od=pe,Ld=TypeError,xd=Od("toPrimitive"),Bd=function(i,e){if(!Ia(i)||Na(i))return i;var t=Cd(i,xd),r;if(t){if(e===void 0&&(e="default"),r=Nd(t,i,e),!Ia(r)||Na(r))return r;throw Ld("Can't convert object to primitive value")}return e===void 0&&(e="number"),Dd(i,e)},Md=Bd,Vd=bo,Vs=function(i){var e=Md(i,"string");return Vd(e)?e:e+""},Fd=Ue,Ud=ho,jd=fo,bi=Xe,Ca=Vs,Hd=TypeError,kr=Object.defineProperty,Gd=Object.getOwnPropertyDescriptor,wr="enumerable",_r="configurable",Ar="writable";ct.f=Fd?jd?function(e,t,r){if(bi(e),t=Ca(t),bi(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Ar in r&&!r[Ar]){var s=Gd(e,t);s&&s[Ar]&&(e[t]=r.value,r={configurable:_r in r?r[_r]:s[_r],enumerable:wr in r?r[wr]:s[wr],writable:!1})}return kr(e,t,r)}:kr:function(e,t,r){if(bi(e),t=Ca(t),bi(r),Ud)try{return kr(e,t,r)}catch(s){}if("get"in r||"set"in r)throw Hd("Accessors not supported");return"value"in r&&(e[t]=r.value),e};var ar=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},qd=Ue,Yd=ct,zd=ar,ai=qd?function(i,e,t){return Yd.f(i,e,zd(1,t))}:function(i,e,t){return i[e]=t,i},Wd=Gi,Qd=yo,Da=Wd("keys"),Fs=function(i){return Da[i]||(Da[i]=Qd(i))},Us={},Jd=Du,To=le,Kd=Ke,Xd=ai,Rr=je,Ir=Bs,Zd=Fs,ec=Us,Oa="Object already initialized",ms=To.TypeError,tc=To.WeakMap,qi,ii,Yi,ic=function(i){return Yi(i)?ii(i):qi(i,{})},rc=function(i){return function(e){var t;if(!Kd(e)||(t=ii(e)).type!==i)throw ms("Incompatible receiver, "+i+" required");return t}};if(Jd||Ir.state){var Ae=Ir.state||(Ir.state=new tc);Ae.get=Ae.get,Ae.has=Ae.has,Ae.set=Ae.set,qi=function(i,e){if(Ae.has(i))throw ms(Oa);return e.facade=i,Ae.set(i,e),e},ii=function(i){return Ae.get(i)||{}},Yi=function(i){return Ae.has(i)}}else{var bt=Zd("state");ec[bt]=!0,qi=function(i,e){if(Rr(i,bt))throw ms(Oa);return e.facade=i,Xd(i,bt,e),e},ii=function(i){return Rr(i,bt)?i[bt]:{}},Yi=function(i){return Rr(i,bt)}}var Eo={set:qi,get:ii,has:Yi,enforce:ic,getterFor:rc},sc=er,$o=Function.prototype,La=$o.apply,xa=$o.call,Po=typeof Reflect=="object"&&Reflect.apply||(sc?xa.bind(La):function(){return xa.apply(La,arguments)}),ac=tr,nc=Ce,ko=function(i){if(ac(i)==="Function")return nc(i)},js={},wo={},_o={}.propertyIsEnumerable,Ao=Object.getOwnPropertyDescriptor,oc=Ao&&!_o.call({1:2},1);wo.f=oc?function(e){var t=Ao(this,e);return!!t&&t.enumerable}:_o;var lc=Ue,uc=Pe,dc=wo,cc=ar,hc=si,fc=Vs,pc=je,mc=ho,Ba=Object.getOwnPropertyDescriptor;js.f=lc?Ba:function(e,t){if(e=hc(e),t=fc(t),mc)try{return Ba(e,t)}catch(r){}if(pc(e,t))return cc(!uc(dc.f,e,t),e[t])};var vc=ye,Sc=se,bc=/#|\.prototype\./,ni=function(i,e){var t=yc[gc(i)];return t==Ec?!0:t==Tc?!1:Sc(e)?vc(e):!!e},gc=ni.normalize=function(i){return String(i).replace(bc,".").toLowerCase()},yc=ni.data={},Tc=ni.NATIVE="N",Ec=ni.POLYFILL="P",Ro=ni,Ma=ko,$c=ft,Pc=er,kc=Ma(Ma.bind),nr=function(i,e){return $c(i),e===void 0?i:Pc?kc(i,e):function(){return i.apply(e,arguments)}},gi=le,wc=Po,_c=ko,Ac=se,Rc=js.f,Ic=Ro,gt=Os,Nc=nr,yt=ai,Va=je,Cc=function(i){var e=function(t,r,s){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,r)}return new i(t,r,s)}return wc(i,this,arguments)};return e.prototype=i.prototype,e},De=function(i,e){var t=i.target,r=i.global,s=i.stat,n=i.proto,o=r?gi:s?gi[t]:(gi[t]||{}).prototype,l=r?gt:gt[t]||yt(gt,t,{})[t],d=l.prototype,u,c,h,f,p,v,m,S,b;for(f in e)u=Ic(r?f:t+(s?".":"#")+f,i.forced),c=!u&&o&&Va(o,f),v=l[f],c&&(i.dontCallGetSet?(b=Rc(o,f),m=b&&b.value):m=o[f]),p=c&&m?m:e[f],!(c&&typeof v==typeof p)&&(i.bind&&c?S=Nc(p,gi):i.wrap&&c?S=Cc(p):n&&Ac(p)?S=_c(p):S=p,(i.sham||p&&p.sham||v&&v.sham)&&yt(S,"sham",!0),yt(l,f,S),n&&(h=t+"Prototype",Va(gt,h)||yt(gt,h,{}),yt(gt[h],f,p),i.real&&d&&(u||!d[f])&&yt(d,f,p)))},vs=Ue,Dc=je,Io=Function.prototype,Oc=vs&&Object.getOwnPropertyDescriptor,Hs=Dc(Io,"name"),Lc=Hs&&function(){}.name==="something",xc=Hs&&(!vs||vs&&Oc(Io,"name").configurable),Bc={EXISTS:Hs,PROPER:Lc,CONFIGURABLE:xc},No={},Mc=Math.ceil,Vc=Math.floor,Fc=Math.trunc||function(e){var t=+e;return(t>0?Vc:Mc)(t)},Uc=Fc,Gs=function(i){var e=+i;return e!==e||e===0?0:Uc(e)},jc=Gs,Hc=Math.max,Gc=Math.min,qc=function(i,e){var t=jc(i);return t<0?Hc(t+e,0):Gc(t,e)},Yc=Gs,zc=Math.min,Wc=function(i){return i>0?zc(Yc(i),9007199254740991):0},Qc=Wc,qs=function(i){return Qc(i.length)},Jc=si,Kc=qc,Xc=qs,Fa=function(i){return function(e,t,r){var s=Jc(e),n=Xc(s),o=Kc(r,n),l;if(i&&t!=t){for(;n>o;)if(l=s[o++],l!=l)return!0}else for(;n>o;o++)if((i||o in s)&&s[o]===t)return i||o||0;return!i&&-1}},Zc={includes:Fa(!0),indexOf:Fa(!1)},eh=Ce,Nr=je,th=si,ih=Zc.indexOf,rh=Us,Ua=eh([].push),sh=function(i,e){var t=th(i),r=0,s=[],n;for(n in t)!Nr(rh,n)&&Nr(t,n)&&Ua(s,n);for(;e.length>r;)Nr(t,n=e[r++])&&(~ih(s,n)||Ua(s,n));return s},Co=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],ah=sh,nh=Co,oh=Object.keys||function(e){return ah(e,nh)},lh=Ue,uh=fo,dh=ct,ch=Xe,hh=si,fh=oh;No.f=lh&&!uh?Object.defineProperties:function(e,t){ch(e);for(var r=hh(t),s=fh(t),n=s.length,o=0,l;n>o;)dh.f(e,l=s[o++],r[l]);return e};var ph=ht,Do=ph("document","documentElement"),mh=Xe,vh=No,ja=Co,Sh=Us,bh=Do,gh=Ds,yh=Fs,Ha=">",Ga="<",Ss="prototype",bs="script",Oo=yh("IE_PROTO"),Cr=function(){},Lo=function(i){return Ga+bs+Ha+i+Ga+"/"+bs+Ha},qa=function(i){i.write(Lo("")),i.close();var e=i.parentWindow.Object;return i=null,e},Th=function(){var i=gh("iframe"),e="java"+bs+":",t;return i.style.display="none",bh.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Lo("document.F=Object")),t.close(),t.F},yi,Mi=function(){try{yi=new ActiveXObject("htmlfile")}catch(e){}Mi=typeof document!="undefined"?document.domain&&yi?qa(yi):Th():qa(yi);for(var i=ja.length;i--;)delete Mi[Ss][ja[i]];return Mi()};Sh[Oo]=!0;var xo=Object.create||function(e,t){var r;return e!==null?(Cr[Ss]=mh(e),r=new Cr,Cr[Ss]=null,r[Oo]=e):r=Mi(),t===void 0?r:vh.f(r,t)},Eh=ye,$h=!Eh(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),Ph=je,kh=se,wh=Ms,_h=Fs,Ah=$h,Ya=_h("IE_PROTO"),gs=Object,Rh=gs.prototype,Bo=Ah?gs.getPrototypeOf:function(i){var e=wh(i);if(Ph(e,Ya))return e[Ya];var t=e.constructor;return kh(t)&&e instanceof t?t.prototype:e instanceof gs?Rh:null},Ih=ai,Ys=function(i,e,t,r){return r&&r.enumerable?i[e]=t:Ih(i,e,t),i},Nh=ye,Ch=se,Dh=Ke,Oh=xo,za=Bo,Lh=Ys,xh=pe,ys=xh("iterator"),Mo=!1,Ve,Dr,Or;[].keys&&(Or=[].keys(),"next"in Or?(Dr=za(za(Or)),Dr!==Object.prototype&&(Ve=Dr)):Mo=!0);var Bh=!Dh(Ve)||Nh(function(){var i={};return Ve[ys].call(i)!==i});Bh?Ve={}:Ve=Oh(Ve);Ch(Ve[ys])||Lh(Ve,ys,function(){return this});var Vo={IteratorPrototype:Ve,BUGGY_SAFARI_ITERATORS:Mo},Mh=pe,Vh=Mh("toStringTag"),Fo={};Fo[Vh]="z";var zs=String(Fo)==="[object z]",Fh=zs,Uh=se,Vi=tr,jh=pe,Hh=jh("toStringTag"),Gh=Object,qh=Vi(function(){return arguments}())=="Arguments",Yh=function(i,e){try{return i[e]}catch(t){}},or=Fh?Vi:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=Yh(e=Gh(i),Hh))=="string"?t:qh?Vi(e):(r=Vi(e))=="Object"&&Uh(e.callee)?"Arguments":r},zh=zs,Wh=or,Qh=zh?{}.toString:function(){return"[object "+Wh(this)+"]"},Jh=zs,Kh=ct.f,Xh=ai,Zh=je,ef=Qh,tf=pe,Wa=tf("toStringTag"),Ws=function(i,e,t,r){if(i){var s=t?i:i.prototype;Zh(s,Wa)||Kh(s,Wa,{configurable:!0,value:e}),r&&!Jh&&Xh(s,"toString",ef)}},rf=Vo.IteratorPrototype,sf=xo,af=ar,nf=Ws,of=Ct,lf=function(){return this},uf=function(i,e,t,r){var s=e+" Iterator";return i.prototype=sf(rf,{next:af(+!r,t)}),nf(i,s,!1,!0),of[s]=lf,i},df=De,cf=Pe,Uo=Bc,hf=uf,ff=Bo,pf=Ws,Qa=Ys,mf=pe,Ja=Ct,jo=Vo,vf=Uo.PROPER;Uo.CONFIGURABLE;jo.IteratorPrototype;var Ti=jo.BUGGY_SAFARI_ITERATORS,Lr=mf("iterator"),Ka="keys",Ei="values",Xa="entries",Sf=function(){return this},bf=function(i,e,t,r,s,n,o){hf(t,e,r);var l=function(b){if(b===s&&f)return f;if(!Ti&&b in c)return c[b];switch(b){case Ka:return function(){return new t(this,b)};case Ei:return function(){return new t(this,b)};case Xa:return function(){return new t(this,b)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=i.prototype,h=c[Lr]||c["@@iterator"]||s&&c[s],f=!Ti&&h||l(s),p=e=="Array"&&c.entries||h,v,m,S;if(p&&(v=ff(p.call(new i)),v!==Object.prototype&&v.next&&(pf(v,d,!0,!0),Ja[d]=Sf)),vf&&s==Ei&&h&&h.name!==Ei&&(u=!0,f=function(){return cf(h,this)}),s)if(m={values:l(Ei),keys:n?f:l(Ka),entries:l(Xa)},o)for(S in m)(Ti||u||!(S in c))&&Qa(c,S,m[S]);else df({target:e,proto:!0,forced:Ti||u},m);return o&&c[Lr]!==f&&Qa(c,Lr,f,{name:s}),Ja[e]=f,m},gf=function(i,e){return{value:i,done:e}},yf=si,Qs=Au,Za=Ct,Ho=Eo,Tf=ct.f,Ef=bf,$i=gf,$f=go,Pf=Ue,Go="Array Iterator",kf=Ho.set,wf=Ho.getterFor(Go);Ef(Array,"Array",function(i,e){kf(this,{type:Go,target:yf(i),index:0,kind:e})},function(){var i=wf(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,$i(void 0,!0)):t=="keys"?$i(r,!1):t=="values"?$i(e[r],!1):$i([r,e[r]],!1)},"values");var en=Za.Arguments=Za.Array;Qs();Qs();Qs();if(!$f&&Pf&&en.name!=="values")try{Tf(en,"name",{value:"values"})}catch(i){}var _f=pe,Af=Ct,Rf=_f("iterator"),If=Array.prototype,Nf=function(i){return i!==void 0&&(Af.Array===i||If[Rf]===i)},Cf=or,tn=xs,Df=ir,Of=Ct,Lf=pe,xf=Lf("iterator"),qo=function(i){if(!Df(i))return tn(i,xf)||tn(i,"@@iterator")||Of[Cf(i)]},Bf=Pe,Mf=ft,Vf=Xe,Ff=sr,Uf=qo,jf=TypeError,Hf=function(i,e){var t=arguments.length<2?Uf(i):e;if(Mf(t))return Vf(Bf(t,i));throw jf(Ff(i)+" is not iterable")},Gf=Pe,rn=Xe,qf=xs,Yf=function(i,e,t){var r,s;rn(i);try{if(r=qf(i,"return"),!r){if(e==="throw")throw t;return t}r=Gf(r,i)}catch(n){s=!0,r=n}if(e==="throw")throw t;if(s)throw r;return rn(r),t},zf=nr,Wf=Pe,Qf=Xe,Jf=sr,Kf=Nf,Xf=qs,sn=Ls,Zf=Hf,ep=qo,an=Yf,tp=TypeError,Fi=function(i,e){this.stopped=i,this.result=e},nn=Fi.prototype,Js=function(i,e,t){var r=t&&t.that,s=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),d=zf(e,r),u,c,h,f,p,v,m,S=function(y){return u&&an(u,"normal",y),new Fi(!0,y)},b=function(y){return s?(Qf(y),l?d(y[0],y[1],S):d(y[0],y[1])):l?d(y,S):d(y)};if(n)u=i.iterator;else if(o)u=i;else{if(c=ep(i),!c)throw tp(Jf(i)+" is not iterable");if(Kf(c)){for(h=0,f=Xf(i);f>h;h++)if(p=b(i[h]),p&&sn(nn,p))return p;return new Fi(!1)}u=Zf(i,c)}for(v=n?i.next:u.next;!(m=Wf(v,u)).done;){try{p=b(m.value)}catch(y){an(u,"throw",y)}if(typeof p=="object"&&p&&sn(nn,p))return p}return new Fi(!1)},ip=Vs,rp=ct,sp=ar,ap=function(i,e,t){var r=ip(e);r in i?rp.f(i,r,sp(0,t)):i[r]=t},np=De,op=Js,lp=ap;np({target:"Object",stat:!0},{fromEntries:function(e){var t={};return op(e,function(r,s){lp(t,r,s)},{AS_ENTRIES:!0}),t}});var up=Os,dp=up.Object.fromEntries,cp={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},hp=cp,fp=le,pp=or,mp=ai,on=Ct,vp=pe,ln=vp("toStringTag");for(var xr in hp){var un=fp[xr],Br=un&&un.prototype;Br&&pp(Br)!==ln&&mp(Br,ln,xr),on[xr]=on.Array}var Sp=dp,bp=Sp,gp=bp,yp=gp,oi=yp,Tp=tr,lr=typeof process!="undefined"&&Tp(process)=="process",Ep=ht,$p=ct,Pp=pe,kp=Ue,dn=Pp("species"),wp=function(i){var e=Ep(i),t=$p.f;kp&&e&&!e[dn]&&t(e,dn,{configurable:!0,get:function(){return this}})},_p=Ls,Ap=TypeError,Rp=function(i,e){if(_p(e,i))return i;throw Ap("Incorrect invocation")},Ip=Ce,Np=se,Ts=Bs,Cp=Ip(Function.toString);Np(Ts.inspectSource)||(Ts.inspectSource=function(i){return Cp(i)});var Yo=Ts.inspectSource,Dp=Ce,Op=ye,zo=se,Lp=or,xp=ht,Bp=Yo,Wo=function(){},Mp=[],Qo=xp("Reflect","construct"),Ks=/^\s*(?:class|function)\b/,Vp=Dp(Ks.exec),Fp=!Ks.exec(Wo),Yt=function(e){if(!zo(e))return!1;try{return Qo(Wo,Mp,e),!0}catch(t){return!1}},Jo=function(e){if(!zo(e))return!1;switch(Lp(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Fp||!!Vp(Ks,Bp(e))}catch(t){return!0}};Jo.sham=!0;var Up=!Qo||Op(function(){var i;return Yt(Yt.call)||!Yt(Object)||!Yt(function(){i=!0})||i})?Jo:Yt,jp=Up,Hp=sr,Gp=TypeError,qp=function(i){if(jp(i))return i;throw Gp(Hp(i)+" is not a constructor")},cn=Xe,Yp=qp,zp=ir,Wp=pe,Qp=Wp("species"),Ko=function(i,e){var t=cn(i).constructor,r;return t===void 0||zp(r=cn(t)[Qp])?e:Yp(r)},Jp=Ce,Kp=Jp([].slice),Xp=TypeError,Zp=function(i,e){if(i<e)throw Xp("Not enough arguments");return i},em=rr,Xo=/(?:ipad|iphone|ipod).*applewebkit/i.test(em),fe=le,tm=Po,im=nr,hn=se,rm=je,Zo=ye,fn=Do,sm=Kp,pn=Ds,am=Zp,nm=Xo,om=lr,Es=fe.setImmediate,$s=fe.clearImmediate,lm=fe.process,Mr=fe.Dispatch,um=fe.Function,mn=fe.MessageChannel,dm=fe.String,Vr=0,Kt={},vn="onreadystatechange",ri,nt,Fr,Ur;Zo(function(){ri=fe.location});var Xs=function(i){if(rm(Kt,i)){var e=Kt[i];delete Kt[i],e()}},jr=function(i){return function(){Xs(i)}},Sn=function(i){Xs(i.data)},bn=function(i){fe.postMessage(dm(i),ri.protocol+"//"+ri.host)};(!Es||!$s)&&(Es=function(e){am(arguments.length,1);var t=hn(e)?e:um(e),r=sm(arguments,1);return Kt[++Vr]=function(){tm(t,void 0,r)},nt(Vr),Vr},$s=function(e){delete Kt[e]},om?nt=function(i){lm.nextTick(jr(i))}:Mr&&Mr.now?nt=function(i){Mr.now(jr(i))}:mn&&!nm?(Fr=new mn,Ur=Fr.port2,Fr.port1.onmessage=Sn,nt=im(Ur.postMessage,Ur)):fe.addEventListener&&hn(fe.postMessage)&&!fe.importScripts&&ri&&ri.protocol!=="file:"&&!Zo(bn)?(nt=bn,fe.addEventListener("message",Sn,!1)):vn in pn("script")?nt=function(i){fn.appendChild(pn("script"))[vn]=function(){fn.removeChild(this),Xs(i)}}:nt=function(i){setTimeout(jr(i),0)});var el={set:Es,clear:$s},tl=function(){this.head=null,this.tail=null};tl.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 il=tl,cm=rr,hm=/ipad|iphone|ipod/i.test(cm)&&typeof Pebble!="undefined",fm=rr,pm=/web0s(?!.*chrome)/i.test(fm),dt=le,gn=nr,mm=js.f,Hr=el.set,vm=il,Sm=Xo,bm=hm,gm=pm,Gr=lr,yn=dt.MutationObserver||dt.WebKitMutationObserver,Tn=dt.document,En=dt.process,Pi=dt.Promise,$n=mm(dt,"queueMicrotask"),Ps=$n&&$n.value,Tt,qr,Yr,ki,Pn;if(!Ps){var wi=new vm,_i=function(){var i,e;for(Gr&&(i=En.domain)&&i.exit();e=wi.get();)try{e()}catch(t){throw wi.head&&Tt(),t}i&&i.enter()};!Sm&&!Gr&&!gm&&yn&&Tn?(qr=!0,Yr=Tn.createTextNode(""),new yn(_i).observe(Yr,{characterData:!0}),Tt=function(){Yr.data=qr=!qr}):!bm&&Pi&&Pi.resolve?(ki=Pi.resolve(void 0),ki.constructor=Pi,Pn=gn(ki.then,ki),Tt=function(){Pn(_i)}):Gr?Tt=function(){En.nextTick(_i)}:(Hr=gn(Hr,dt),Tt=function(){Hr(_i)}),Ps=function(i){wi.head||Tt(),wi.add(i)}}var ym=Ps,Tm=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},Zs=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},Em=le,Dt=Em.Promise,rl=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",$m=rl,Pm=lr,km=!$m&&!Pm&&typeof window=="object"&&typeof document=="object",wm=le,Xt=Dt,_m=se,Am=Ro,Rm=Yo,Im=pe,Nm=km,Cm=rl,zr=mo,kn=Xt&&Xt.prototype,Dm=Im("species"),ks=!1,sl=_m(wm.PromiseRejectionEvent),Om=Am("Promise",function(){var i=Rm(Xt),e=i!==String(Xt);if(!e&&zr===66||!(kn.catch&&kn.finally))return!0;if(!zr||zr<51||!/native code/.test(i)){var t=new Xt(function(n){n(1)}),r=function(n){n(function(){},function(){})},s=t.constructor={};if(s[Dm]=r,ks=t.then(function(){})instanceof r,!ks)return!0}return!e&&(Nm||Cm)&&!sl}),li={CONSTRUCTOR:Om,REJECTION_EVENT:sl,SUBCLASSING:ks},Ot={},wn=ft,Lm=TypeError,xm=function(i){var e,t;this.promise=new i(function(r,s){if(e!==void 0||t!==void 0)throw Lm("Bad Promise constructor");e=r,t=s}),this.resolve=wn(e),this.reject=wn(t)};Ot.f=function(i){return new xm(i)};var Bm=De,zi=lr,Je=le,ui=Pe,Mm=Ys,Vm=Ws,Fm=wp,Um=ft,ws=se,jm=Ke,Hm=Rp,Gm=Ko,al=el.set,ea=ym,qm=Tm,Ym=Zs,zm=il,nl=Eo,_s=Dt,ta=li,ol=Ot,ur="Promise",ll=ta.CONSTRUCTOR,Wm=ta.REJECTION_EVENT;ta.SUBCLASSING;var Wr=nl.getterFor(ur),Qm=nl.set,Jm=_s&&_s.prototype,$t=_s,Qr=Jm,ul=Je.TypeError,As=Je.document,ia=Je.process,Rs=ol.f,Km=Rs,Xm=!!(As&&As.createEvent&&Je.dispatchEvent),dl="unhandledrejection",Zm="rejectionhandled",_n=0,cl=1,ev=2,ra=1,hl=2,Ai,An,tv,fl=function(i){var e;return jm(i)&&ws(e=i.then)?e:!1},pl=function(i,e){var t=e.value,r=e.state==cl,s=r?i.ok:i.fail,n=i.resolve,o=i.reject,l=i.domain,d,u,c;try{s?(r||(e.rejection===hl&&rv(e),e.rejection=ra),s===!0?d=t:(l&&l.enter(),d=s(t),l&&(l.exit(),c=!0)),d===i.promise?o(ul("Promise-chain cycle")):(u=fl(d))?ui(u,d,n,o):n(d)):o(t)}catch(h){l&&!c&&l.exit(),o(h)}},ml=function(i,e){i.notified||(i.notified=!0,ea(function(){for(var t=i.reactions,r;r=t.get();)pl(r,i);i.notified=!1,e&&!i.rejection&&iv(i)}))},vl=function(i,e,t){var r,s;Xm?(r=As.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),Je.dispatchEvent(r)):r={promise:e,reason:t},!Wm&&(s=Je["on"+i])?s(r):i===dl&&qm("Unhandled promise rejection",t)},iv=function(i){ui(al,Je,function(){var e=i.facade,t=i.value,r=Rn(i),s;if(r&&(s=Ym(function(){zi?ia.emit("unhandledRejection",t,e):vl(dl,e,t)}),i.rejection=zi||Rn(i)?hl:ra,s.error))throw s.value})},Rn=function(i){return i.rejection!==ra&&!i.parent},rv=function(i){ui(al,Je,function(){var e=i.facade;zi?ia.emit("rejectionHandled",e):vl(Zm,e,i.value)})},Pt=function(i,e,t){return function(r){i(e,r,t)}},wt=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=ev,ml(i,!0))},Is=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw ul("Promise can't be resolved itself");var r=fl(e);r?ea(function(){var s={done:!1};try{ui(r,e,Pt(Is,s,i),Pt(wt,s,i))}catch(n){wt(s,n,i)}}):(i.value=e,i.state=cl,ml(i,!1))}catch(s){wt({done:!1},s,i)}}};ll&&($t=function(e){Hm(this,Qr),Um(e),ui(Ai,this);var t=Wr(this);try{e(Pt(Is,t),Pt(wt,t))}catch(r){wt(t,r)}},Qr=$t.prototype,Ai=function(e){Qm(this,{type:ur,done:!1,notified:!1,parent:!1,reactions:new zm,rejection:!1,state:_n,value:void 0})},Ai.prototype=Mm(Qr,"then",function(e,t){var r=Wr(this),s=Rs(Gm(this,$t));return r.parent=!0,s.ok=ws(e)?e:!0,s.fail=ws(t)&&t,s.domain=zi?ia.domain:void 0,r.state==_n?r.reactions.add(s):ea(function(){pl(s,r)}),s.promise}),An=function(){var i=new Ai,e=Wr(i);this.promise=i,this.resolve=Pt(Is,e),this.reject=Pt(wt,e)},ol.f=Rs=function(i){return i===$t||i===tv?new An(i):Km(i)});Bm({global:!0,constructor:!0,wrap:!0,forced:ll},{Promise:$t});Vm($t,ur,!1,!0);Fm(ur);var sv=pe,Sl=sv("iterator"),bl=!1;try{var av=0,In={next:function(){return{done:!!av++}},return:function(){bl=!0}};In[Sl]=function(){return this},Array.from(In,function(){throw 2})}catch(i){}var nv=function(i,e){if(!e&&!bl)return!1;var t=!1;try{var r={};r[Sl]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch(s){}return t},ov=Dt,lv=nv,uv=li.CONSTRUCTOR,gl=uv||!lv(function(i){ov.all(i).then(void 0,function(){})}),dv=De,cv=Pe,hv=ft,fv=Ot,pv=Zs,mv=Js,vv=gl;dv({target:"Promise",stat:!0,forced:vv},{all:function(e){var t=this,r=fv.f(t),s=r.resolve,n=r.reject,o=pv(function(){var l=hv(t.resolve),d=[],u=0,c=1;mv(e,function(h){var f=u++,p=!1;c++,cv(l,t,h).then(function(v){p||(p=!0,d[f]=v,--c||s(d))},n)}),--c||s(d)});return o.error&&n(o.value),r.promise}});var Sv=De,bv=li.CONSTRUCTOR,Nn=Dt;Nn&&Nn.prototype;Sv({target:"Promise",proto:!0,forced:bv,real:!0},{catch:function(i){return this.then(void 0,i)}});var gv=De,yv=Pe,Tv=ft,Ev=Ot,$v=Zs,Pv=Js,kv=gl;gv({target:"Promise",stat:!0,forced:kv},{race:function(e){var t=this,r=Ev.f(t),s=r.reject,n=$v(function(){var o=Tv(t.resolve);Pv(e,function(l){yv(o,t,l).then(r.resolve,s)})});return n.error&&s(n.value),r.promise}});var wv=De,_v=Pe,Av=Ot,Rv=li.CONSTRUCTOR;wv({target:"Promise",stat:!0,forced:Rv},{reject:function(e){var t=Av.f(this);return _v(t.reject,void 0,e),t.promise}});var Iv=Xe,Nv=Ke,Cv=Ot,yl=function(i,e){if(Iv(i),Nv(e)&&e.constructor===i)return e;var t=Cv.f(i),r=t.resolve;return r(e),t.promise},Dv=De,Ov=ht,Lv=go,xv=Dt,Bv=li.CONSTRUCTOR,Mv=yl,Vv=Ov("Promise"),Fv=!Bv;Dv({target:"Promise",stat:!0,forced:Lv},{resolve:function(e){return Mv(Fv&&this===Vv?xv:this,e)}});var Uv=De,Ns=Dt,jv=ye,Hv=ht,Gv=se,qv=Ko,Cn=yl,Yv=Ns&&Ns.prototype,zv=!!Ns&&jv(function(){Yv.finally.call({then:function(){}},function(){})});Uv({target:"Promise",proto:!0,real:!0,forced:zv},{finally:function(i){var e=qv(this,Hv("Promise")),t=Gv(i);return this.then(t?function(r){return Cn(e,i()).then(function(){return r})}:i,t?function(r){return Cn(e,i()).then(function(){throw r})}:i)}});var Wv=ht,Tl=Wv,Qv=Tl,Jv=Qv("Promise","finally"),Kv=Jv,Xv=Kv,Zv=Xv,eS=Zv,dr=eS,_t;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(_t||(_t={}));var At=(i,e=0,t=_t.OFFSET_P)=>{switch(t){case _t.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case _t.PLAYBACK_SHIFT:{if(e===0)return i;const r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}default:a.assertNever(t)}return i},P=(i,e,t=!1)=>{const r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};exports.VideoQuality=void 0;(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"})(exports.VideoQuality||(exports.VideoQuality={}));const $e={[exports.VideoQuality.Q_144P]:{width:256,height:144},[exports.VideoQuality.Q_240P]:{width:428,height:240},[exports.VideoQuality.Q_360P]:{width:640,height:360},[exports.VideoQuality.Q_480P]:{width:856,height:480},[exports.VideoQuality.Q_720P]:{width:1280,height:720},[exports.VideoQuality.Q_1080P]:{width:1920,height:1080},[exports.VideoQuality.Q_1440P]:{width:2560,height:1440},[exports.VideoQuality.Q_2160P]:{width:3840,height:2160},[exports.VideoQuality.Q_4320P]:{width:7680,height:4320}},Ui=(i,e)=>$e[i].height>$e[e].height,tS=(i,e)=>$e[i].height>=$e[e].height,Zt=(i,e)=>$e[i].height<$e[e].height,iS=(i,e)=>$e[i].height<=$e[e].height,rS=i=>i.sort((e,t)=>e===t?0:e===exports.VideoQuality.INVARIANT?1:t===exports.VideoQuality.INVARIANT?-1:Zt(e,t)?1:-1)[0],sS=Object.keys($e).sort((i,e)=>Zt(i,e)?-1:1),pt=({width:i,height:e})=>{const t=Math.min(i,e),r=Math.max(i,e);return sS.find(s=>{const n=$e[s];return n.width>=r&&n.height>=t})},aS=i=>$e[i].height,Wi=i=>i===exports.VideoQuality.INVARIANT;class Q{constructor(e){this.transitionStarted$=new a.Subject,this.transitionEnded$=new a.Subject,this.transitionUpdated$=new a.Subject,this.forceChanged$=new a.Subject,this.stateChangeStarted$=a.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=a.merge(this.transitionEnded$,this.forceChanged$),this.state=e}setState(e){const t=this.transition,r=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:r,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,r=this.state;r===e||a.isNonNullable(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:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}const nS=i=>{switch(i){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return a.assertNever(i)}};var L;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(L||(L={}));const oS=5,lS=5,uS=500,Dn=7e3;class dS{constructor(e){this.subscription=new a.Subscription,this.loadMediaTimeoutSubscription=new a.Subscription,this.videoState=new Q(L.STOPPED),this.syncPlayback=()=>{const r=this.videoState.getState(),s=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${r}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){r!==L.STOPPED&&(this.videoState.startTransitionTo(L.STOPPED),this.stop());return}if(!s){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===C.Requested&&r!==L.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(r){case L.PLAYING:case L.PAUSED:case L.READY:break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:a.assertNever(r)}break}case exports.PlaybackState.PLAYING:{switch(r){case L.PLAYING:break;case L.PAUSED:this.videoState.startTransitionTo(L.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case L.READY:this.videoState.startTransitionTo(L.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:a.assertNever(r)}break}case exports.PlaybackState.PAUSED:{switch(r){case L.PLAYING:this.videoState.startTransitionTo(L.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case L.PAUSED:break;case L.READY:this.videoState.startTransitionTo(L.PAUSED),this.videoState.setState(L.PAUSED);break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:a.assertNever(r)}break}default:a.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(nS(e.format)),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 a.Subscription;this.subscription.add(e),this.subscription.add(a.merge(this.videoState.stateChangeStarted$.pipe(a.map(s=>`stateChangeStarted$ ${JSON.stringify(s)}`)),this.videoState.stateChangeEnded$.pipe(a.map(s=>`stateChangeEnded$ ${JSON.stringify(s)}`))).subscribe(s=>this.log({message:`[videoState] ${s}`})));const t=(s,n)=>this.subscription.add(s.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const s=new a.Subject;e.add(s.pipe(a.debounce(uS)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(o=>{this.logRemoteEvent(o);const l=o.value;this.params.output.position$.next(l),(this.params.desiredState.seekState.getState().state===C.Applying||Math.abs(l-n)>oS)&&s.next(l),n=l})),e.add(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemotePause():this.handleRemotePlay()}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),s=>{this.logRemoteEvent(s);const{remotePlayer:n}=this.params.connection,o=s.value,l=this.params.output.isBuffering$.getValue(),d=o===chrome.cast.media.PlayerState.BUFFERING;switch(l!==d&&this.params.output.isBuffering$.next(d),o){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&n.duration-n.currentTime<lS&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(this.params.desiredState.playbackState,exports.PlaybackState.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:a.assertNever(o)}}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({volume:s.value})}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({muted:s.value})});const r=a.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));t(r,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(L.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(L.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:C.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===L.PAUSED||e===L.PLAYING)&&(this.videoState.setState(L.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===L.PLAYING||e===L.PAUSED)&&(this.videoState.setState(L.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===L.READY&&this.videoState.setState(L.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===exports.PlaybackState.READY&&P(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==L.STOPPED&&this.videoState.setState(L.STOPPED)}handleRemoteVolumeChange(e){var t,r;const s=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:s.volume,muted:(r=e.muted)!==null&&r!==void 0?r:s.muted};(n.volume!==s.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const r=this.params.source;let s,n,o;switch(e){case exports.VideoFormat.MPEG:{const c=r[e];a.assertNonNullable(c);const h=rS(Object.keys(c));a.assertNonNullable(h);const f=c[h];a.assertNonNullable(f),s=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=r[e];a.assertNonNullable(c),s=c.url,n="application/x-mpegurl",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:{const c=r[e];a.assertNonNullable(c),s=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS_LIVE:{const c=r[e];a.assertNonNullable(c),s=At(c.url),n="application/x-mpegurl",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const c="Unsupported format for Chromecast",h=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:a.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:h}),h}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}const l=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:s,n);l.contentUrl=s,l.streamType=o,l.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:d,subtitle:u}=this.params.meta;return a.isNonNullable(d)&&(l.metadata.title=d),a.isNonNullable(u)&&(l.metadata.subtitle=u),l}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const r=this.params.desiredState.seekState.getState();return r.state===C.Applying||r.state===C.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),r=new Promise((s,n)=>{this.loadMediaTimeoutSubscription.add(a.timeout(Dn).subscribe(()=>n(`timeout(${Dn})`)))});dr(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===C.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},s=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${s}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:a.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:s})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}function J(i,e,t,r){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function l(c){try{u(r.next(c))}catch(h){o(h)}}function d(c){try{u(r.throw(c))}catch(h){o(h)}}function u(c){c.done?n(c.value):s(c.value).then(l,d)}u((r=r.apply(i,e||[])).next())})}function R(i){return this instanceof R?(this.v=i,this):new R(i)}function Ee(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(i,e||[]),s,n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(f){r[f]&&(s[f]=function(p){return new Promise(function(v,m){n.push([f,p,v,m])>1||l(f,p)})})}function l(f,p){try{d(r[f](p))}catch(v){h(n[0][3],v)}}function d(f){f.value instanceof R?Promise.resolve(f.value.v).then(u,c):h(n[0][2],f)}function u(f){l("next",f)}function c(f){l("throw",f)}function h(f,p){f(p),n.shift(),n.length&&l(n[0][0],n[0][1])}}class On{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;const r=this.listeners[e];for(let s=0,n=r.length;s<n;s++)if(r[s].callback===t){r.splice(s,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const r=this.listeners[e.type].slice();for(let s=0,n=r.length;s<n;s++){const o=r[s];try{o.callback.call(this,e)}catch(l){Promise.resolve().then(()=>{throw l})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class El extends On{constructor(){super(),this.listeners||On.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 $l=class{constructor(){Object.defineProperty(this,"signal",{value:new El,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(s){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 r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(s){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&($l.prototype[Symbol.toStringTag]="AbortController",El.prototype[Symbol.toStringTag]="AbortSignal");function Pl(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 cS(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=i;if(!Pl({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||s)&&(n=function(u,c){let h;c&&c.signal&&(h=c.signal,delete c.signal);const f=new t(u,c);return h&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),f},n.prototype=t.prototype);const o=e;return{fetch:(d,u)=>{const c=n&&n.prototype.isPrototypeOf(d)?d.signal:u?u.signal:void 0;if(c){let h;try{h=new DOMException("Aborted","AbortError")}catch(p){h=new Error("Aborted"),h.name="AbortError"}if(c.aborted)return Promise.reject(h);const f=new Promise((p,v)=>{c.addEventListener("abort",()=>v(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,o(d,u)])}return o(d,u)},Request:n}}const cr=Pl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),kl=cr?cS({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Rt=cr?kl.fetch:window.fetch;cr?kl.Request:window.Request;const lt=cr?$l:window.AbortController,zt=i=>i.range?i.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class ei{constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){var t;const{url:r}=e.request,s=(t=this.dashJsRequestQueue.get(r))!==null&&t!==void 0?t:[];s.push(e),this.dashJsRequestQueue.set(r,s)}executeNextRequests(){return J(this,void 0,void 0,function*(){for(const[e,t]of this.dashJsRequestQueue.entries()){const r=this.activeRequests.get(e);if(r){t.length&&this.onBigRequestProgress(r);const s=t[0];if(!s||!s.request.range)continue;const[n,o]=zt(s.request);if(n>=r.from&&o<=r.to)continue;this.activeRequests.delete(e)}if(t.length){const s=this.sendBigRequest(e,t.map(({request:n})=>n));this.activeRequests.set(e,s)}}})}abort(e){var t;if(e){const{request:r}=e,s=((t=this.dashJsRequestQueue.get(r.url))!==null&&t!==void 0?t:[]).includes(e),n=this.activeRequests.get(r.url);s&&n&&n.abortController.abort()}else for(const{abortController:r}of this.activeRequests.values())r.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const r=t.map(zt),s=r[0][0];let n=r[0][1];for(let f=1;f<r.length&&n<this.params.minDataSize;f++){const p=r[f][1];p-s<=2*this.params.minDataSize&&(n=Math.max(n,p))}s===0?n=Math.max(n,s+this.params.minInitSize):n=Math.max(n,s+this.params.minDataSize);const o=new URL(e,location.href);o.searchParams.append("bytes",`${s}-${n}`);const l=o.toString(),d=new lt,u=d.signal,c={url:e,from:s,to:n,loaded:0,data:null,abortController:d};u.addEventListener("abort",()=>this.onBigRequestAbort(c));const h=f=>{var p,v;throw(v=(p=this.params).onError)===null||v===void 0||v.call(p,{id:"BigRequestParsing",category:a.ErrorCategory.PARSER,message:"Error parsing response data",thrown:f}),f};return Rt(l,{signal:u}).then(f=>{var p,v,m;if(c.response=f,!f.ok||!f.body){this.onBigRequestError(c);return}const[S,b]=f.body.tee();(v=(p=this.params).onDownloadStream)===null||v===void 0||v.call(p,b);const y=S.getReader(),w=parseInt((m=f.headers.get("Content-Length"))!==null&&m!==void 0?m:"",10)||n-s+1;c.data=new ArrayBuffer(w);const T=new Uint8Array(c.data),E=({done:_,value:F})=>J(this,void 0,void 0,function*(){_?this.onBigRequestProgress(c):F&&(T.set(F,c.loaded),c.loaded+=F.byteLength,this.onBigRequestProgress(c),yield y==null?void 0:y.read().then(E,ei.suppressStreamErrors).catch(h))});y==null||y.read().then(E,ei.suppressStreamErrors).catch(h)},ei.suppressAbort).catch(f=>this.onBigRequestError(c,f)),c}onBigRequestProgress({url:e,from:t,to:r,loaded:s,data:n,response:o}){var l,d,u,c,h,f,p,v;if(!this.activeRequests.has(e)||!n)return;const m=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const S of m){const{request:b}=S,[y,w]=zt(b),T=y>=t&&w<=t+s,E=t>=y&&t+s<w,_=n.slice(y-t,Math.min(w-t+1,s));if((T||E)&&(b.requestStartDate=(d=b.requestStartDate)!==null&&d!==void 0?d:new Date,b.firstByteDate=(u=b.firstByteDate)!==null&&u!==void 0?u:new Date,b.bytesLoaded=_.byteLength,b.bytesTotal=r-t),T){b.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((c=this.dashJsRequestQueue.get(e))!==null&&c!==void 0?c:[]).filter(O=>O!==S)),(h=S.success)===null||h===void 0||h.call(S,_,"",e);const F=o?Array.from(o.headers.entries()).map(([O,I])=>`${O}: ${I}`).join(`\r
|
|
7
|
+
`):"";(f=this.dashMetrics)===null||f===void 0||f.addHttpRequest(b,e,(p=o==null?void 0:o.status)!==null&&p!==void 0?p:200,F,[])}else E&&((v=S.progress)===null||v===void 0||v.call(S,{loaded:s,total:r-t,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:t,to:r},s){var n,o,l,d;if((o=(n=this.params).onError)===null||o===void 0||o.call(n,{id:"BigRequest",category:a.ErrorCategory.NETWORK,message:"Download error",thrown:s}),!this.activeRequests.has(e))return;const u=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const c of u){const[h,f]=zt(c.request);(h>=t&&h<r||f>t&&f<=r)&&((d=c==null?void 0:c.error)===null||d===void 0||d.call(c,c.request,String(s)))}if(this.activeRequests.delete(e),s)throw s}onBigRequestAbort({url:e,from:t,to:r}){var s,n;if(!this.activeRequests.has(e))return;const o=(s=this.dashJsRequestQueue.get(e))!==null&&s!==void 0?s:[];for(const l of o){const[d,u]=zt(l.request);(d>=t&&d<r||u>t&&u<=r)&&((n=l==null?void 0:l.abort)===null||n===void 0||n.call(l,l.request))}this.activeRequests.delete(e)}static suppressAbort(e){if(!(e instanceof DOMException)||!(e.name==="AbortError"||e.code===20))throw e}static suppressStreamErrors(){}}class Qi{constructor(e,t,r){this.baseLoader=e,this.config=r,this.bigRequest=t,t.setMetrics(r.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(Qi.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;Qi.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const hS=(i,e)=>t=>({create:r=>{const s=i(t).create(r);return new Qi(s,e,r)}}),fS=(i,e)=>{const t=new ei(e);return i.extend("SchemeLoaderFactory",function(){const{parent:r}=this,s=r.getLoader;return{getLoader:n=>{const o=s(n);return hS(o,t)}}},!0),()=>t.destroy()};var pS=i=>{let e,t=!1,r=!1;i.on("playbackTimeUpdated",({timeToEnd:s})=>{r=s<=3,t&&r&&(e==null||e())}),i.extend("MediaSourceController",function(){const{parent:s}=this,n=s.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&r&&(e==null||e())}}},!0)},mS=i=>{const e=new a.ValueSubject(1/0),t=new a.Subject,r=new a.ValueSubject(void 0),s=new a.ValueSubject(void 0);let n=NaN,o=!1;const l=()=>{n=Date.now(),o=!1},d=c=>{var h,f,p,v,m;const S=oi(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(w=>w.split(": ")));if("x-playback-duration"in S||"x-playback-duration-millis"in S){const w=parseInt((h=c.getResponseHeader("X-Playback-Duration"))!==null&&h!==void 0?h:"",10),T=parseInt((f=c.getResponseHeader("X-Playback-Duration-Millis"))!==null&&f!==void 0?f:"",10),E=(p=T!=null?T:w*1e3)!==null&&p!==void 0?p:NaN;a.isNonNullable(E)&&!isNaN(E)&&e.next(E)}const b=(v=S["x-delivery-type"])!==null&&v!==void 0?v:exports.HttpConnectionType.HTTP1,y=(m={1:!0,0:!1}[S["x-reused"]])!==null&&m!==void 0?m:void 0;r.next(b),s.next(y)},u=c=>{c.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return i.extend("XHRLoader",function(){const{parent:c}=this,h=c.load.bind(c);return{load:function(f){if(f.request.type==="MPD"){const p=f.onload,v=f.progress;f.onload=function(...m){return d(this),p(...m)},f.progress=function(...m){return u(this),v(...m)},l()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:s,connectionType$:r}},It=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},vS=i=>i.extend("RequestModifier",()=>({modifyRequestURL:It}),!0),SS=i=>{i.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:r=>{if(r.request&&r.request.range){const[s,n]=r.request.range.split("-").map(l=>parseInt(l,10)),o=new URL(r.request.url,location.href);o.searchParams.append("bytes",`${s}-${n}`),r.request.url=o.toString(),r.request.range=void 0}t(r)}}},!0)};const Ne=(i,e,t,{equal:r=(o,l)=>o===l,changed$:s,onError:n}={})=>{const o=i.getState(),l=e(),d=a.isNullable(s),u=new a.Subscription;return s&&u.add(s.subscribe(c=>{const h=i.getState();r(c,h)&&i.setState(c)},n)),r(l,o)||(t(o),d&&i.setState(o)),u.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),d&&i.setState(c.to)},n)),u},mt=(i,e,t)=>Ne(e,()=>i.loop,r=>{a.isNonNullable(r)&&(i.loop=r)},{onError:t}),He=(i,e,t,r)=>Ne(e,()=>({muted:i.muted,volume:i.volume}),s=>{a.isNonNullable(s)&&(i.muted=s.muted,i.volume=s.volume)},{equal:(s,n)=>s===n||(s==null?void 0:s.muted)===(n==null?void 0:n.muted)&&(s==null?void 0:s.volume)===(n==null?void 0:n.volume),changed$:t,onError:r}),Ze=(i,e,t,r)=>Ne(e,()=>i.playbackRate,s=>{a.isNonNullable(s)&&(i.playbackRate=s)},{changed$:t,onError:r}),bS=i=>["__",i.language,i.label].join("|"),gS=(i,e)=>{if(i.id===e)return!0;const[t,r,s]=e.split("|");return i.language===r&&i.label===s};class Oe{constructor(){this.available$=new a.Subject,this.current$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.subscription=new a.Subscription,this.externalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const s=n=>{this.error$.next({id:"TextTracksManager",category:a.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Ne(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{a.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>a.isNonNullable(n)&&a.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},d)=>l===o[d].id),changed$:this.available$.pipe(a.map(n=>n.filter(({type:o})=>o==="external"))),onError:s})),this.subscription.add(Ne(t.currentTextTrack,()=>{if(this.video)return;const n=this.htmlTextTracksAsArray().find(({mode:o})=>o==="showing");return n&&this.htmlTextTrackToITextTrack(n).id},n=>this.select(n),{changed$:this.current$,onError:s})),this.subscription.add(Ne(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){a.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(a.fromEvent(e,"addtrack").subscribe(()=>{const r=this.current$.getValue();this.select(r)})),this.subscription.add(a.merge(a.fromEvent(e,"addtrack"),a.fromEvent(e,"removetrack"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),a.filterChanged((r,s)=>r.length===s.length&&r.every(({id:n},o)=>n===s[o].id))).subscribe(this.available$)),this.subscription.add(a.merge(a.fromEvent(e,"change"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),a.map(r=>r&&this.htmlTextTrackToITextTrack(r).id),a.filterChanged()).subscribe(this.current$));const t=r=>{var s,n;return this.applyCueSettings((n=(s=r.target)===null||s===void 0?void 0:s.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(a.fromEvent(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)===null||s===void 0||s.addEventListener("cuechange",t);const o=l=>{var d,u,c,h,f;const p=(u=(d=l.target)===null||d===void 0?void 0:d.cues)!==null&&u!==void 0?u:null;p&&p.length&&(this.applyCueSettings((h=(c=l.target)===null||c===void 0?void 0:c.cues)!==null&&h!==void 0?h:null),(f=l.target)===null||f===void 0||f.removeEventListener("cuechange",o))};(n=r.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(a.fromEvent(e,"removetrack").subscribe(r=>{var s;(s=r.track)===null||s===void 0||s.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const r of Array.from(e)){const s=r;a.isNonNullable(t.align)&&(s.align=t.align),a.isNonNullable(t.position)&&(s.position=t.position),a.isNonNullable(t.size)&&(s.size=t.size),a.isNonNullable(t.line)&&(s.line=t.line)}}htmlTextTracksAsArray(e=!1){a.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Oe.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:r}=e,s=e.id!==""?e.id:bS(e);return this.externalTracks.has(s)?{id:s,type:"external",language:t,label:r,url:this.externalTracks.get(s).url}:{id:s,type:"internal",language:t,label:r}}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(r=>r.id===t)).forEach(t=>this.detach(t))}select(e){a.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))a.isNonNullable(e)&&gS(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){a.assertNonNullable(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){a.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e);t&&this.video.removeChild(t),this.externalTracks.delete(e)}}var Ge=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 sa{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 wl=()=>{const{userAgent:i}=window.navigator;return!/chrome/i.test(i)&&/webkit|safari|khtml/i.test(i)};const Cs=3;class yS{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,r=this._source.buffered.length;t<r;t++){let s=this._source.buffered.start(t);const n=this._source.buffered.end(t);s>e&&s-e<Cs&&(s=e),this._buffer.push({from:s,to:n,i:t})}return this._buffer.sort(function(t,r){return t.from-r.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const r=this.getNext(e);if(r&&r.from-e.to<(t||Cs))return r}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,r){this._buffer.forEach(({from:s,to:n})=>{const o=s>=e&&s<t,l=n>=e&&n<t;o&&l||(o?r(t,n):l?r(s,e):s<e&&n>t?(r(t,n),r(s,e)):r(s,n))})}destroy(){this._buffer=[]}}var _l=(i,e,t=Cs)=>{let r=0,s=0;for(let n=0;n<i.length;n++){const o=i.start(n),l=i.end(n);if(o<=e&&e<=l){if(r=o,s=l,!t)return{from:r,to:s};for(let d=n-1;d>=0;d--)i.end(d)+t>=r&&(r=i.start(d));for(let d=n+1;d<i.length;d++)i.start(d)-t<=s&&(s=i.end(d))}}return{from:r,to:s}};const qe=i=>{const e=p=>a.fromEvent(i,p).pipe(a.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],r=a.merge(...t.map(p=>a.fromEvent(i,p))).pipe(a.map(p=>p.type==="ended"?i.readyState<2:i.readyState<3),a.filterChanged()),s=a.merge(a.fromEvent(i,"progress"),a.fromEvent(i,"timeupdate")).pipe(a.map(()=>_l(i.buffered,i.currentTime))),n=wl()?a.combine({play:e("play").pipe(a.once()),playing:e("playing")}).pipe(a.mapTo(void 0)):e("playing"),o=a.fromEvent(i,"volumechange").pipe(a.map(()=>({muted:i.muted,volume:i.volume}))),l=a.fromEvent(i,"ratechange").pipe(a.map(()=>i.playbackRate)),d=a.fromEvent(i,"error").pipe(a.filter(()=>Boolean(i.error||i.played.length)),a.map(()=>{var p;const v=i.error;return{id:v?`MediaError#${v.code}`:"HtmlVideoError",category:a.ErrorCategory.VIDEO_PIPELINE,message:v?v.message:"Error event from HTML video element",thrown:(p=i.error)!==null&&p!==void 0?p:void 0}})),u=a.fromEvent(i,"timeupdate").pipe(a.map(()=>i.currentTime)),c=new a.Subject,h=.3;let f;return u.subscribe(p=>{i.loop&&a.isNonNullable(f)&&a.isNonNullable(p)&&f>=i.duration-h&&p<=h&&c.next(f),f=p}),{playing$:n,pause$:e("pause").pipe(a.filter(()=>!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$:u,durationChange$:a.fromEvent(i,"durationchange").pipe(a.map(()=>i.duration)),isBuffering$:r,currentBuffer$:s,volumeState$:o,playbackRateState$:l}},aa=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var TS=De,ES=Ms,$S=qs,PS=Gs;TS({target:"Array",proto:!0},{at:function(e){var t=ES(this),r=$S(t),s=PS(e),n=s>=0?s:r+s;return n<0||n>=r?void 0:t[n]}});var kS=Tl,wS=kS("Array","at"),_S=wS,AS=_S,RS=AS,IS=RS,xe=IS;let na=!1,Be={};const NS=i=>{na=i},CS=()=>{Be={}},DS=i=>{i(Be)},Ri=(i,e)=>{var t;na&&(Be.meta=(t=Be.meta)!==null&&t!==void 0?t:{},Be.meta[i]=e)};class Ie{constructor(e){this.name=e}next(e){var t,r;if(!na)return;Be.series=(t=Be.series)!==null&&t!==void 0?t:{};const s=(r=Be.series[this.name])!==null&&r!==void 0?r:[];s.push([Date.now(),e]),Be.series[this.name]=s}}const OS=new Ie("best_bitrate"),LS=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class xS{constructor(){this.history={}}recordSelection(e){this.history[e.id]=a.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const di=(i,{container:e,throughput:t,tuning:r,limits:s,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:d,history:u})=>{var c,h,f,p;const v=r.usePixelRatio&&(c=window.devicePixelRatio)!==null&&c!==void 0?c:1,m=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*v*r.containerSizeFactor,height:e.height*v*r.containerSizeFactor},S=m&&pt(m),b=r.considerPlaybackRate&&a.isNonNullable(l)?l:1,y=i.filter(N=>!Wi(N.quality)).sort((N,A)=>Ui(N.quality,A.quality)?-1:1),w=(h=xe(y,-1))===null||h===void 0?void 0:h.quality,T=(f=xe(y,0))===null||f===void 0?void 0:f.quality,E=a.isNullable(s)||a.isNonNullable(s.min)&&a.isNonNullable(s.max)&&Zt(s.max,s.min)||a.isNonNullable(s.min)&&T&&Ui(s.min,T)||a.isNonNullable(s.max)&&w&&Zt(s.max,w),_=b*LS(o!=null?o:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),O=y.filter(N=>{const A=S?Zt(N.quality,S):!0,G=a.isNonNullable(t)&&isFinite(t)&&a.isNonNullable(N.bitrate)?t-n>=N.bitrate*_:!0,K=r.lazyQualitySwitch&&a.isNonNullable(r.minBufferToSwitchUp)&&d&&!Wi(d.quality)&&(o!=null?o:0)<r.minBufferToSwitchUp&&Ui(N.quality,d.quality),te=E||(a.isNullable(s.max)||iS(N.quality,s.max))&&(a.isNullable(s.min)||tS(N.quality,s.min));return A&&G&&!K&&te})[0];O&&O.bitrate&&OS.next(O.bitrate);const I=(p=O!=null?O:y[Math.ceil((y.length-1)/2)])!==null&&p!==void 0?p:i[0],U=I&&u&&u.history[I.id]&&a.now()-u.history[I.id]<=r.trackCooldown&&(!u.last||I.id!==u.last.id);if(I!=null&&I.id&&u&&!U&&u.recordSelection(I),U&&(u!=null&&u.last)){const N=u.last;return u==null||u.recordSwitch(N),N}return u==null||u.recordSwitch(I),I};var de=i=>new URL(i).hostname;const BS=300,Ji=(i,e=BS)=>new a.Observable(t=>{const{width:r,height:s}=i.getBoundingClientRect();if(t.next({width:r,height:s}),!window.ResizeObserver)return;const n=new ResizeObserver(uu(o=>{const l=o[0];if(!l)return;let d,u;l.contentBoxSize&&l.contentBoxSize[0]?(u=l.contentBoxSize[0].blockSize,d=l.contentBoxSize[0].inlineSize):l.contentRect&&(d=l.contentRect.width,u=l.contentRect.height),a.isNonNullable(d)&&a.isNonNullable(u)&&t.next({width:d,height:u})},e));return n.observe(i),()=>n.disconnect()}),MS=5e3,Wt={};var x;(function(i){i.DOWNLOADING_LIB="downloading_lib",i.STOPPED="stopped",i.STREAM_INITIALIZED="stream_initialized",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(x||(x={}));const re=(i,e)=>new a.Observable(t=>{const r=s=>t.next(s);return i.on(e,r),()=>i.off(e,r)});class VS{constructor(e){this.subscription=new a.Subscription,this.videoState=new Q(x.DOWNLOADING_LIB),this.textTracksManager=new Oe,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new a.ValueSubject(void 0),this.maxSeekBackTime$=new a.ValueSubject(1/0),this.availableFrom$=new a.ValueSubject(void 0),this.elementSize$=new a.ValueSubject(void 0),this.liveOffset=new sa,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState(),o=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===x.DOWNLOADING_LIB||t===x.STREAM_INITIALIZED))switch((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===C.Requested&&t!==x.STOPPED&&r!==exports.PlaybackState.STOPPED&&(o?this.seek(n.position-this.liveOffset.getTotalPausedTime()):this.seek(n.position)),r){case exports.PlaybackState.STOPPED:{switch(t){case x.STOPPED:break;case x.PLAYING:case x.PAUSED:case x.READY:this.stop();break;default:a.assertNever(t)}break}case exports.PlaybackState.READY:{switch(t){case x.STOPPED:this.prepare();break;case x.PLAYING:case x.PAUSED:case x.READY:break;default:a.assertNever(t)}break}case exports.PlaybackState.PLAYING:{switch(t){case x.PLAYING:break;case x.PAUSED:o&&(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 x.READY:this.play();break;case x.STOPPED:this.prepare();break;default:a.assertNever(t)}break}case exports.PlaybackState.PAUSED:{switch(t){case x.PLAYING:this.pause(),this.liveOffset.pause();break;case x.PAUSED:break;case x.READY:this.videoState.setState(x.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case x.STOPPED:this.prepare();break;default:a.assertNever(t)}break}default:a.assertNever(r)}},this.video=Ge(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=s=>{var n;e||this.params.output.error$.next({id:s==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:a.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${(n=s==null?void 0:s.toString)===null||n===void 0?void 0:n.call(s)}`,thrown:s}),e=!0},r=window.setTimeout(()=>t("timeout"),MS);dr(import("dashjs/dist/dash.mediaplayer.min.js").then(s=>{e||(Wt.MediaPlayer=s.MediaPlayer,Wt.Debug=s.Debug,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){a.assertNonNullable(Wt.MediaPlayer,"dashjs not loaded"),a.assertNonNullable(Wt.Debug,"dashjs not loaded"),this.player=Wt.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?aa(t.frameRate+""):void 0),!0)),(this.params.format===exports.VideoFormat.DASH_WEBM||this.params.format===exports.VideoFormat.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=fS(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&&SS(this.player),pS(this.player),this.params.tuning.requestQuick&&vS(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(x.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,r=m=>{e.error$.next({id:"DashIFProvider",category:a.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:m})},s=(m,S)=>this.subscription.add(m.subscribe(S,r));s(Ji(this.video),this.elementSize$),s(re(this.player,"error").pipe(a.map(m=>{const S=typeof m.error=="object"?m.error.code:m.error,b=typeof m.error=="object"?m.error.message:void 0;return{id:`DashJS#${S}`,message:b}})),e.error$),s(re(this.player,"playbackError").pipe(a.map(m=>({id:"DashJSPlayback",message:m.error}))),e.error$);const n=re(this.player,"qualityChangeRendered").pipe(a.filter(({mediaType:m})=>m==="video"),a.map(({newQuality:m})=>{var S;return(S=this.videoTracks.find(({bitrateInfo:b})=>b.qualityIndex===m))===null||S===void 0?void 0:S.track}));n.pipe(a.filter(a.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(a.filter(({to:m})=>m===x.STREAM_INITIALIZED),a.once()).subscribe(()=>{this.subscription.add(Ne(t.videoTrack,()=>{var m,S;const b=this.player.getQualityFor("video");return(S=(m=this.videoTracks.find(({bitrateInfo:y})=>y.qualityIndex===b))===null||m===void 0?void 0:m.track)===null||S===void 0?void 0:S.id},m=>{var S;if(a.isNullable(m))return;const b=(S=this.videoTracks.find(({track:y})=>y.id===m))===null||S===void 0?void 0:S.bitrateInfo;b&&this.player.setQualityFor("video",b.qualityIndex)},{changed$:n.pipe(a.map(m=>m==null?void 0:m.id)),onError:r}))},r)),this.subscription.add(Ne(t.autoVideoTrackSwitching,()=>{var m,S,b;return(b=(S=(m=this.player.getSettings().streaming)===null||m===void 0?void 0:m.abr)===null||S===void 0?void 0:S.autoSwitchBitrate)===null||b===void 0?void 0:b.video},m=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:m}}}}),{onError:r})),s(re(this.player,"bufferStateChanged").pipe(a.filter(({mediaType:m})=>m==="video"),a.map(({state:m})=>m==="bufferStalled")),e.isBuffering$),s(re(this.player,"fragmentLoadingStarted"),({mediaType:m,request:{url:S}})=>{var b,y;const w=this.player.getDashMetrics(),T=w.getLatestFragmentRequestHeaderValueByID(m,"X-Reused"),E=(b=w.getLatestFragmentRequestHeaderValueByID(m,"X-Delivery-Type"))!==null&&b!==void 0?b:exports.HttpConnectionType.HTTP1,_=(y={1:!0,0:!1}[T])!==null&&y!==void 0?y:void 0;this.params.output.httpConnectionType$.next(E),this.params.output.httpConnectionReused$.next(_),e.hostname$.next(de(S))}),s(re(this.player,"streamInitialized"),({streamInfo:{duration:m,manifestInfo:{isDynamic:S,availableFrom:b}}})=>{this.isLive$.next(S),this.availableFrom$.next(b.getTime()),S||e.duration$.next(m),this.videoTracks=[];const y=this.player.getQualityFor("video");let w;for(const T of this.player.getBitrateInfoListFor("video")){const E=T.qualityIndex.toString(10),_=pt(T),F=T.bitrate/1e3,O={width:T.width,height:T.height},I=this.frameRatesByFrameHeight[T.height];if(_){const U={id:E,quality:_,bitrate:F,size:O,fps:I};this.videoTracks.push({track:U,bitrateInfo:T}),T.qualityIndex===y&&(w=U)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:T})=>T)),w&&e.currentVideoTrack$.next(w),this.videoState.setState(x.STREAM_INITIALIZED),this.videoState.startTransitionTo(x.READY)}),s(re(this.player,"fragmentLoadingCompleted"),({request:m})=>{if(!m.requestEndDate||!m.firstByteDate||!m.bytesLoaded)return;const S=m.requestEndDate.getTime()-m.firstByteDate.getTime(),b=m.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(b,S)}),s(a.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const m=this.params.dependencies.throughputEstimator.throughput$.getValue(),S=di(this.videoTracks.map(({track:y})=>y),{container:this.elementSize$.getValue(),throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),b=this.videoTracks.find(({track:y})=>y===S);b!=null&&b.bitrateInfo&&this.player.setQualityFor("video",b==null?void 0:b.bitrateInfo.qualityIndex,!1)}),s(a.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(a.filter(a.isNonNullable))}).pipe(a.filter(({isLive:m})=>m),a.map(({maxSeekBackTime:m})=>-m/1e3)),this.params.output.duration$);const o=re(this.player,"playbackTimeUpdated").pipe(a.map(({time:m})=>m!=null?m:0));s(a.combine({availableFrom:this.availableFrom$.pipe(a.filter(a.isNonNullable)),currentTime:o}),({availableFrom:m,currentTime:S})=>this.params.output.liveTime$.next(m+S*1e3)),s(o.pipe(a.filter(()=>this.isLive$.getValue()===!1)),e.position$),s(re(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),s(re(this.player,"playbackEnded"),e.endedEvent$),s(re(this.player,"playbackProgress").pipe(a.map(()=>_l(this.video.buffered,this.video.currentTime))),e.currentBuffer$),s(re(this.player,"playbackPlaying"),()=>{this.videoState.setState(x.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)}),s(re(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(x.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),s(re(this.player,"playbackPaused"),()=>{this.videoState.setState(x.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)}),s(re(this.player,"canPlay"),()=>{var m;((m=this.videoState.getTransition())===null||m===void 0?void 0:m.to)===x.READY&&this.videoState.setState(x.READY)}),s(this.isLive$,e.isLive$),s(Ji(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const l=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));s(l,this.syncPlayback);const{playbackDuration$:d,ping$:u,connectionType$:c,connectionReused$:h}=mS(this.player);s(c,this.params.output.httpConnectionType$),s(h,this.params.output.httpConnectionReused$),s(d,this.maxSeekBackTime$),s(u.pipe(a.once()),e.firstBytesEvent$),s(re(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&s(a.combine({isLive:this.isLive$,isShort:e.duration$.pipe(a.map(m=>m<60))}),({isLive:m,isShort:S})=>{const b=!m&&S;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:b}}})}),s(o.pipe(a.filter(m=>m>this.params.tuning.insufficientBufferRuleMargin),a.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(re(this.player,"manifestLoaded").pipe(a.once()).subscribe(()=>{this.subscription.add(re(this.player,"playbackPlaying").pipe(a.once(),a.mapTo(void 0)).subscribe(e.firstFrameEvent$,r))},r)),this.subscription.add(mt(this.video,t.isLooped,r));const{volumeState$:f,looped$:p,playbackRateState$:v}=qe(this.video);this.subscription.add(He(this.video,t.volume,f,r)),this.subscription.add(f.subscribe(e.volume$,r)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(Ze(this.video,t.playbackRate,v,r))}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(x.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(x.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,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3);const s=At(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,_t.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(x.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(x.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(r){}this.video.remove(),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var ci=i=>{switch(i){case"mobile":return exports.VideoQuality.Q_144P;case"lowest":return exports.VideoQuality.Q_240P;case"low":return exports.VideoQuality.Q_360P;case"sd":case"medium":return exports.VideoQuality.Q_480P;case"hd":case"high":return exports.VideoQuality.Q_720P;case"fullhd":case"full":return exports.VideoQuality.Q_1080P;case"quadhd":case"quad":return exports.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return exports.VideoQuality.Q_2160P}},et=i=>J(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(r){return i.muted=!1,console.warn(r),!1}}return!0});function oe(){return a.now()}function Al(i){return oe()-i}function Ln(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,s=o=>r.test(o);return{resolve:(o,l,d=!1)=>{s(o)||(o.startsWith("/")||(o="/"+o),o=t+o);let u=o.indexOf("?")>-1?"&":"?";return d&&(o+=u+"lowLat=1",u="&"),l&&(o+=u+"_rnd="+Math.floor(999999999*Math.random())),o}}}function FS(i,e,t){const r=(...s)=>{t.apply(null,s),i.removeEventListener(e,r)};i.addEventListener(e,r)}function ji(i,e,t,r){const s=window.XMLHttpRequest;let n,o,l,d=!1,u=0,c,h,f=!1,p="arraybuffer",v=7e3,m=2e3,S=()=>{if(d)return;a.assertNonNullable(c);const A=Al(c);let G;if(A<m){G=m-A,setTimeout(S,G);return}m*=2,m>v&&(m=v),o&&o.abort(),o=new s,_()};const b=A=>(n=A,N),y=A=>(h=A,N),w=()=>(p="json",N),T=()=>{if(!d){if(--u>=0){S(),r&&r();return}d=!0,h&&h(),t&&t()}},E=A=>(f=A,N),_=()=>{c=oe(),o=new s,o.open("get",i);let A=0,G,K=0;const te=()=>(a.assertNonNullable(c),Math.max(c,Math.max(G||0,K||0)));if(n&&o.addEventListener("progress",$=>{const D=oe();n.updateChunk&&$.loaded>A&&(n.updateChunk(te(),$.loaded-A),A=$.loaded,G=D)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>T())),o.addEventListener("load",()=>{if(d)return;a.assertNonNullable(o);const $=o.status;if($>=200&&$<300){if(o.response.byteLength&&n){const D=o.response.byteLength-A;D&&n.updateChunk&&n.updateChunk(te(),D)}h&&h(),o&&e(o.response)}else T()}),o.addEventListener("error",()=>{T()}),f){const $=()=>{a.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(K=oe(),o.removeEventListener("readystatechange",$))};o.addEventListener("readystatechange",$)}return o.responseType=p,o.send(),N},N={withBitrateReporting:b,withParallel:E,withJSONResponse:w,withRetryCount:A=>(u=A,N),withRetryInterval:(A,G)=>(a.isNonNullable(A)&&(m=A),a.isNonNullable(G)&&(v=G),N),withTimeout:A=>(l=A,N),withFinally:y,send:_,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return N}const US=100,jS=2e3,HS=500;let GS=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,r){return{start:e,end:t,bytes:r}}_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-HS;if(t-e>jS){let r=0,s=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)r+=n.end-n.start,s+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,l=n.end-n.start;r+=o;const d=n.bytes*o/l;s+=d,n.start=t,n.bytes-=d}}}if(s>0&&r>0){const n=s*8/(r/1e3);return this._updateRate(n),this.logger(`rate updated, new=${Math.round(n/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(s)}/${Math.round(r)} 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,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>US&&(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 qS{constructor(e,t,r,s,n){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=r,this.MAX_PARALLEL_REQUESTS=s,this.logger=n}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 r=oe(),s=d=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=d,e._errorCB?e._errorCB(d):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=d=>{e._complete=1,e._responseData=d,e._downloadTime=oe()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(d,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},o=()=>{e._finallyCB&&e._finallyCB()},l=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=ji(t,n,()=>s("error"),l),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(o),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=oe()}_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=oe();if(Object.keys(this.activeRequests).length>=e)return!1;const r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!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,r,s){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=r,o._retryCB=s,o._finallyCB=n._finallyCB,o._error||o._complete?(this._removeFromActive(e),setTimeout(()=>{o._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(o._responseData,o._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(o._errorMsg)),n._finallyCB&&n._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const l=this.pendingQueue.indexOf(e);l!==-1&&this.pendingQueue.splice(l,1),this.logger(`Request not prefetched, starting new request, url=${e}${l===-1?"":"; removed pending"}`),this._sendRequest(n,e)}},n._cb=t,n._errorCB=r,n._retryCB=s,n.abort=function(){n.request&&n.request.abort()},n.withFinally=o=>(n._finallyCB=o,n),n}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Ii=1e4,Ni=3,YS=300,zS=2e3,WS=6e4,QS=10,JS=1,KS=500;class XS{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.requiredPlaybackRate=1,this.bitrate=0,this.manifest=[],this.sourceBuffer=0,this.bufferStates=[],this.sourceJitter=-1,this.params=e,this.chunkRateEstimator=new GS(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Ln(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setRequiredPlaybackRate(e){this.requiredPlaybackRate=e}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],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=Ln(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 r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-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 r;Boolean(e.error)&&!this.destroyed&&(t(`Video element error: ${(r=e.error)===null||r===void 0?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.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,r=t.buffered.length;let s;r!==0&&(s=t.buffered.start(r-1),t.currentTime<s&&(e("Fixup stall"),t.currentTime=s))}_selectQuality(e){const{videoElement:t}=this.params;let r,s,n;const o=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let l=0;l<this.manifest.length;++l)n=this.manifest[l],!(this.maxAutoQuality&&n.video.height>this.maxAutoQuality)&&(n.bitrate<e&&o>Math.min(n.video.height,n.video.width)?(!s||n.bitrate>s.bitrate)&&(s=n):(!r||r.bitrate>n.bitrate)&&(r=n));return s||r}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||a.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:r,videoElement:s,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),s.src=URL.createObjectURL(this.mediaSource),s.playbackRate=this.requiredPlaybackRate,this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,s.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{FS(s,"progress",()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),n({name:"playing"})):o()})};o()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new qS(Ni,Ii,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:r,playerCallback:s}=this.params;let n=!1,o=null,l=null,d=null,u=null,c=!1;const h=()=>{const T=n&&(!c||c===this.rep);return T||t("Not running!"),T},f=(T,E,_)=>{d&&d.abort(),d=ji(this.urlResolver.resolve(T,!1),E,_,()=>this._retryCallback()).withTimeout(Ii).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ni).withFinally(()=>{d=null}).send()},p=(T,E,_)=>{a.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),E,_,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},v=T=>{const E=r.playbackRate;r.playbackRate!==T&&(t(`Playback rate switch: ${E}=>${T}`),r.playbackRate=T)},m=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),S()},S=()=>{if(!this.lowLatency)v(this.requiredPlaybackRate);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){v(1);return}const _=oe()-6e4;let F=0;for(let I=0;I<this.bufferStates.length;I++){const U=this.bufferStates[I];T=Math.min(T,U.buf),U.ts<_&&F++}this.bufferStates.splice(0,F),t(`update playback rate; minBuffer=${T} drop=${F} jitter=${this.sourceJitter}`);let O=T-JS;this.sourceJitter>=0?O-=this.sourceJitter/2:this.sourceJitter-=1,O>3?v(1.15):O>1?v(1.1):O>.3?v(1.01):v(1)}},b=T=>{let E;const _=()=>E&&E.start?E.start.length:0,F=$=>E.start[$]/1e3,O=$=>E.dur[$]/1e3,I=$=>E.fragIndex+$,U=($,D)=>({chunkIdx:I($),startTS:F($),dur:O($),discontinuity:D}),N=()=>{let $=0;if(E&&E.dur){let D=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,z=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ee=D;this.sourceJitter>1&&(ee+=this.sourceJitter-1);let ie=E.dur.length-1;for(;ie>=0&&(ee-=E.dur[ie],!(ee<=0));--ie);$=Math.min(ie,E.dur.length-1-z),$=Math.max($,0)}return U($,!0)},A=$=>{const D=_();if(!(D<=0)){if(a.isNonNullable($)){for(let z=0;z<D;z++)if(F(z)>$)return U(z)}return N()}},G=$=>{const D=_(),z=$?$.chunkIdx+1:0,ee=z-E.fragIndex;if(!(D<=0)){if(!$||ee<0||ee-D>QS)return t(`Resync: offset=${ee} bChunks=${D} chunk=`+JSON.stringify($)),N();if(!(ee>=D))return U(z-E.fragIndex,!1)}},K=($,D,z)=>{u&&u.abort(),u=ji(this.urlResolver.resolve($,!0,this.lowLatency),D,z,()=>this._retryCallback()).withTimeout(Ii).withRetryCount(Ni).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:($,D)=>{K(T,z=>{if(!h())return;E=z;const ee=Boolean(E.lowLatency);ee!==this.lowLatency&&m(ee);let ie=0;for(let ce=0;ce<E.dur.length;++ce)ie+=E.dur[ce];ie>0&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ie/E.dur.length)),s({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,$(A(D))},()=>this._handleNetworkError())},nextChunk:G}},y=()=>{n=!1,l&&l.abort(),d&&d.abort(),u&&u.abort(),a.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:T=>{const{videoElement:E,logger:_}=this.params;let F=b(e.jidxUrl),O,I,U,N,A=0,G,K,te;const $=()=>{G&&(clearTimeout(G),G=void 0);const j=Math.max(KS,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ae=A+j,ue=oe(),me=Math.min(1e4,ae-ue);A=ue;const tt=()=>{u||h()&&F.seek(()=>{h()&&(A=oe(),D(),$())})};me>0?G=window.setTimeout(()=>{this.paused?$():tt()},me):tt()},D=()=>{let j;for(;j=F.nextChunk(N);)N=j,ke(j);const ae=F.nextChunk(U);if(ae){if(U&&ae.discontinuity){_("Detected discontinuity; restarting playback"),this.paused?$():(y(),this._initPlayerWith(e));return}ce(ae)}else $()},z=(j,ae)=>{if(!h()||!this.sourceBuffer)return;let ue,me,tt;const we=Ye=>{window.setTimeout(()=>{h()&&z(j,ae)},Ye)};if(this.sourceBuffer.updating)_("Source buffer is updating; delaying appendBuffer"),we(100);else{const Ye=oe(),it=E.currentTime;!this.paused&&E.buffered.length>1&&K===it&&Ye-te>500&&(_("Stall suspected; trying to fix"),this._fixupStall()),K!==it&&(K=it,te=Ye);const xt=this._getBufferSizeSec();if(xt>30)_(`Buffered ${xt} seconds; delaying appendBuffer`),we(2e3);else try{this.sourceBuffer.appendBuffer(j),this.videoPlayStarted?(this.bufferStates.push({ts:Ye,buf:xt}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ae&&ae()}catch(vt){if(vt.name==="QuotaExceededError")_("QuotaExceededError; delaying appendBuffer"),tt=this.sourceBuffer.buffered.length,tt!==0&&(ue=this.sourceBuffer.buffered.start(0),me=it,me-ue>4&&this.sourceBuffer.remove(ue,me-3)),we(1e3);else throw vt}}},ee=()=>{I&&O&&(_([`Appending chunk, sz=${I.byteLength}:`,JSON.stringify(U)]),z(I,function(){I=null,D()}))},ie=j=>e.fragUrlTemplate.replace("%%id%%",j.chunkIdx),ce=j=>{h()&&p(ie(j),(ae,ue)=>{if(h()){if(ue/=1e3,I=ae,U=j,o=j.startTS,ue){const me=Math.min(10,j.dur/ue);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*me:me}ee()}},()=>this._handleNetworkError())},ke=j=>{h()&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ie(j),!1)))},Lt=j=>{h()&&(e.cachedHeader=j,z(j,()=>{O=!0,ee()}))};n=!0,F.seek(j=>{if(h()){if(A=oe(),!j){$();return}N=j,!a.isNullable(T)||j.startTS>T?ce(j):(U=j,D())}},T),e.cachedHeader?Lt(e.cachedHeader):f(e.headerUrl,Lt,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>o},c}_switchToQuality(e){const{logger:t,playerCallback:r}=this.params;let s;e.bitrate!==this.bitrate&&(this.rep&&(s=this.rep.getTimestampSec(),a.isNonNullable(s)&&(s+=.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,a.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(s),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return a.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,r=h=>{if(!this.autoQuality)return;let f,p,v;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(p=this._getBufferSizeSec(),v=h/this.bitrate,p>10&&v>.8||p>15&&v>.5||p>20&&v>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}f=this._selectQuality(h),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${h}`)},n=(()=>({updateChunk:(f,p)=>{const v=oe();if(this.chunkRateEstimator.addInterval(f,v,p)){const S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:v-f,speed:S}),!0}},get:()=>{const f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}}))();let o=-1/0,l,d=!0;const u=()=>{let h=n.get();if(h&&l&&this.autoQuality){if(d&&h>l&&Al(o)<3e4)return;r(h)}d=this.autoQuality};return{updateChunk:(h,f)=>{const p=n.updateChunk(h,f);return p&&u(),p},notifySwitch:h=>{const f=oe();h<l&&(o=f),l=h}}}_fetchManifest(e,t,r){this.manifestRequest=ji(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Ii).withRetryCount(Ni).withRetryInterval(YS,zS).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;et(t).then(r=>{r||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:r,videoElement:s}=this.params,n=o=>{const l=[];return o!=null&&o.length?(o.forEach((d,u)=>{d.video&&s.canPlayType(d.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(d.codecs)&&(d.index=u,l.push(d))}),l.sort(function(d,u){return d.video&&u.video?u.video.height-d.video.height:u.bitrate-d.bitrate}),l):(this.params.playerCallback({name:"error",type:"partial_metadata"}),[])};this.manifest=n(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({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))},WS))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var B;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(B||(B={}));const ZS=[B.PAUSED,B.PLAYING,B.READY],eb=[B.PAUSED,B.PLAYING,B.READY];class tb{constructor(e){this.subscription=new a.Subscription,this.videoState=new Q(B.STOPPED),this.representations$=new a.ValueSubject([]),this.textTracksManager=new Oe,this.maxSeekBackTime$=new a.ValueSubject(1/0),this.zeroTime$=new a.ValueSubject(void 0),this.liveOffset=new sa,this._dashCb=s=>{var n,o,l,d;switch(s.name){case"buffering":{const u=s.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${s.type}`,category:a.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=s.manifest,c=[];for(const h of u){const f=(n=h.name)!==null&&n!==void 0?n:h.index.toString(10),p=(o=ci(h.name))!==null&&o!==void 0?o:pt(h.video),v=h.bitrate/1e3,m=Object.assign({},h.video);if(!p)continue;const S={id:f,quality:p,bitrate:v,size:m};c.push({track:S,representation:h})}this.representations$.next(c),this.params.output.availableVideoTracks$.next(c.map(({track:h})=>h)),((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===B.MANIFEST_READY&&this.videoState.setState(B.MANIFEST_READY);break}case"qualitySwitch":{const u=s.quality,c=(d=this.representations$.getValue().find(({representation:h})=>h===u))===null||d===void 0?void 0:d.track;this.params.output.hostname$.next(new URL(u.headerUrl,this.params.source.url).hostname),a.isNonNullable(c)&&this.params.output.currentVideoTrack$.next(c);break}case"bandwidth":{const{size:u,duration:c}=s;this.params.dependencies.throughputEstimator.addRawSpeed(u,c);break}case"index":{this.maxSeekBackTime$.next(s.shiftDuration),this.zeroTime$.next(s.zeroTime);break}}},this.syncPlayback=()=>{var s;const n=this.videoState.getState(),o=this.videoState.getTransition(),l=this.params.desiredState.playbackState.getState(),d=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${n}; videoTransition: ${JSON.stringify(o)}; desiredPlaybackState: ${l}; seekState: ${JSON.stringify(u)};`}),l===exports.PlaybackState.STOPPED){n!==B.STOPPED&&(this.videoState.startTransitionTo(B.STOPPED),this.dash.destroy(),this.video.setAttribute("src",""),this.video.load(),this.videoState.setState(B.STOPPED));return}if(!o){if(eb.includes(n)){const c=(s=this.params.desiredState.videoTrack.getTransition())===null||s===void 0?void 0:s.to;a.isNonNullable(c)&&this.setVideoTrack(c);const h=this.params.desiredState.autoVideoTrackSwitching.getTransition();h&&this.setAutoQuality(h.to)}if((d==null?void 0:d.to)!==exports.PlaybackState.PAUSED&&u.state===C.Requested&&ZS.includes(n)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(n){case B.STOPPED:this.videoState.startTransitionTo(B.MANIFEST_READY),this.dash.attachSource(At(this.params.source.url));return;case B.MANIFEST_READY:this.videoState.startTransitionTo(B.READY),this.prepare();break;case B.READY:if(l===exports.PlaybackState.PAUSED)this.videoState.setState(B.PAUSED);else if(l===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(B.PLAYING);const c=d==null?void 0:d.from;c&&c===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(B.PAUSED)})}return;case B.PLAYING:l===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(B.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case B.PAUSED:l===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(B.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(B.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return a.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=s=>{e.output.error$.next({id:"DashLiveProvider",category:a.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:s})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(s)}`})}),this.video=Ge(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(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const r=qe(this.video);this.subscription.add(r.canplay$.subscribe(()=>{var s;((s=this.videoState.getTransition())===null||s===void 0?void 0:s.to)===B.READY&&this.videoState.setState(B.READY)},t)).add(r.pause$.subscribe(()=>{this.videoState.setState(B.PAUSED)},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===C.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(B.PLAYING)},t)).add(r.error$.subscribe(this.params.output.error$)).add(r.playbackRateState$.pipe(a.filterChanged()).subscribe(s=>this.dash.setRequiredPlaybackRate(s))).add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(s=>-s/1e3)).subscribe(this.params.output.duration$)).add(a.combine({zeroTime:this.zeroTime$.pipe(a.filter(a.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:s,position:n})=>this.params.output.liveTime$.next(s+n*1e3),t)).add(a.combine({position:this.params.output.position$,duration:this.params.output.duration$}).subscribe(({position:s,duration:n})=>{s<n+a.ACTIVE_LIVE_VALID_DELAY&&(this.params.desiredState.playbackRate.setState(1),this.dash.setRequiredPlaybackRate(1))})).add(this.params.output.position$.subscribe(s=>{s>-a.ACTIVE_LIVE_VALID_DELAY&&(this.params.desiredState.playbackRate.setState(1),this.dash.setRequiredPlaybackRate(1))})).add(mt(this.video,this.params.desiredState.isLooped,t)).add(He(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ze(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:s}})=>{const n=s&&aS(s);this.dash.setMaxAutoQuality(n)})).add(this.videoState.stateChangeEnded$.subscribe(s=>{var n;switch(s.to){case B.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case B.MANIFEST_READY:case B.READY:((n=this.params.desiredState.playbackState.getTransition())===null||n===void 0?void 0:n.to)===exports.PlaybackState.READY&&this.params.desiredState.playbackState.setState(exports.PlaybackState.READY);break;case B.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case B.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(s.to)}},t)).add(a.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const e=new XS({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},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,r,s,n,o;const l=this.representations$.getValue(),d=(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(),u=(s=(r=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||r===void 0?void 0:r.to)!==null&&s!==void 0?s:this.params.desiredState.autoVideoTrackSwitching.getState(),c=!u&&a.isNonNullable(d)?d:(n=di(l.map(({track:f})=>f),{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||n===void 0?void 0:n.id,h=(o=l.find(({track:f})=>f.id===c))===null||o===void 0?void 0:o.representation;a.assertNonNullable(h,"Representations missing"),this.dash.startPlay(h,u),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(c),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(u)}setVideoTrack(e){var t;const r=(t=this.representations$.getValue().find(({track:s})=>s.id===e))===null||t===void 0?void 0:t.representation;a.assertNonNullable(r,`No such representation ${e}`),this.dash.switchByName(r.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,r=t<=this.maxSeekBackTime$.getValue()?t:0;this.params.output.position$.next(e/1e3),this.liveOffset.resetTo(r),this.dash.reinit(At(this.params.source.url,r))}}var Rl=i=>{var e,t;const r=i.get("X-Delivery-Type"),s=i.get("X-Reused"),n=r===null?exports.HttpConnectionType.HTTP1:(e=r)!==null&&e!==void 0?e:void 0,o=s===null?void 0:(t={1:!0,0:!1}[s])!==null&&t!==void 0?t:void 0;return{type:n,reused:o}},ot=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){const s=i.start(r)*1e3,n=i.end(r)*1e3;s<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const ib=i=>{const e=document.createElement("a");return e.href=i,e.origin},rb=i=>{const e=document.createElement("a");return e.href=i,e.host};class Il{constructor(e,t=[],r,s,n,o){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=r,this._progressCb=s,this._headersCb=n,this._errorCb=o,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,r,s,n,o,l,d,u;if(a.assertNonNullable(this._xhr),((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(r=this._errorCb)===null||r===void 0||r.call(this,`Http${(s=this._xhr)===null||s===void 0?void 0:s.status}`,`XHR response code ${(n=this._xhr)===null||n===void 0?void 0:n.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const c=oi(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(h=>h.split(":").map(f=>f.trim())));(o=this._headersCb)===null||o===void 0||o.call(this,new Headers(c))}else this._xhr.readyState===4?(l=this._completeCb)===null||l===void 0||l.call(this,this._xhr.response):this._xhr.readyState===3&&((d=this._progressCb)===null||d===void 0||d.call(this,this._xhr.response))}catch(c){throw(u=this._errorCb)===null||u===void 0||u.call(this,"XHR2CallbackError",`xhr2 callback threw ${String(c)}`,c),c}},this._xhr.onerror=()=>{var t;(t=this._xhr)===null||t===void 0||t.abort(),this._retryTimeout=window.setTimeout(()=>{var r;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(r=this._errorCb)===null||r===void 0||r.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let s;this._failoverIndex>=this._failoverHosts.length?(s=this._url,this._failoverIndex=0):(s=this._url.replace(rb(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",s,!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 Ki{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(r){if(r.name==="QuotaExceededError"){this._isFull=!0;const s=this._sourceBuffer.buffered;let n=0;for(let o=0,l=s.length;o<l;o++)n+=s.end(o)-s.start(o);n&&(this._maxBufferDuration=Math.round(n))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",r),r}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,r,s,n,o,l){this.abort(()=>{let d=0;const u=Date.now();let c=0,h=0,f=0;const p=m=>{s(Ki._str2ua(m.substr(d))),d=m.length};let v=e.baseURL+"&bytes="+t+"-"+r;this._params.requestQuic&&(v=It(v)),this._lastXhr=new Il(v,e.failoverHosts,m=>{this._lastXhr=void 0,p(m);const S=Date.now()-u;this._params.onBandwidthChange({size:m.length,duration:S,speed:8*m.length/(S/1e3)}),this._onDashCallback("loading",{size:m.length,done:!0}),n==null||n()},m=>{if(m.length-d>l&&p(m),h===0){h=Date.now();return}f=m.length-c;const S=Date.now()-h;f>=100*1024&&S>=1e3&&(this._params.onBandwidthChange({size:f,duration:S,speed:8*f/(S/1e3)}),f=0,c=m.length,h=Date.now()),this._onDashCallback("loading",{size:m.length,done:!1})},o,(m,S,b)=>this._params.onError(m,S,b))})}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(r){throw this._params.onError("SourceBuffer","Source Buffer update error",r),r}};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=Ki._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 r=new Uint8Array(e.byteLength+t.byteLength);return r.set(e,0),r.set(t,e.byteLength),r}static _str2ua(e){const t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);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 sb{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)?)?$/,r=(l,d)=>{const u=l?parseFloat(l.replace(",",".")):NaN;return(isNaN(u)?0:u)*d},s=t.exec(e),n=(s==null?void 0:s[1])==="-"?-1:1,o={years:r(s==null?void 0:s[2],n),months:r(s==null?void 0:s[3],n),weeks:r(s==null?void 0:s[4],n),days:r(s==null?void 0:s[5],n),hours:r(s==null?void 0:s[6],n),minutes:r(s==null?void 0:s[7],n),seconds:r(s==null?void 0:s[8],n)};return o.hours*3600+o.minutes*60+o.seconds}getRepresentations(){return this._representations}attachSource(e,t){let r=e;this._config.REQUEST_QUIC&&(r=It(r)),new Il(r,t,s=>{this.attachManifest(s,t,ib(r))},void 0,s=>{this._params.onResponseHeaders(s)},(s,n,o)=>this._params.onError(s,n,o))}attachManifest(e,t,r){const n=new DOMParser().parseFromString(e,"text/xml").documentElement,o=(u,c)=>{const h=u.attributes.getNamedItem(c);return h?h.value:null};this._duration=this._parseDurationFromISO8601(String(o(n,"mediaPresentationDuration")));const l=[],d=[];if(Array.prototype.forEach.call(n.getElementsByTagName("Representation"),u=>{var c,h,f,p,v,m,S,b,y,w,T,E,_,F,O,I,U,N,A;const G=u.getElementsByTagName("SegmentBase")[0],K=G&&o(G,"indexRange").split("-"),te=G&&G.getElementsByTagName("Initialization")[0],$=te&&o(te,"range").split("-");if(!$||!K){const ke=u.parentElement;if((ke==null?void 0:ke.getAttribute("contentType"))==="text"){const Lt=(c=u.getAttribute("id"))!==null&&c!==void 0?c:void 0,j=(r?r+"/":"")+((v=(p=(f=(h=u.getElementsByTagName("BaseURL"))===null||h===void 0?void 0:h[0])===null||f===void 0?void 0:f.childNodes)===null||p===void 0?void 0:p[0])===null||v===void 0?void 0:v.data),ae=(m=ke.getAttribute("lang"))!==null&&m!==void 0?m:void 0;j&&d.push({id:Lt,url:j,language:ae})}return}const D=.1,z=Number((S=u.attributes.getNamedItem("bandwidth"))===null||S===void 0?void 0:S.value),ee=(r?r+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ie;const ce=(y=(b=u.attributes.getNamedItem("frameRate"))===null||b===void 0?void 0:b.value)!==null&&y!==void 0?y:void 0;ie=ce?aa(ce):void 0,l.push({width:Number((w=u.attributes.getNamedItem("width"))===null||w===void 0?void 0:w.value),height:Number((T=u.attributes.getNamedItem("height"))===null||T===void 0?void 0:T.value),bandwidth:z,baseURL:ee,failoverHosts:t,indexFrom:Number(K[0]),indexTo:Number(K[1]),initFrom:Number($[0]),initTo:Number($[1]),codecs:(_=(E=u.attributes.getNamedItem("codecs"))===null||E===void 0?void 0:E.value)!==null&&_!==void 0?_:void 0,mimeType:(O=(F=u.attributes.getNamedItem("mimeType"))===null||F===void 0?void 0:F.value)!==null&&O!==void 0?O:void 0,fps:ie,bufferSize:D*z/8,bufferLength:D,name:(U=(I=u.attributes.getNamedItem("okQuality"))===null||I===void 0?void 0:I.value)!==null&&U!==void 0?U:void 0,id:(A=(N=u.attributes.getNamedItem("id"))===null||N===void 0?void 0:N.value)!==null&&A!==void 0?A:void 0})}),l.length)this._representations=l;else{this._onDashCallback("error");return}d.forEach(({id:u,language:c,url:h})=>{const f=document.createElement("track");f.setAttribute("src",h),u&&f.setAttribute("id",u),c&&f.setAttribute("srclang",c),this._video.appendChild(f)}),this._representations.sort((u,c)=>c.bandwidth-u.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 r=Date.now();this._stream.load(e,e.initFrom,e.indexTo,s=>{let n=e.initTo-e.initFrom+1;if(!s.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(s.buffer,0,n);const o=new DataView(s.buffer);n+=12;const l=o.getUint32(n+4,!1);n+=8;let d=o.getUint32(n,!1),u=o.getUint32(n+4,!1)+(e.indexTo+1);n+=8;const c=o.getUint16(n+2,!1);n+=4,e.refs=[];for(let f=0;f<c;f+=1){const p=u+(o.getUint32(n,!1)&2147483647),v=d+o.getUint32(n+4,!1);n+=12,e.refs.push({fromTime:d/l,toTime:v/l,fromOffset:u,toOffset:p-1}),u=p,d=v}const h=e.refs[e.refs.length-1];h.toTime-h.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,s=>{this._params.onResponseHeaders(s),this._params.onIdxRequestPing(Date.now()-r)},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 r=new t;let s,n;const o=()=>{const u=this._findRef(this._video.currentTime);if(!u||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const p=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),p)}const c=this._appendVector[String(u.fromTime)];c!==s&&(s=c,this._params.onRepresentationPlay(c));let h;if(this._findRef(u.toTime)){const p=this._buffer.getByTime(this._video.currentTime);if(!p){this._onDashCallback("buffering");return}h=p.to-this._video.currentTime,h<e.bufferLength&&(this._onDashCallback("buffering"),n!==p.to&&(n=p.to,window.setTimeout(()=>{try{const v=this._buffer.getNextWithGap(p);v&&(this._video.currentTime=v.from)}catch(v){throw this._params.onError("GapSyncError",`Seek Error ${String(v)}`,v),v}},h*1e3)))}},l=()=>{this._loopTimeout=window.setTimeout(()=>{try{o()}catch(u){throw this._params.onError("LoopError",`Dash Loop exception ${String(u)}`,u),u}l()},250)},d=()=>{if(!this._stream)try{const u=r.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Ki({mediaSource:r,sourceBuffer:u,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(u){throw this._params.onError("DashSourceOpen",`Source open exception ${String(u)}`,u),u}this._loadInitAndSidx(e),r.duration||(r.duration=this._duration),this._loopTimeout||l(),r.removeEventListener("sourceopen",d),r.removeEventListener("webkitsourceopen",d)};r.addEventListener("sourceopen",d,!1),r.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(r),this._video.addEventListener("waiting",()=>{const u=this._video&&this._video.played.length;u&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(u-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,r=!1,s=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const n=this._findRef(t);if(n){if(r){this._isLastRef(n)&&t>=n.toTime&&(t=n.fromTime);const o=this._findRef(this._video.currentTime),l=Math.abs(this._video.currentTime-t),d=s||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||n===o||l<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=d?t:n.fromTime}this._appendVector[String(n.fromTime)]=e,this._stream.load(e,n.fromOffset,n.toOffset,(o,l)=>this._stream.append(o,l),()=>{this._lastLoadOffset=n.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},o=>this._params.onResponseHeaders(o),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const r=this._buffer.getByTime(this._video.currentTime),s=this._findRef(this._video.currentTime);if(!r||!s){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(s.toTime<r.to+n){const o=this._findRef(s.toTime);o&&o.toTime<r.to+n?(this._buffer.smartRemove(s.fromTime-n,o.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(s.fromTime-n,s.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,s.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||a.isNullable(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const r=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!r)return;if(Array.isArray(r)&&r.length===0){this._params.onError("emptyrefs","Empty refs");return}let s;for(let n=0;n<r.length;n++){const o=r[n];if(o.fromTime<=e&&o.toTime>e)return o;o.fromTime>e&&(!s||o.fromTime<s.fromTime)&&(s=o)}if(!s){const n=r[r.length-1];if(e>n.toTime)return n}return s}_isLastRef(e){var t;const r=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!r)return!1;const s=r[r.length-1];return e.fromTime===s.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const r=this._video.buffered.start(t),s=this._video.buffered.end(t);if(e>r&&e<s)return Math.round(s*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var M;(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"})(M||(M={}));const ab=[M.PAUSED,M.PLAYING];class nb{constructor(e){this.videoState=new Q(M.STOPPED),this.subscription=new a.Subscription,this.representations$=new a.ValueSubject([]),this.currentRepresentation$=new a.ValueSubject(void 0),this.textTracksManager=new Oe,this.elementSize$=new a.ValueSubject(void 0),this.dashLiteEvents={idxRequestPing$:new a.Subject,responseHeaders$:new a.Subject,manifestReady$:new a.Subject,representationPlay$:new a.Subject,error$:new a.Subject},this.handleManifestReady=t=>{var r,s,n;const o=[];for(const l of t){const d=(s=(r=l.name)!==null&&r!==void 0?r:l.id)!==null&&s!==void 0?s:l.height.toString(10),u=(n=l.name&&ci(l.name))!==null&&n!==void 0?n:pt(l),c=l.bandwidth/1e3,h={width:l.width,height:l.height},f=l.fps;if(!u)continue;const p={id:d,quality:u,bitrate:c,size:h,fps:f};o.push({track:p,representation:l})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:l})=>l)),this.videoState.setState(M.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var r;const s=(r=this.representations$.getValue().find(({representation:n})=>n===t))===null||r===void 0?void 0:r.track;s&&(this.params.output.currentVideoTrack$.next(s),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(s.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return a.assertNonNullable(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${s}; seekState: ${JSON.stringify(o)};`}),s===exports.PlaybackState.STOPPED){t!==M.STOPPED&&(this.videoState.startTransitionTo(M.STOPPED),this.dash.destroy(),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(M.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!r)switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&o.state===C.Requested&&ab.includes(t)&&this.seek(o.position,o.forcePrecise),t){case M.STOPPED:this.videoState.startTransitionTo(M.MANIFEST_LOADED),this.prepare();return;case M.MANIFEST_LOADED:this.videoState.startTransitionTo(M.INITIAL_REPRESENTATION_SELECTED);return;case M.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(M.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case M.METADATA_LOADED:this.videoState.startTransitionTo(M.READY),this.dash.updateRefsForCurrentTime();return;case M.READY:s===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):s===exports.PlaybackState.PAUSED?(this.videoState.setState(M.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(M.PLAYING),this.playIfAllowed());return;case M.PLAYING:s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(M.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case M.PAUSED:s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(M.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),a.merge(this.videoState.stateChangeStarted$.pipe(a.map(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:r})=>{this.log({message:`[videoState change] ${r}: ${JSON.stringify(t)}`})}),this.video=Ge(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.source.type==="url"&&this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new yS(this.video),this.dash=new sb({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,r,s)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:r,thrown:s,category:a.ErrorCategory.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,r=l=>{e.error$.next({id:"DashProvider",category:a.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:l})},s=()=>{const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:l},n=qe(this.video),o=(l,d)=>this.subscription.add(l.subscribe(d,r));o(n.timeUpdate$,e.position$),o(n.durationChange$,e.duration$),o(n.ended$,e.endedEvent$),o(n.looped$,e.loopedEvent$),o(n.error$,e.error$),o(n.isBuffering$,e.isBuffering$),o(n.playing$,e.firstFrameEvent$),o(n.canplay$,e.canplay$),this.subscription.add(n.seeking$.subscribe(()=>{a.isNullable(this.params.desiredState.seekState.getState().state!==C.Applying)&&(this.videoState.getState()===M.PLAYING||this.videoState.getState()===M.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(mt(this.video,t.isLooped,r)),this.subscription.add(He(this.video,t.volume,n.volumeState$,r)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ze(this.video,t.playbackRate,n.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),o(Ji(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===M.READY&&this.videoState.setState(M.READY)},r)).add(n.pause$.subscribe(()=>{this.videoState.setState(M.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(M.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},r)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(M.METADATA_LOADED)},r)).add(n.currentBuffer$.subscribe(l=>{this.buffer.fill(),e.currentBuffer$.next(l)},r)).add(this.dashLiteEvents.error$.pipe(a.map(({id:l,message:d,thrown:u})=>({id:`DashLite_${l}`,category:a.ErrorCategory.WTF,message:d,thrown:u}))).subscribe(this.params.output.error$)).add(a.merge(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$,a.fromEvent(this.video,"progress")).pipe(a.map(()=>{var l,d,u;const c=this.currentRepresentation$.getValue(),h=this.representations$.getValue(),f=this.params.desiredState.autoVideoTrackSwitching.getTransition(),p=this.params.desiredState.videoTrack.getState(),v=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),m=this.elementSize$.getValue(),S=s();f&&this.params.desiredState.autoVideoTrackSwitching.setState(f.to);let b;if(!S&&a.isNonNullable(p))b=p;else{const y=ot(this.video.buffered,this.video.currentTime*1e3),w=S?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,T=Math.min(y/w,1);b=(d=di(h.map(({track:E})=>E),{container:m,throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:T,playbackRate:this.video.playbackRate,current:(l=h.find(({representation:E})=>E===c))===null||l===void 0?void 0:l.track}))===null||d===void 0?void 0:d.id}return a.isNonNullable(b)?(u=h.find(({track:y})=>y.id===b))===null||u===void 0?void 0:u.representation:void 0}),a.filterChanged()).subscribe(this.currentRepresentation$,r)).add(a.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(a.filter(l=>l.to===M.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(a.filter(a.isNonNullable))}).pipe(a.once()).subscribe(()=>this.videoState.setState(M.INITIAL_REPRESENTATION_SELECTED),r)).add(this.currentRepresentation$.pipe(a.filter(a.isNonNullable),a.filterChanged((l,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&s()?l.height<=d.height:l===d)).subscribe(l=>{const d=ot(this.video.buffered,this.video.currentTime*1e3),u=Math.min(d/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||u<=.5||!s())&&(this.dash.setQualityByRepresentation(l,!0),this.params.output.hostname$.next(de(l.baseURL)))},r)).add(this.dashLiteEvents.responseHeaders$.subscribe(l=>{const{type:d,reused:u}=Rl(l);this.params.output.httpConnectionType$.next(d),this.params.output.httpConnectionReused$.next(u)})).add(this.dashLiteEvents.idxRequestPing$.pipe(a.once(),a.mapTo(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(l=>this.params.dependencies.throughputEstimator.addRawRtt(l))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,r)).add(this.dashLiteEvents.representationPlay$.pipe(a.filter(a.isNonNullable)).subscribe(this.handleRepresentationPlay,r)).add(a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return a.assertNever(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){et(this.video).then(e=>{e||(this.videoState.setState(M.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}}var Se;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(Se||(Se={}));var Xi;(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"})(Xi||(Xi={}));var be;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(be||(be={}));var H;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(H||(H={}));var Nt;(function(i){i.MP4="mp4",i.WEBM="webm"})(Nt||(Nt={}));var xn=(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 ob=(i,e={})=>{const r=e.timeout||1,s=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-s-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-s))}})},1)},lb=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Bn=lb?ob:window.requestIdleCallback;var Jr,Kr;let Nl=!1;try{Nl=wl()&&parseInt((Kr=(Jr=navigator.userAgent.match(/Version\/(\d+)/))===null||Jr===void 0?void 0:Jr[1])!==null&&Kr!==void 0?Kr:"",10)<16}catch(i){console.error(i)}class ub{constructor(e){this.bufferFull$=new a.Subject,this.error$=new a.Subject,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const r=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!r),this.currentTask=null}this.queue.length&&this.pull()}catch(r){this.error$.next({id:"BufferTaskQueueUnknown",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:r})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return J(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(r=>{const s={operation:"append",data:e,signal:t,callback:r};this.queue.push(s),this.pull()})})}remove(e,t,r){return J(this,void 0,void 0,function*(){return r&&r.aborted?!1:new Promise(s=>{const n={operation:"remove",from:e,to:t,signal:r,callback:s};this.queue.unshift(n),this.pull()})})}abort(e){return J(this,void 0,void 0,function*(){return new Promise(t=>{let r;Nl&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(const{callback:s}of this.queue)s(!1);r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask)}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:r}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&r==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"&&r==="remove"||this.error$.next({id:`BufferTaskQueue:${r}`,category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:n}),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:a.assertNever(t)}}}var Mn=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};const Cl=new TextDecoder("ascii"),Dl=i=>{let e=0,t=i.getUint32(e);e+=4;const r=new DataView(i.buffer,i.byteOffset+e,4),s=Cl.decode(r);e+=4,t===0?t=1/0:t===1&&(e+=8,t=1/0);const n=Math.min(t,i.byteLength)-e,o=new DataView(i.buffer,i.byteOffset+e,n);return{id:s,size:t,contents:o}},db=i=>Cl.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",cb=i=>{const e=Dl(i),t=[];let r=0;const s=()=>{const p=e.contents.getUint32(r);return r+=4,p};if((s()&4278190080)!==0)throw new SyntaxError("Unsupported sidx version");s();const l=s(),d=s(),u=s(),c=s()&4294967295;let h=d/l*1e3,f=i.byteOffset+i.byteLength+u;for(let p=0;p<c;p++){const v=s(),m=v>>>31,S=v<<1>>>1,b=s();if(s(),m!==0)throw new Error("Unsupported multilevel sidx");const y=b/l*1e3;t.push({status:H.NONE,time:{from:h,to:h+y},byte:{from:f,to:f+S-1}}),h+=y,f+=S}return t},hb=i=>{let e=0,t=!1,r=!1;for(;e<=i.byteLength&&!t;){const s=new DataView(i.buffer,i.byteOffset+e);try{const n=Dl(s);if(r||(r=n.id==="mdat"),e+n.size<=i.byteLength)e+=n.size;else break}catch(n){t=!0}}return e>0&&e<=i.byteLength&&r?new DataView(i.buffer,i.byteOffset,e):null},fb={validateData:db,parseInit:()=>null,getIndexRange:()=>{},parseSegments:cb,parseFeedableSegmentChunk:hb};var g;(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"})(g||(g={}));var k;(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"})(k||(k={}));const Vn={[g.EBML]:{type:k.Master},[g.EBMLVersion]:{type:k.UnsignedInteger},[g.EBMLReadVersion]:{type:k.UnsignedInteger},[g.EBMLMaxIDLength]:{type:k.UnsignedInteger},[g.EBMLMaxSizeLength]:{type:k.UnsignedInteger},[g.DocType]:{type:k.String},[g.DocTypeVersion]:{type:k.UnsignedInteger},[g.DocTypeReadVersion]:{type:k.UnsignedInteger},[g.Void]:{type:k.Binary},[g.Segment]:{type:k.Master},[g.SeekHead]:{type:k.Master},[g.Seek]:{type:k.Master},[g.SeekID]:{type:k.Binary},[g.SeekPosition]:{type:k.UnsignedInteger},[g.Info]:{type:k.Master},[g.TimestampScale]:{type:k.UnsignedInteger},[g.Duration]:{type:k.Float},[g.Tracks]:{type:k.Master},[g.Chapters]:{type:k.Master},[g.Cluster]:{type:k.Master},[g.Timestamp]:{type:k.UnsignedInteger},[g.SilentTracks]:{type:k.Master},[g.SilentTrackNumber]:{type:k.UnsignedInteger},[g.Position]:{type:k.UnsignedInteger},[g.PrevSize]:{type:k.UnsignedInteger},[g.SimpleBlock]:{type:k.Binary},[g.BlockGroup]:{type:k.Master},[g.EncryptedBlock]:{type:k.Binary},[g.Attachments]:{type:k.Master},[g.Tags]:{type:k.Master},[g.Cues]:{type:k.Master},[g.CuePoint]:{type:k.Master},[g.CueTime]:{type:k.UnsignedInteger},[g.CueTrackPositions]:{type:k.Master},[g.CueTrack]:{type:k.UnsignedInteger},[g.CueClusterPosition]:{type:k.UnsignedInteger},[g.CueRelativePosition]:{type:k.UnsignedInteger},[g.CueDuration]:{type:k.UnsignedInteger},[g.CueBlockNumber]:{type:k.UnsignedInteger},[g.CueCodecState]:{type:k.UnsignedInteger},[g.CueReference]:{type:k.Master},[g.CueRefTime]:{type:k.UnsignedInteger}},Ol=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 r=Zi(i,t),s=r in Vn,n=s?Vn[r].type:k.Binary,o=i.getUint8(t);let l=0;o&128?l=1:o&64?l=2:o&32?l=3:o&16?l=4:o&8?l=5:o&4?l=6:o&2?l=7:o&1&&(l=8);const d=new DataView(i.buffer,i.byteOffset+t+1,l-1),u=((o&255>>l)<<(l-1)*8)+Zi(d),c=t+l;let h;return c+u>i.byteLength?h=new DataView(i.buffer,i.byteOffset+c):h=new DataView(i.buffer,i.byteOffset+c,u),{tag:s?r:"0x"+r.toString(16).toUpperCase(),type:n,tagHeaderSize:c,tagSize:c+u,value:h,valueSize:u}},Zi=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint16(0)<<8|i.getUint8(2);case 4:return i.getUint32(0);case 5:return i.getUint32(0)<<8|i.getUint8(4);case 6:return i.getUint32(0)<<16|i.getUint16(4);case 7:return i.getUint32(0)<<32|i.getUint16(4)<<8|i.getUint8(6);case 8:return i.getUint32(0)<<32|i.getUint32(4)}return 0},Me=(i,e)=>{switch(e){case k.SignedInteger:return i.getInt8(0);case k.UnsignedInteger:return Zi(i);case k.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case k.String:return new TextDecoder("ascii").decode(i);case k.UTF8:return new TextDecoder("utf-8").decode(i);case k.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case k.Master:return i;case k.Binary:return i;default:a.assertNever(e)}},hi=(i,e)=>{let t=0;for(;t<i.byteLength;){const r=new DataView(i.buffer,i.byteOffset+t),s=Ol(r);if(!e(s))return;s.type===k.Master&&hi(s.value,e),t=s.value.byteOffset-i.byteOffset+s.valueSize}},pb=i=>{if(i.getUint32(0)!==g.EBML)return!1;let e,t,r;const s=Ol(i);return hi(s.value,({tag:n,type:o,value:l})=>(n===g.EBMLReadVersion?e=Me(l,o):n===g.DocType?t=Me(l,o):n===g.DocTypeReadVersion&&(r=Me(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)},Ll=[g.Info,g.SeekHead,g.Tracks,g.Chapters,g.Cluster,g.Cues,g.Attachments,g.Tags],mb=[g.Timestamp,g.SilentTracks,g.SilentTrackNumber,g.Position,g.PrevSize,g.SimpleBlock,g.BlockGroup,g.EncryptedBlock],vb=i=>{let e,t,r,s,n=!1,o=!1,l=!1,d,u;return hi(i,({tag:c,type:h,value:f,valueSize:p})=>{if(c===g.SeekID){const v=Me(f,h);u=Zi(v)}else c!==g.SeekPosition&&(u=void 0);return c===g.Segment?(e=f.byteOffset,t=f.byteOffset+p):c===g.Info?n=!0:c===g.SeekHead?o=!0:c===g.TimestampScale?r=Me(f,h):c===g.Duration?s=Me(f,h):c===g.SeekPosition&&u===g.Cues?d=Me(f,h):n&&o&&Ll.includes(c)&&(l=!0),!l}),a.assertNonNullable(e,"Failed to parse webm Segment start"),a.assertNonNullable(t,"Failed to parse webm Segment end"),a.assertNonNullable(s,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(s/1e9*r*1e3),cuesSeekPosition:d}},Sb=i=>{if(a.isNullable(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},bb=(i,e)=>{let t=!1,r=!1;const s=l=>a.isNonNullable(l.time)&&a.isNonNullable(l.position),n=[];let o;return hi(i,({tag:l,type:d,value:u})=>{switch(l){case g.Cues:t=!0;break;case g.CuePoint:o&&s(o)&&n.push(o),o={};break;case g.CueTime:o&&(o.time=Me(u,d));break;case g.CueTrackPositions:break;case g.CueClusterPosition:o&&(o.position=Me(u,d));break;default:t&&Ll.includes(l)&&(r=!0)}return!(t&&r)}),o&&s(o)&&n.push(o),n.map((l,d)=>{const{time:u,position:c}=l,h=n[d+1];return{status:H.NONE,time:{from:u,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},gb=i=>{let e=0,t=!1;try{hi(i,r=>r.tag===g.Cluster?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):mb.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||(t=[g.SimpleBlock,g.BlockGroup,g.EncryptedBlock].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},yb={validateData:pb,parseInit:vb,getIndexRange:Sb,parseSegments:bb,parseFeedableSegmentChunk:gb};class Fn{constructor(e,t,r,s,{fetcher:n,tuning:o,getCurrentPosition:l,compatibilityMode:d=!1}){switch(this.onLastSegment$=new a.ValueSubject(!1),this.fullyBuffered$=new a.ValueSubject(!1),this.playingRepresentation$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.gaps=[],this.subscription=new a.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new lt,this.destroyAbortController=new lt,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=a.abortable(this.destroyAbortController.signal,function(u){return Ee(this,arguments,function*(){const c=this.representations.get(u);a.assertNonNullable(c,`Cannot find representation ${u}`),this.playingRepresentationId=u,this.downloadingRepresentationId=u,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${c.mime}; codecs="${c.codecs}"`),this.sourceBufferTaskQueue=new ub(this.sourceBuffer),this.subscription.add(a.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},v=>this.error$.next({id:"SegmentEjection",category:a.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:v}))),this.subscription.add(a.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:a.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(v=>{if(!this.sourceBuffer)return;const m=Math.min(this.bufferLimit,Mn(this.sourceBuffer.buffered)*.8);this.bufferLimit=m,this.pruneBuffer(this.getCurrentPosition(),v)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(v=>this.error$.next(v))),yield yield R(this.loadInit(c,"high",!0));const h=this.initData.get(c.id),f=this.segments.get(c.id);if(a.assertNonNullable(h,"No init buffer for starting representation"),a.assertNonNullable(f,"No segments for starting representation"),!(h instanceof ArrayBuffer))return yield R(void 0);let p=0;for(const v of f)v.time.from-p>0&&this.gaps.push({representation:c.id,from:p,to:v.time.from}),p=v.time.to;a.isNonNullable(c.duration)&&c.duration-p>0&&this.gaps.push({representation:c.id,from:p,to:c.duration}),yield yield R(this.sourceBufferTaskQueue.append(h,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId)})}.bind(this)),this.switchTo=a.abortable(this.destroyAbortController.signal,function(u){return Ee(this,arguments,function*(){if(u===this.downloadingRepresentationId||u===this.switchingToRepresentationId)return yield R(void 0);this.switchingToRepresentationId=u;const c=this.representations.get(u);a.assertNonNullable(c,`No such representation ${u}`);let h=this.initData.get(u);if(a.isNullable(h)?yield yield R(this.loadInit(c,"high",!1)):h instanceof Promise&&(yield yield R(h)),h=this.initData.get(u),!h||!(h instanceof ArrayBuffer)||!this.sourceBuffer)return yield R(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=u,this.abort(),yield yield R(this.sourceBufferTaskQueue.append(h,this.downloadAbortController.signal));const f=this.getCurrentPosition();a.isNonNullable(f)&&this.maintain(f)})}.bind(this)),this.fetcher=n,this.tuning=o,this.compatibilityMode=d,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=l,this.container=r,r){case Nt.MP4:this.containerParser=fb;break;case Nt.WEBM:this.containerParser=yb;break;default:a.assertNever(r)}this.initData=new Map(s.map(u=>[u.id,null])),this.segments=new Map,this.representations=new Map(s.map(u=>[u.id,u])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new lt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(a.isNullable(e)||a.isNullable(this.downloadingRepresentationId)||a.isNullable(this.playingRepresentationId)||a.isNullable(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(a.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;const s=r.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=ot(this.sourceBuffer.buffered,e),h=s?s.time.to+100:-1/0;s&&c>=s.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&Mn(this.sourceBuffer.buffered)>=this.bufferLimit){const u=ot(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<c);return}let l=[];if(!this.activeSegments.size&&(l=this.selectForwardBufferSegments(r,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&s)if(l.includes(s))u="high";else{const c=xe(l,0);c&&c.time.from-s.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}!this.preloadOnly&&!this.allInitsLoaded&&s&&s.status===H.FED&&!l.length&&ot(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=xe(r,-1);d&&d.status===H.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===d))}findSegmentStartTime(e){var t,r,s;const n=(r=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&r!==void 0?r:this.playingRepresentationId;if(!n)return;const o=this.segments.get(n);if(!o)return;const l=o.find(d=>d.time.from<=e&&d.time.to>=e);return(s=l==null?void 0:l.time.from)!==null&&s!==void 0?s: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,r){const s=e.findIndex(({status:h,time:{from:f,to:p}},v)=>(h===H.NONE||h===H.PARTIALLY_EJECTED)&&(f>r||f<=r&&p>=r||v===0&&r===0)&&(this.preloadOnly&&f<=r+Math.min(this.forwardBufferTarget,this.bufferLimit)||p<=r+Math.min(this.forwardBufferTarget,this.bufferLimit)));if(s===-1)return[];if(t!==be.BYTE_RANGE)return e.slice(s,s+1);const n=e;let o=0,l=0;const d=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let h=s;h<n.length&&(o<=u||l<=c);h++){const f=n[h];if(o+=f.byte.to+1-f.byte.from,l+=f.time.to+1-f.time.from,f.status===H.NONE||f.status===H.PARTIALLY_EJECTED)d.push(f);else break}return d}loadSegments(e,t,r="auto"){return J(this,void 0,void 0,function*(){if(!e.length)return;let s,n,o=e;const{type:l}=t.segmentReference;switch(l){case be.BYTE_RANGE:{s=t.segmentReference.url,n={from:xe(e,0).byte.from,to:xe(e,-1).byte.to};break}case be.TEMPLATE:{const u=xe(e,0);s=new URL(u.url,t.segmentReference.baseUrl).toString(),o=[u];break}default:a.assertNever(l)}for(const u of o)u.status=H.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(yield a.abortable(d,function(){return Ee(this,arguments,function*(){const u=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield R(new Promise(c=>setTimeout(c,u)))})}.bind(this))(),d.aborted))for(const u of this.activeSegments)e.includes(u.segment)&&this.abortSegment(u.segment);return void this.fetcher.fetch(s,{range:n,onProgress:(u,c)=>{if(!d.aborted)try{this.onSomeDataLoaded(u,t.id,n?n.from:0,c,d)}catch(h){this.error$.next({id:"SegmentFeeding",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}},signal:d,priority:r}).then(()=>this.failedDownloads=0,u=>{for(const c of this.activeSegments)e.includes(c.segment)&&this.abortSegment(c.segment);this.onSegmentDownloadError(u)})})}onSegmentDownloadError(e){var t;let r=!1;const s=this.getCurrentPosition();this.sourceBuffer&&a.isNonNullable(s)&&(r=ot((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,s)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,r||this.error$.next({id:"SegmentDownload",category:a.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,r,s,n){if(!this.activeSegments.size)return;const o=h=>{this.abortSegment(h.segment)},l=h=>{var f;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),h.segment.status=H.FED,"size"in h.segment&&(h.segment.size=h.fedBytes);for(const p of this.representations.values())if(p.id!==t)for(const v of(f=this.segments.get(p.id))!==null&&f!==void 0?f:[])v.status===H.FED&&v.time.from===h.segment.time.from&&v.time.to===h.segment.time.to&&(v.status=H.NONE);this.activeSegments.delete(h),this.detectGapsWhenIdle(t,[h.segment])},d=this.representations.get(t);if(!d)return;const u=d.segmentReference.type,c=e.byteLength;for(const h of this.activeSegments){const{segment:f}=h,p=u===be.BYTE_RANGE,v=p?f.byte.to-f.byte.from+1:c;if(h.representationId!==t||!(!p||f.byte.from>=r&&f.byte.to<r+e.byteLength))continue;if(n.aborted){o(h);continue}const S=p?f.byte.from-r:0,b=p?f.byte.to-r:e.byteLength,y=S<s,w=b<=s;if(f.status===H.DOWNLOADING&&y&&w){f.status=H.DOWNLOADED,this.activeSegments.delete(h);const T=new DataView(e.buffer,e.byteOffset+S,v);this.sourceBufferTaskQueue.append(T,n).then(E=>E&&!n.aborted?l(h):o(h))}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&y&&(h.loadedBytes=Math.min(v,s-S),h.loadedBytes>h.feedingBytes)){const T=new DataView(e.buffer,e.byteOffset+S+h.feedingBytes,h.loadedBytes-h.feedingBytes),E=h.loadedBytes===v?T:this.containerParser.parseFeedableSegmentChunk(T);E!=null&&E.byteLength&&(f.status=H.PARTIALLY_FED,h.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,n).then(_=>{if(n.aborted)o(h);else if(_)h.fedBytes+=E.byteLength,h.fedBytes===v&&l(h);else{if(h.feedingBytes<v)return;o(h)}}))}}}abortSegment(e){e.status===H.PARTIALLY_FED||e.status===H.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=H.NONE),e.status=H.PARTIALLY_EJECTED):e.status=H.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[s,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const r=this.representations.get(e);r&&(this.initLoadIdleCallback=Bn(()=>dr(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return J(this,void 0,void 0,function*(){const s=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!r&&this.failedDownloads>0?a.abortable(this.destroyAbortController.signal,function(){return Ee(this,arguments,function*(){const l=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield R(new Promise(d=>setTimeout(d,l)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s)).then(l=>{if(!l)return;const{dataView:d,segments:u}=l,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c),this.segments.set(e.id,u)}).then(()=>this.failedDownloads=0,l=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:a.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o})}pruneBuffer(e,t,r=!1){return J(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||a.isNullable(e)||this.sourceBuffer.updating)return!1;let s=0,n=1/0,o=-1/0,l=!1;const d=u=>{var c;n=Math.min(n,u.time.from),o=Math.max(o,u.time.to);const h="size"in u?(c=u.size)!==null&&c!==void 0?c:0:u.byte.to-u.byte.from;s+=h};for(const u of this.segments.values())for(const c of u){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||s>=t)break;c.status===H.FED&&d(c)}if(l=isFinite(n)&&isFinite(o),!l){s=0,n=1/0,o=-1/0;for(const u of this.segments.values())for(const c of u){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||s>t)break;c.status===H.FED&&d(c)}}if(l=isFinite(n)&&isFinite(o),!l)for(let u=0;u<this.sourceBuffer.buffered.length;u++){const c=this.sourceBuffer.buffered.start(u)*1e3,h=this.sourceBuffer.buffered.end(u)*1e3;for(const f of this.segments.values())for(const p of f)if(p.status===H.NONE&&Math.round(p.time.from)<=Math.round(c)&&Math.round(p.time.to)>=Math.round(h)){n=c,o=h;break}}if(l=isFinite(n)&&isFinite(o),!l&&r){s=0,n=1/0,o=-1/0;const u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const c of this.segments.values())for(const h of c)h.time.from>e+u&&h.status===H.FED&&d(h)}return l=isFinite(n)&&isFinite(o),l?this.sourceBufferTaskQueue.remove(n,o):!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 r of t){let s={representation:e,from:r.time.from,to:r.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3;if(!(l<=r.time.from||o>=r.time.to)){if(o<=r.time.from&&l>=r.time.to){s=void 0;break}l>r.time.from&&l<r.time.to&&(s.from=l),o<r.time.to&&o>r.time.from&&(s.to=o)}}s&&s.to-s.from>=1&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Bn(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:a.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(a.isNullable(this.sourceBuffer)||a.isNullable(this.playingRepresentationId))return;const e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){const s=Math.round(this.sourceBuffer.buffered.start(r)*1e3),n=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:s,to:n})}const t=1;for(const r of this.segments.values())for(const s of r){const{status:n}=s;if(n!==H.FED&&n!==H.PARTIALLY_EJECTED)continue;const o=Math.floor(s.time.from),l=Math.ceil(s.time.to),d=e.some(c=>c.from-t<=o&&c.to+t>=l),u=e.some(c=>o>=c.from-t&&o<=c.to+t||l>=c.from-t&&l<=c.to+t);d||(u?s.status=H.PARTIALLY_EJECTED:s.status=H.NONE)}}}var kt;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(kt||(kt={}));class Tb{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.abortAllController=new lt,this.subscription=new a.Subscription,this.fetchManifest=a.abortable(this.abortAllController.signal,function(s){return Ee(this,arguments,function*(){let n=s;this.requestQuic&&(n=It(n));const o=yield yield R(Rt(n,{signal:this.abortAllController.signal}).catch(Qt));return o?(this.onHeadersReceived(o.headers),yield R(o.text())):yield R(null)})}.bind(this)),this.fetch=a.abortable(this.abortAllController.signal,function(s,{rangeMethod:n=this.compatibilityMode?kt.HEADER:kt.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0}={}){var h,f,p,v;return Ee(this,arguments,function*(){let m=s;const S=new Headers;if(o)switch(n){case kt.HEADER:{S.append("Range",`${o.from}-${o.to}`);break}case kt.PARAM:{const $=new URL(m,location.href);$.searchParams.append("bytes",`${o.from}-${o.to}`),m=$.toString();break}default:a.assertNever(n)}this.requestQuic&&(m=It(m));let b=this.abortAllController.signal;if(u){const $=new lt;if(this.subscription.add(a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.fromEvent(u,"abort")).subscribe(()=>{try{$.abort()}catch(D){Qt(D)}})),this.abortAllController.signal.aborted||u.aborted)try{$.abort()}catch(D){Qt(D)}b=$.signal}const y=a.now(),w=yield yield R(Rt(m,{priority:d,headers:S,signal:b}).catch(Qt)),T=a.now();if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(T-y),!w)return yield R(null);if(!w.ok||!w.body)return yield R(Promise.reject(new Error(`Fetch error ${w.status}: ${w.statusText}`)));this.onHeadersReceived(w.headers);const E=parseInt((f=w.headers.get("Content-Length"))!==null&&f!==void 0?f:"",10)||o&&o.to-o.from+1||NaN;if(!E){const $=yield yield R(w.arrayBuffer());return(p=this.throughputEstimator)===null||p===void 0||p.addRawSpeed($.byteLength,a.now()-T),l==null||l(new DataView($),$.byteLength),yield R($)}if(!l&&!c)return yield R(w.arrayBuffer());const[_,F]=w.body.tee(),O=_.getReader();c&&((v=this.throughputEstimator)===null||v===void 0||v.trackStream(F));let I=0;const U=new ArrayBuffer(E),N=new Uint8Array(U),A=new DataView(U);let G=!1;const K=$=>{G=!0,Qt($)},te=a.abortable(b,function({done:$,value:D}){return Ee(this,arguments,function*(){if(I===0&&this.lastRequestFirstBytes$.next(a.now()-y),b.aborted)return yield R(void 0);$?l==null||l(A,I):D&&(N.set(D,I),I+=D.byteLength,l==null||l(A,I),yield yield R(O==null?void 0:O.read().then(te,K)))})}.bind(this));return yield yield R(O==null?void 0:O.read().then(te,K)),yield R(G?null:U)})}.bind(this)),this.fetchByteRangeRepresentation=a.abortable(this.abortAllController.signal,function(s,n,o){return Ee(this,arguments,function*(){if(s.type!==be.BYTE_RANGE)return yield R(null);const{from:l,to:d}=s.initRange;let u=l,c=d,h=!1,f,p;s.indexRange&&(f=s.indexRange.from,p=s.indexRange.to,h=d+1===f,h&&(u=Math.min(f,l),c=Math.max(p,d))),u=Math.min(u,0);const v=yield yield R(this.fetch(s.url,{range:{from:u,to:c},priority:o,measureThroughput:!1}));if(!v)return yield R(null);const m=new DataView(v,l-u,d-u+1);if(!n.validateData(m))throw new Error("Invalid media file");const S=n.parseInit(m);let b;if(h&&f!==void 0&&p!==void 0)b=new DataView(v,f-u,p-f+1);else{const w=n.getIndexRange(S);if(w){const T=yield yield R(this.fetch(s.url,{range:w,priority:o,measureThroughput:!1}));if(!T)return yield R(null);b=new DataView(T)}}if(!b)throw new ReferenceError("No way to load representation index");const y=n.parseSegments(b,S);return yield R({dataView:new DataView(v),segments:y})})}.bind(this)),this.fetchTemplateRepresentation=a.abortable(this.abortAllController.signal,function(s,n){return Ee(this,arguments,function*(){if(s.type!==be.TEMPLATE)return yield R(null);const o=new URL(s.initUrl,s.baseUrl).toString(),l=yield yield R(this.fetch(o,{priority:n,measureThroughput:!1}));if(!l)return yield R(null);const d=s.segments.map(u=>Object.assign(Object.assign({},u),{status:H.NONE,size:void 0}));return yield R({segments:d,dataView:new DataView(l)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r}onHeadersReceived(e){const{type:t,reused:r}=Rl(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){var s,n;return J(this,void 0,void 0,function*(){const{type:o}=e;switch(o){case be.BYTE_RANGE:return(s=yield this.fetchByteRangeRepresentation(e,t,r))!==null&&s!==void 0?s:null;case be.TEMPLATE:return(n=yield this.fetchTemplateRepresentation(e,r))!==null&&n!==void 0?n:null;default:a.assertNever(o)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Qt=i=>{if(!(i instanceof DOMException)||!(i.name==="AbortError"||i.code===20))throw i},Un=i=>{if(!i.startsWith("P"))return;const e=(o,l)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*l},r=/^(-|\+)?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),s=(r==null?void 0:r[1])==="-"?-1:1,n={days:e(r==null?void 0:r[5],s),hours:e(r==null?void 0:r[6],s),minutes:e(r==null?void 0:r[7],s),seconds:e(r==null?void 0:r[8],s)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},Xr=(i,e)=>{let t=i;t=t.replaceAll("$$","$");const r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,n]of Object.entries(r)){const o=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(o,(l,d)=>a.isNullable(n)?l:a.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},Eb=(i,e)=>{var t,r,s,n,o,l,d,u,c,h,f,p,v,m,S,b,y,w,T,E,_,F,O,I,U,N,A,G,K,te,$,D,z,ee,ie,ce,ke;const j=new DOMParser().parseFromString(i,"application/xml"),ae={video:[],audio:[],text:[]},ue=j.children[0],me=ue.getElementsByTagName("Period")[0],tt=me.children;let we;const Ye=ue.getAttribute("mediaPresentationDuration"),it=me.getAttribute("duration");if(Ye)we=Un(Ye);else if(it){const _e=Un(it);a.isNonNullable(_e)&&(we=_e)}let xt=0;const vt=(r=(t=ue.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&r!==void 0?r:[],Vl=vt.includes(Xi.WEBM_AS_IN_FFMPEG)||vt.includes(Xi.WEBM_AS_IN_SPEC)?Nt.WEBM:Nt.MP4;for(const _e of tt){const fi=_e.getAttribute("mimeType"),Fl=_e.getAttribute("codecs"),oa=(s=_e.getAttribute("contentType"))!==null&&s!==void 0?s:fi==null?void 0:fi.split("/")[0],Ul=(o=(n=_e.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],jl=_e.querySelectorAll("Representation"),Hl=_e.querySelector("SegmentTemplate");if(oa!=="text")for(const ne of jl){const Bt=(l=ne.getAttribute("mimeType"))!==null&&l!==void 0?l:fi,la=(u=(d=ne.getAttribute("codecs"))!==null&&d!==void 0?d:Fl)!==null&&u!==void 0?u:"",pi=(h=(c=ne.getAttribute("contentType"))!==null&&c!==void 0?c:Bt==null?void 0:Bt.split("/")[0])!==null&&h!==void 0?h:oa,Gl=(p=(f=_e.getAttribute("profiles"))===null||f===void 0?void 0:f.split(","))!==null&&p!==void 0?p:[],ql=parseInt((v=ne.getAttribute("width"))!==null&&v!==void 0?v:"",10),ua=parseInt((m=ne.getAttribute("height"))!==null&&m!==void 0?m:"",10),da=parseInt((S=ne.getAttribute("bandwidth"))!==null&&S!==void 0?S:"",10)/1e3,ca=(b=ne.getAttribute("frameRate"))!==null&&b!==void 0?b:"",Yl=(y=ne.getAttribute("quality"))!==null&&y!==void 0?y:void 0,zl=ca?aa(ca):void 0,Wl=(w=ne.getAttribute("id"))!==null&&w!==void 0?w:(xt++).toString(10),Ql=pi==="video"?`${ua}p`:pi==="audio"?`${da}Kbps`:la,Jl=`${Wl}@${Ql}`,Kl=(_=(E=(T=ne.querySelector("BaseURL"))===null||T===void 0?void 0:T.textContent)===null||E===void 0?void 0:E.trim())!==null&&_!==void 0?_:"",ha=new URL(Kl,e).toString(),Xl=[...vt,...Ul,...Gl];let fr;const Zl=ne.querySelector("SegmentBase"),rt=(F=ne.querySelector("SegmentTemplate"))!==null&&F!==void 0?F:Hl;if(Zl){const Mt=(I=(O=ne.querySelector("SegmentBase Initialization"))===null||O===void 0?void 0:O.getAttribute("range"))!==null&&I!==void 0?I:"",[Vt,mr]=Mt.split("-").map(st=>parseInt(st,10)),Ft={from:Vt,to:mr},Ut=(U=ne.querySelector("SegmentBase"))===null||U===void 0?void 0:U.getAttribute("indexRange"),[vr,mi]=Ut?Ut.split("-").map(st=>parseInt(st,10)):[],jt=Ut?{from:vr,to:mi}:void 0;fr={type:be.BYTE_RANGE,url:ha,initRange:Ft,indexRange:jt}}else if(rt){const Mt={representationId:(N=ne.getAttribute("id"))!==null&&N!==void 0?N:void 0,bandwidth:(A=ne.getAttribute("bandwidth"))!==null&&A!==void 0?A:void 0},Vt=parseInt((G=rt.getAttribute("timescale"))!==null&&G!==void 0?G:"",10),mr=(K=rt.getAttribute("initialization"))!==null&&K!==void 0?K:"",Ft=rt.getAttribute("media"),Ut=($=parseInt((te=rt.getAttribute("startNumber"))!==null&&te!==void 0?te:"",10))!==null&&$!==void 0?$:1,vr=Xr(mr,Mt);if(!Ft)throw new ReferenceError("No media attribute in SegmentTemplate");const mi=(D=rt.querySelectorAll("SegmentTimeline S"))!==null&&D!==void 0?D:[],jt=[];if(mi.length){let st=Ut,at=0;for(const Ht of mi){const St=parseInt((z=Ht.getAttribute("d"))!==null&&z!==void 0?z:"",10)*1e3,Gt=parseInt((ee=Ht.getAttribute("r"))!==null&&ee!==void 0?ee:"",10)||0,qt=(ce=parseInt((ie=Ht.getAttribute("t"))!==null&&ie!==void 0?ie:"",10))!==null&&ce!==void 0?ce:void 0;for(let fa=0;fa<Gt+1;fa++){const eu=Xr(Ft,Object.assign(Object.assign({},Mt),{segmentNumber:st.toString(10),segmentTime:qt.toString(10)})),tu=qt?qt/Vt:at;at+=St/Vt;const iu=at;st++,jt.push({time:{from:tu,to:iu},url:eu})}}}else if(a.isNonNullable(we)){const at=parseInt((ke=rt.getAttribute("duration"))!==null&&ke!==void 0?ke:"",10)/Vt*1e3,Ht=Math.ceil(we/at);let St=0;for(let Gt=1;Gt<Ht;Gt++){const qt=Xr(Ft,Object.assign(Object.assign({},Mt),{segmentNumber:Gt.toString(10),segmentTime:St.toString(10)}));jt.push({time:{from:St,to:St+at},url:qt}),St+=at}}fr={type:be.TEMPLATE,baseUrl:ha,initUrl:vr,segments:jt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!pi||!Bt)continue;const pr={video:Se.VIDEO,audio:Se.AUDIO,text:Se.TEXT}[pi];pr&&ae[pr].push({id:Jl,kind:pr,segmentReference:fr,profiles:Xl,duration:we,bitrate:da,mime:Bt,codecs:la,width:ql,height:ua,fps:zl,quality:Yl})}}return{duration:we,container:Vl,representations:ae}},$b=["timeupdate","progress","play","seeked","stalled"];var ve;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(ve||(ve={}));let Pb=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new a.Subscription,this.state$=new Q(ve.NONE),this.currentVideoRepresentation$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.forceEnded$=new a.Subject,this.gapWatchdogStarted=!1,this.destroyController=new lt,this.initManifest=a.abortable(this.destroyController.signal,function(t,r){return Ee(this,arguments,function*(){this.element=t,this.state$.startTransitionTo(ve.MANIFEST_READY);const s=yield yield R(this.fetcher.fetchManifest(r).catch(l=>this.error$.next({id:"LoadManifest",category:a.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:l})));if(!s)return yield R(void 0);let n;try{n=Eb(s!=null?s:"",r)}catch(l){this.error$.next({id:"ManifestParsing",category:a.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:l})}if(!n)return yield R(void 0);const o=({mime:l,codecs:d})=>{var u,c,h;return Boolean(((u=t.canPlayType)===null||u===void 0?void 0:u.call(t,l))&&((h=(c=window.MediaSource)===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0?void 0:h.call(c,`${l}; codecs="${d}"`)))};this.manifest=Object.assign(Object.assign({},n),{representations:oi(Object.entries(n.representations).map(([l,d])=>[l,d.filter(o)]))}),this.manifest.representations.video.length?this.state$.setState(ve.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:a.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this)),this.initRepresentations=a.abortable(this.destroyController.signal,function(t,r){return Ee(this,arguments,function*(){a.assertNonNullable(this.manifest),a.assertNonNullable(this.element),this.state$.startTransitionTo(ve.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0};this.videoBufferManager=new Fn(Se.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(r)&&(this.audioBufferManager=new Fn(Se.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,s),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 n=a.merge(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(a.map(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),o=a.merge(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(a.map(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.subscription.add(a.merge(this.forceEnded$,a.combine({allBuffersFull:n,someBufferEnded:o}).pipe(a.filter(({allBuffersFull:l,someBufferEnded:d})=>l&&d))).subscribe(()=>{var l;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{(l=this.source)===null||l===void 0||l.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.subscription.add(a.merge(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.source.readyState!=="open"&&(yield yield R(new Promise(l=>{var d;return(d=this.source)===null||d===void 0?void 0:d.addEventListener("sourceopen",l)}))),a.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&a.isNonNullable(r)?yield yield R(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(r)])):yield yield R(this.videoBufferManager.startWith(t)),this.state$.setState(ve.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,r;if(!this.element||!this.videoBufferManager)return;const s=this.element.currentTime*1e3;this.videoBufferManager.maintain(s),(t=this.audioBufferManager)===null||t===void 0||t.maintain(s),(this.videoBufferManager.gaps.length||!((r=this.audioBufferManager)===null||r===void 0)&&r.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=a.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),n=>{this.error$.next({id:"GapWatchdog",category:a.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Tb({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initBuffer(){a.assertNonNullable(this.element),this.state$.setState(ve.RUNNING),this.subscription.add(a.merge(...$b.map(e=>a.fromEvent(this.element,e)),a.fromEvent(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:a.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(a.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(a.fromEvent(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&xn(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}switchRepresentation(e,t){return J(this,void 0,void 0,function*(){const r={[Se.VIDEO]:this.videoBufferManager,[Se.AUDIO]:this.audioBufferManager,[Se.TEXT]:null}[e];return r==null?void 0:r.switchTo(t)})}seek(e,t){var r,s,n,o,l;a.assertNonNullable(this.element),a.assertNonNullable(this.videoBufferManager);let d;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?d=e:d=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!==null&&r!==void 0?r:e,(n=(s=this.audioBufferManager)===null||s===void 0?void 0:s.findSegmentStartTime(e))!==null&&n!==void 0?n:e),xn(this.element.buffered,d)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)===null||o===void 0||o.abort()),this.videoBufferManager.maintain(d),(l=this.audioBufferManager)===null||l===void 0||l.maintain(d),this.element.currentTime=d/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(ve.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3,t=[];for(const r of this.bufferManagers)for(const s of r.gaps)r.playingRepresentation$.getValue()===s.representation&&s.from<=e&&s.to>e&&(this.element.duration*1e3-s.to<this.tuning.endGapTolerance?t.push(1/0):t.push(s.to));if(t.length){const r=Math.max(...t);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=r/1e3}}};var X;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(X||(X={}));const kb=({id:i,width:e,height:t,bitrate:r,fps:s,quality:n})=>{var o;const l=(o=n?ci(n):void 0)!==null&&o!==void 0?o:pt({width:e,height:t});return l&&{id:i,quality:l,bitrate:r,size:{width:e,height:t},fps:s}},wb=(i,e,t)=>{var r;const s=e.indexOf(t);return(r=xe(i,Math.round(i.length*s/e.length)))!==null&&r!==void 0?r:xe(i,-1)};class _b{constructor(e){this.subscription=new a.Subscription,this.videoState=new Q(X.STOPPED),this.elementSize$=new a.ValueSubject(void 0),this.textTracksManager=new Oe,this.videoTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new xS,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(n.state===C.Requested&&(s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&t!==X.STOPPED&&r!==exports.PlaybackState.STOPPED&&this.seek(n.position,n.forcePrecise),r===exports.PlaybackState.STOPPED){t!==X.STOPPED&&(this.videoState.startTransitionTo(X.STOPPED),this.player.stop(),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(X.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(t){case X.STOPPED:this.videoState.startTransitionTo(X.READY),this.prepare();return;case X.READY:r===exports.PlaybackState.PAUSED?(this.videoState.setState(X.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(X.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.READY&&P(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case X.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(X.PAUSED),this.video.pause()):(s==null?void 0:s.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case X.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(X.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}}},this.params=e,this.video=Ge(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Pb({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,r=qe(this.video),s=u=>{e.error$.next({id:"DashVKProvider",category:a.ErrorCategory.WTF,message:"DashVKProvider internal logic error",thrown:u})},n=(u,c)=>this.subscription.add(u.subscribe(c,s));n(r.timeUpdate$,e.position$),n(r.durationChange$,e.duration$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.lastRequestFirstBytes$.pipe(a.filter(a.isNonNullable),a.once(),a.mapTo(void 0)),e.firstBytesEvent$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(mt(this.video,t.isLooped,s)),this.subscription.add(He(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Ze(this.video,t.playbackRate,r.playbackRateState$,s)),n(Ji(this.video),this.elementSize$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(X.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(X.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(r.canplay$.subscribe(()=>{this.videoState.getState()===X.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var c;if(u===ve.MANIFEST_READY){this.videoTracks=[];const h=this.player.getRepresentations();a.assertNonNullable(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((m,S)=>S.bitrate-m.bitrate),p=Array.from(h.video).sort((m,S)=>S.bitrate-m.bitrate);for(const m of p){const S=kb(m);if(S){this.videoTracks.push({track:S,representation:m});const b=wb(f,p,m);b&&this.audioRepresentations.set(m.id,b)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:m})=>m));const v=this.selectVideoRepresentation();a.assertNonNullable(v),this.player.initRepresentations(v.id,(c=this.audioRepresentations.get(v.id))===null||c===void 0?void 0:c.id)}else u===ve.REPRESENTATIOS_READY&&(this.videoState.setState(X.READY),this.player.initBuffer())},s));const o=u=>e.error$.next({id:"RepresentationSwitch",category:a.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(a.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,a.fromEvent(this.video,"progress")).subscribe(()=>{const u=this.player.state$.getState(),c=this.player.state$.getTransition();if(u!==ve.RUNNING||c||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const h=this.selectVideoRepresentation();if(h){this.player.switchRepresentation(Se.VIDEO,h.id).catch(o);const f=this.audioRepresentations.get(h.id);f&&this.player.switchRepresentation(Se.AUDIO,f.id).catch(o)}},s)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(a.filterChanged(),a.map(u=>{var c;return u&&((c=this.videoTracks.find(({representation:{id:h}})=>h===u))===null||c===void 0?void 0:c.track)})).subscribe(e.currentVideoTrack$,s)),this.textTracksManager.connect(this.video,t,e);const l=t.playbackState.stateChangeStarted$.pipe(a.map(({to:u})=>u===exports.PlaybackState.READY),a.filterChanged());this.subscription.add(a.merge(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const u=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(a.merge(l,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,s))}selectVideoRepresentation(){var e,t,r,s,n,o;const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.videoTrack.getState(),u=(e=this.videoTracks.find(({track:{id:b}})=>b===d))===null||e===void 0?void 0:e.track,c=this.params.output.currentVideoTrack$.getValue(),h=ot(this.video.buffered,this.video.currentTime*1e3),f=l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=Math.min(h/Math.min(f,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),v=Math.max(u&&!l&&(r=(t=this.audioRepresentations.get(u.id))===null||t===void 0?void 0:t.bitrate)!==null&&r!==void 0?r:0,c&&(n=(s=this.audioRepresentations.get(c.id))===null||s===void 0?void 0:s.bitrate)!==null&&n!==void 0?n:0),m=di(this.videoTracks.map(({track:b})=>b),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:p,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),S=l?m!=null?m:u:u!=null?u:m;return S&&((o=this.videoTracks.find(({track:b})=>b===S))===null||o===void 0?void 0:o.representation)}prepare(){return J(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.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){et(this.video).then(e=>{e||(this.videoState.setState(X.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}}const Ab=5e3,Le={};var V;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(V||(V={}));const Ci=(i,e)=>new a.Observable(t=>{const r=(s,n)=>t.next(n);return i.on(e,r),()=>i.off(e,r)});class Rb{constructor(e){this.subscription=new a.Subscription,this.videoState=new Q(V.INITIALIZING),this.textTracksManager=new Oe,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(t!==V.INITIALIZING)switch((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===C.Requested&&this.seek(n.position),r){case exports.PlaybackState.STOPPED:switch(t){case V.STOPPED:break;case V.READY:case V.PLAYING:case V.PAUSED:this.stop();break;default:a.assertNever(t)}break;case exports.PlaybackState.READY:switch(t){case V.STOPPED:this.prepare();break;case V.READY:case V.PLAYING:case V.PAUSED:break;default:a.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case V.PLAYING:break;case V.STOPPED:this.prepare();break;case V.READY:case V.PAUSED:this.playIfAllowed();break;default:a.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case V.PAUSED:break;case V.STOPPED:this.prepare();break;case V.READY:this.videoState.setState(V.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case V.PLAYING:this.pause();break;default:a.assertNever(t)}break;default:a.assertNever(r)}},this.video=Ge(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(de(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)===null||e===void 0||e.detachMedia(),(t=this.hls)===null||t===void 0||t.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:a.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:s}),e=!0},r=window.setTimeout(()=>t("timeout"),Ab);dr(import("hls.js/dist/hls.min.js").then(s=>{e||(Le.Hls=s.default,Le.Events=s.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){a.assertNonNullable(Le.Hls,"hls.js not loaded"),this.hls=new Le.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(V.STOPPED)}subscribe(){a.assertNonNullable(Le.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:a.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},s=qe(this.video),n=(u,c)=>this.subscription.add(u.subscribe(c,r));n(s.timeUpdate$,t.position$),n(s.durationChange$,t.duration$),n(s.ended$,t.endedEvent$),n(s.looped$,t.loopedEvent$),n(s.error$,t.error$),n(s.isBuffering$,t.isBuffering$),n(s.currentBuffer$,t.currentBuffer$),n(s.loadStart$,t.firstBytesEvent$),n(s.playing$,t.firstFrameEvent$),n(s.canplay$,t.canplay$),n(s.seeked$,t.seekedEvent$),this.subscription.add(mt(this.video,e.isLooped,r)),this.subscription.add(He(this.video,e.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ze(this.video,e.playbackRate,s.playbackRateState$,r)),this.subscription.add(Ci(this.hls,Le.Events.ERROR).subscribe(u=>{var c;u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:a.ErrorCategory.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${(c=u.err)===null||c===void 0?void 0:c.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(V.PLAYING),P(e.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(V.PAUSED),P(e.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===V.READY&&this.videoState.setState(V.READY),this.videoState.getState()===V.PLAYING&&this.playIfAllowed()},r)),n(Ci(this.hls,Le.Events.MANIFEST_PARSED).pipe(a.map(({levels:u})=>u.reduce((c,h)=>{var f,p;const v=h.name||h.height.toString(10),{width:m,height:S}=h,b=(p=ci((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&p!==void 0?p:pt({width:m,height:S});if(!b)return c;const y=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,w={id:v.toString(),quality:b,bitrate:h.bitrate/1e3,size:{width:m,height:S},fps:y};return this.trackLevels.set(v,{track:w,level:h}),c.push(w),c},[]))),t.availableVideoTracks$),n(Ci(this.hls,Le.Events.LEVEL_LOADING).pipe(a.map(({url:u})=>de(u))),t.hostname$),this.subscription.add(Ne(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:r}));const o=u=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:h})=>h===u))===null||c===void 0?void 0:c.track},l=Ci(this.hls,Le.Events.LEVEL_SWITCHED).pipe(a.map(({level:u})=>o(this.hls.levels[u])));l.pipe(a.filter(a.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Ne(e.videoTrack,()=>{var u;return(u=o(this.hls.levels[this.hls.currentLevel]))===null||u===void 0?void 0:u.id},u=>{var c;if(a.isNullable(u))return;const h=(c=this.trackLevels.get(u))===null||c===void 0?void 0:c.level;if(!h)return;const f=this.hls.levels.indexOf(h),p=this.hls.currentLevel,v=this.hls.levels[p];!v||h.bitrate>v.bitrate?this.hls.nextLevel=f:(this.hls.loadLevel=f,this.hls.loadLevel=f)},{changed$:l.pipe(a.map(u=>u==null?void 0:u.id)),onError:r})),n(s.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=a.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo(V.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return J(this,void 0,void 0,function*(){this.videoState.startTransitionTo(V.PLAYING),(yield et(this.video))||(this.videoState.setState(V.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(V.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.setAttribute("src",""),this.video.load(),this.videoState.setState(V.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const jn="X-Playback-Duration";var Hn=i=>J(void 0,void 0,void 0,function*(){const e=yield Rt(i,{method:"HEAD"});return e.headers.has(jn)?parseInt(e.headers.get(jn),10):void 0});const Ib=i=>{let e=null;if(i.QUALITY&&(e=ci(i.QUALITY)),!e&&i.RESOLUTION){const[t,r]=i.RESOLUTION.split("x").map(s=>parseInt(s,10));e=pt({width:t,height:r})}return e!=null?e:null},xl=(i,e=i)=>J(void 0,void 0,void 0,function*(){var t;const n=(yield(yield Rt(i)).text()).split(`
|
|
8
|
+
`),o=[];for(let l=0;l<n.length;l++){const u=n[l].match(/^#EXT-X-STREAM-INF:(.+)/);if(!u)continue;const c=oi(u[1].split(",").map(b=>b.split("="))),h=(t=c.QUALITY)!==null&&t!==void 0?t:`stream-${c.BANDWIDTH}`,f=Ib(c);let p;c.BANDWIDTH&&(p=parseInt(c.BANDWIDTH,10)/1e3||void 0),!p&&c["AVERAGE-BANDWIDTH"]&&(p=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const v=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0;let m;if(c.RESOLUTION){const[b,y]=c.RESOLUTION.split("x").map(w=>parseInt(w,10));b&&y&&(m={width:b,height:y})}const S=new URL(n[++l],e).toString();f&&o.push({id:h,quality:f,url:S,bandwidth:p,size:m,fps:v})}return o});var q;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(q||(q={}));class Nb{constructor(e){var t;this.subscription=new a.Subscription,this.videoState=new Q(q.STOPPED),this.textTracksManager=new Oe,this.manifests$=new a.ValueSubject([]),this.liveOffset=new sa,this.manifestStartTime$=new a.ValueSubject(void 0),this.syncPlayback=()=>{const s=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(n===exports.PlaybackState.STOPPED){s!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(q.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(s===q.STOPPED){this.videoState.startTransitionTo(q.READY),this.prepare();return}if(l||d){const h=this.videoState.getState();this.videoState.setState(q.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),c.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&c.state===C.Requested){this.videoState.startTransitionTo(q.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(s){case q.READY:n===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):n===exports.PlaybackState.PAUSED?(this.videoState.setState(q.PAUSED),this.liveOffset.pause(),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):n===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed());return;case q.PLAYING:n===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(q.PAUSED),this.liveOffset.pause(),this.video.pause()):(o==null?void 0:o.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case q.PAUSED:n===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(q.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())):(o==null?void 0:o.to)===exports.PlaybackState.PAUSED&&(P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case q.CHANGING_MANIFEST:break;default:return a.assertNever(s)}},this.params=e,this.video=Ge(e.container),this.params.output.element$.next(this.video);const r={id:"master",quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([r]),xl(At(this.params.source.url),this.params.source.url).then(s=>{this.manifests$.next([r,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.maxSeekBackTime$=new a.ValueSubject((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:r,videoTrack:s}=this.params.desiredState,n=r.getState(),o=s.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:s.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d)return;const u=n?"master":l;return n&&!o&&s.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,r=l=>{e.error$.next({id:"HlsLiveProvider",category:a.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:l})},s=qe(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,r));n(s.ended$,e.endedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(He(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ze(this.video,t.playbackRate,s.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(q.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(q.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===q.READY&&this.videoState.setState(q.READY),this.videoState.getState()===q.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(l=>-l/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(s.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&a.isNonNullable(u.to)){const h=u.to;this.params.desiredState.videoTrack.setState(h);const f=this.manifests$.getValue().find(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(de(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===q.CHANGING_MANIFEST&&this.videoState.setState(d.to),l&&l.state===C.Requested&&this.seek(l.position)},r)),this.subscription.add(s.loadedData$.subscribe(()=>{var l,d,u;const c=(u=(d=(l=this.video)===null||l===void 0?void 0:l.getStartDate)===null||d===void 0?void 0:d.call(l))===null||u===void 0?void 0:u.getTime();this.manifestStartTime$.next(c||void 0)},r)),this.subscription.add(a.combine({startTime:this.manifestStartTime$.pipe(a.filter(a.isNonNullable)),currentTime:s.timeUpdate$}).subscribe(({startTime:l,currentTime:d})=>this.params.output.liveTime$.next(l+d*1e3),r)),this.subscription.add(this.manifests$.pipe(a.map(l=>l.map(({id:d,quality:u,size:c,bandwidth:h,fps:f})=>({id:d,quality:u,size:c,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,r));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();if(a.isNullable(e))return;const t=At(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),Hn(t).then(r=>{var s;if(!a.isNullable(r))this.maxSeekBackTime$.next(r);else{const n=(s=this.params.source.maxSeekBackTime)!==null&&s!==void 0?s:this.maxSeekBackTime$.getValue();if(a.isNullable(n)||!isFinite(n))try{Rt(t).then(o=>o.text()).then(o=>{var l;const d=(l=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(o))===null||l===void 0?void 0:l[1];if(d){const u=new URL(d,t).toString();Hn(u).then(c=>{a.isNullable(c)||this.maxSeekBackTime$.next(c)})}})}catch(o){}}})}playIfAllowed(){et(this.video).then(e=>{e||(this.videoState.setState(q.PAUSED),this.liveOffset.pause(),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next();const t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}}var W;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(W||(W={}));class Cb{constructor(e){this.subscription=new a.Subscription,this.videoState=new Q(W.STOPPED),this.textTracksManager=new Oe,this.manifests$=new a.ValueSubject([]),this.syncPlayback=()=>{const r=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s===exports.PlaybackState.STOPPED){r!==W.STOPPED&&(this.videoState.startTransitionTo(W.STOPPED),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(W.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.seekState.getState();if(r===W.STOPPED){this.videoState.startTransitionTo(W.READY),this.prepare();return}if(o||l){const c=this.videoState.getState();this.videoState.setState(W.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),u.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:h*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&u.state===C.Requested&&this.seek(u.position),r){case W.READY:s===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):s===exports.PlaybackState.PAUSED?(this.videoState.setState(W.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed());return;case W.PLAYING:s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(W.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case W.PAUSED:s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case W.CHANGING_MANIFEST:break;default:return a.assertNever(r)}},this.params=e,this.video=Ge(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([t]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(de(this.params.source.url)),xl(this.params.source.url).then(r=>{this.manifests$.next([t,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:r,videoTrack:s}=this.params.desiredState,n=r.getState(),o=s.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:s.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d)return;const u=n?"master":l;return n&&!o&&s.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,r=l=>{e.error$.next({id:"HlsProvider",category:a.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:l})},s=qe(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d));n(s.timeUpdate$,e.position$),n(s.durationChange$,e.duration$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.seeked$,e.seekedEvent$),this.subscription.add(mt(this.video,t.isLooped,r)),this.subscription.add(He(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ze(this.video,t.playbackRate,s.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===W.READY&&this.videoState.setState(W.READY),this.videoState.getState()===W.PLAYING&&this.playIfAllowed()},r).add(s.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&a.isNonNullable(u.to)){const h=u.to;this.params.desiredState.videoTrack.setState(h);const f=this.manifests$.getValue().find(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(de(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===W.CHANGING_MANIFEST&&this.videoState.setState(d.to),l.state===C.Requested&&this.seek(l.position)},r))),this.subscription.add(this.manifests$.pipe(a.map(l=>l.map(({id:d,quality:u,size:c,bandwidth:h,fps:f})=>({id:d,quality:u,size:c,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,r));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();a.isNullable(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){et(this.video).then(e=>{e||(this.videoState.setState(W.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var Z;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(Z||(Z={}));class Db{constructor(e){this.subscription=new a.Subscription,this.videoState=new Q(Z.STOPPED),this.trackUrls={},this.textTracksManager=new Oe,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(r===exports.PlaybackState.STOPPED){t!==Z.STOPPED&&(this.videoState.startTransitionTo(Z.STOPPED),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Z.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.seekState.getState();if(t===Z.STOPPED){this.videoState.startTransitionTo(Z.READY),this.prepare();return}if(o){const{currentTime:d}=this.video;this.prepare(),l.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:d*1e3,forcePrecise:!0});return}switch((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&l.state===C.Requested&&this.seek(l.position),t){case Z.READY:r===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):r===exports.PlaybackState.PAUSED?(this.videoState.setState(Z.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed());return;case Z.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Z.PAUSED),this.video.pause()):(s==null?void 0:s.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Z.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.params=e,this.video=Ge(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach(([t,r],s)=>{const n=s.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:r}}),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.isLive$.next(!1),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,r=l=>{e.error$.next({id:"MpegProvider",category:a.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:l})},s=qe(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,r));n(s.timeUpdate$,e.position$),n(s.durationChange$,e.duration$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.seeked$,e.seekedEvent$),this.subscription.add(mt(this.video,t.isLooped,r)),this.subscription.add(He(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ze(this.video,t.playbackRate,s.playbackRateState$,r)),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(Z.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(Z.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===Z.READY&&this.videoState.setState(Z.READY);const d=this.params.desiredState.videoTrack.getTransition();d&&a.isNonNullable(d.to)&&(this.params.desiredState.videoTrack.setState(d.to),this.params.output.currentVideoTrack$.next(this.trackUrls[d.to].track)),this.videoState.getState()===Z.PLAYING&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);const o=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){var e,t;const r=(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();a.assertNonNullable(r,"MpegProvider: track is not selected");let{url:s}=this.trackUrls[r];a.assertNonNullable(s,`MpegProvider: No url for ${r}`),this.params.tuning.requestQuick&&(s=It(s)),this.video.setAttribute("src",s),this.video.load(),this.params.output.hostname$.next(de(s))}playIfAllowed(){et(this.video).then(e=>{e||(this.videoState.setState(Z.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}const Gn=["stun:videostun.mycdn.me:80"],Ob=1e3,Lb=3,Zr=()=>null;class xb{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=Zr,this.externalStopCallback=Zr,this.externalErrorCallback=Zr,this.options=this.normalizeOptions(t);const r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return J(this,void 0,void 0,function*(){try{const t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return J(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:Gn}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return J(this,void 0,void 0,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return J(this,void 0,void 0,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:a.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return J(this,void 0,void 0,function*(){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return J(this,void 0,void 0,function*(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))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),Ob)}normalizeOptions(e={}){const t={stunServerList:Gn,maxRetryNumber:Lb,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var Y;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(Y||(Y={}));class Bb{constructor(e){this.videoState=new Q(Y.STOPPED),this.maxSeekBackTime$=new a.ValueSubject(0),this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(r===exports.PlaybackState.STOPPED){t!==Y.STOPPED&&(this.videoState.startTransitionTo(Y.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(Y.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition();if(t===Y.STOPPED){this.videoState.startTransitionTo(Y.READY),this.prepare();return}if(o){this.prepare();return}switch(t){case Y.READY:r===exports.PlaybackState.PAUSED?(this.videoState.setState(Y.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed());return;case Y.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Y.PAUSED),this.video.pause()):(s==null?void 0:s.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Y.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ge(e.container),this.liveStreamClient=new xb(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.video.remove(),this.params.output.element$.next(void 0),this.liveStreamClient.disconnect()}subscribe(){const{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"WebRTCLiveProvider",category:a.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:l})=>{this.log({message:`[videoState change] ${l}: ${JSON.stringify(o)}`})});const s=qe(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,r));n(s.timeUpdate$,e.liveTime$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),this.subscription.add(s.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(s.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===Y.READY&&this.videoState.setState(Y.READY)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED)},r)).add(s.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING)},r)).add(s.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(He(this.video,t.volume,s.volumeState$,r)).add(s.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case Y.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case Y.READY:break;case Y.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case Y.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(o.to)}},r)).add(a.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}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(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:exports.VideoQuality.INVARIANT}),this.video.srcObject=e,P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(Y.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:a.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){et(this.video).then(e=>{e||(this.videoState.setState(Y.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}prepare(){this.liveStreamClient.connect()}}class qn{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 Mb=()=>{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")},es,ts,is,rs,ss,as,Di,ns,Oi,os,Li,ls,xi,us,Bi,ds;const Bl=Mb(),We=document.createElement("video"),ze={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&((ts=(es=window.SourceBuffer)===null||es===void 0?void 0:es.prototype)===null||ts===void 0?void 0:ts.appendBuffer)),hls:Boolean(((is=We.canPlayType)===null||is===void 0?void 0:is.call(We,"application/x-mpegurl"))||((rs=We.canPlayType)===null||rs===void 0?void 0:rs.call(We,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection)},Re={mp4:Boolean((ss=We.canPlayType)===null||ss===void 0?void 0:ss.call(We,"video/mp4")),webm:Boolean((as=We.canPlayType)===null||as===void 0?void 0:as.call(We,"video/webm"))},Qe={h264:Boolean((ns=(Di=window.MediaSource)===null||Di===void 0?void 0:Di.isTypeSupported)===null||ns===void 0?void 0:ns.call(Di,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean((os=(Oi=window.MediaSource)===null||Oi===void 0?void 0:Oi.isTypeSupported)===null||os===void 0?void 0:os.call(Oi,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean((ls=(Li=window.MediaSource)===null||Li===void 0?void 0:Li.isTypeSupported)===null||ls===void 0?void 0:ls.call(Li,'video/webm; codecs="vp9"')),aac:Boolean((us=(xi=window.MediaSource)===null||xi===void 0?void 0:xi.isTypeSupported)===null||us===void 0?void 0:us.call(xi,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean((ds=(Bi=window.MediaSource)===null||Bi===void 0?void 0:Bi.isTypeSupported)===null||ds===void 0?void 0:ds.call(Bi,'audio/webm; codecs="opus"'))},Jt=(Qe.h264||Qe.h265)&&Qe.aac,hr=ze.hls&&Re.mp4,Vb=Boolean(window.WebSocket),Fb=()=>Object.keys(Qe).filter(i=>Qe[i]),Ub=(i,e=!1)=>i.filter(t=>{switch(t){case exports.VideoFormat.DASH:return ze.mse&&Re.mp4&&Jt;case exports.VideoFormat.DASH_SEP:return ze.mse&&Re.mp4&&Jt;case exports.VideoFormat.DASH_WEBM:return ze.mse&&Re.webm&&Qe.vp9&&Qe.opus;case exports.VideoFormat.DASH_LIVE:return ze.mse&&Re.mp4&&Jt;case exports.VideoFormat.DASH_ONDEMAND:return ze.mse&&Re.mp4&&Jt;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_ONDEMAND:return hr||e&&ze.mse&&Re.mp4&&Jt;case exports.VideoFormat.MPEG:return Re.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return ze.webrtc&&Vb&&Qe.h264&&(Re.mp4||Re.webm);default:return a.assertNever(t)}}),jb=()=>Bl?[exports.VideoFormat.MPEG,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND]:hr?[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG],Hb=()=>Bl?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE]:hr?[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.DASH_LIVE]:[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.HLS_LIVE],Yn=i=>i?[exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var Gb=i=>new a.Observable(e=>{const t=new a.Subscription,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(a.map(({from:u,to:c})=>`${u}-${c}`)),s=i.desiredPlaybackState$.stateChangeEnded$,n=i.providerChanged$,o=new a.Subject;let l=0,d="unknown";return t.add(r.subscribe(u=>{l&&window.clearTimeout(l),d=u,l=window.setTimeout(()=>o.next(u),i.maxTransitionInterval)})),t.add(s.subscribe(()=>{window.clearTimeout(l),d="provider change",l=0})),t.add(n.subscribe(()=>{l&&(window.clearTimeout(l),l=window.setTimeout(()=>o.next(d),i.maxTransitionInterval))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const zn={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},qb={cacheDuration:12e4},Yb={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},zb={maxPausedTime:3e4},Wb={maxPausedTime:3e4};class Qb{constructor(e){this.current$=new a.ValueSubject({type:void 0}),this.providerError$=new a.Subject,this.noAvailableProvidersError$=new a.Subject,this.providerOutput={position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),volume$:new a.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new a.ValueSubject(void 0),availableVideoTracks$:new a.ValueSubject([]),autoVideoTrackLimitingAvailable$:new a.ValueSubject(!1),currentBuffer$:new a.ValueSubject(void 0),isBuffering$:new a.ValueSubject(!0),error$:new a.Subject,willSeekEvent$:new a.Subject,seekedEvent$:new a.Subject,loopedEvent$:new a.Subject,endedEvent$:new a.Subject,firstBytesEvent$:new a.Subject,firstFrameEvent$:new a.Subject,canplay$:new a.Subject,isLive$:new a.ValueSubject(void 0),liveTime$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),element$:new a.ValueSubject(void 0)},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Ub([...Hb(),...jb()],this.params.tuning.useHlsJs).filter(o=>a.isNonNullable(e.sources[o])),{formatsToAvoid:r}=this.params.tuning,s=r.length?[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:t;this.screenFormatsIterator=new qn(s);const n=[...Yn(!0),...Yn(!1)];this.chromecastFormatsIterator=new qn(n.filter(o=>a.isNonNullable(e.sources[o])))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(a.isNullable(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(s){this.providerError$.next({id:"ProviderNotConstructed",category:a.ErrorCategory.WTF,message:"Failed to create provider",thrown:s})}r?this.current$.next({type:t,provider:r,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const e=this.current$.getValue().destination;a.assertNonNullable(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,r=this.params.desiredState.seekState.getState(),s=r.state!==C.None;this.params.desiredState.seekState.setState({state:C.Requested,position:s?r.position:t,forcePrecise:s?r.forcePrecise:!1}),e.destroy();const n=this.providerOutput.isBuffering$;n.getValue()||n.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case he.SCREEN:return this.createScreenProvider(t);case he.CHROMECAST:return this.createChromecastProvider(t);default:return a.assertNever(e)}}createScreenProvider(e){const{sources:t,container:r,desiredState:s}=this.params,n=this.providerOutput,o={container:r,source:null,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new nb(Object.assign(Object.assign({},o),{source:l,config:qb}))}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),this.params.tuning.useDashJs?new VS(Object.assign(Object.assign({},o),{source:l,format:e,config:Wb})):new _b(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),hr||!this.params.tuning.useHlsJs?new Cb(Object.assign(Object.assign({},o),{source:l})):new Rb(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.HLS_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Nb(Object.assign(Object.assign({},o),{source:l,config:zb}))}case exports.VideoFormat.MPEG:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Db(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new tb(Object.assign(Object.assign({},o),{source:l,config:Yb}))}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Bb({container:r,source:l,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:r,desiredState:s,meta:n}=this.params,o=this.providerOutput,l=this.params.dependencies.chromecastInitializer.connection$.getValue();return a.assertNonNullable(l),new dS({connection:l,meta:n,container:r,source:t,format:e,desiredState:s,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?he.CHROMECAST:he.SCREEN}chooseFormat(e){switch(e){case he.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case he.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return a.assertNever(e)}}skipFormat(e){switch(e){case he.SCREEN:return this.screenFormatsIterator.next();case he.CHROMECAST:return this.chromecastFormatsIterator.next();default:return a.assertNever(e)}}handleNoFormatsError(e){switch(e){case he.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case he.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return a.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const r=s=>{const n=new URL(s);return n.host=t,n.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:r(e.url)})}return oi(Object.entries(e).map(([s,n])=>[s,r(n)]))}initProviderErrorHandling(){const e=new a.Subscription;let t=!1,r=0;return e.add(a.merge(this.providerOutput.error$,Gb({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:zn.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(a.filter(({type:s})=>s!==void 0))}).pipe(a.map(s=>({id:`ProviderHangup:${s}`,category:a.ErrorCategory.WTF,message:`A ${s} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const s=this.params.desiredState.playbackState.transitionEnded$.pipe(a.filter(({to:n})=>n===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>t=!0);e.add(s)})),e.add(this.providerError$.subscribe(s=>{if(this.current$.getValue().destination===he.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=s.category===a.ErrorCategory.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=r<zn.providerErrorLimit;o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(r++,this.reinitProvider()):this.switchToNextProvider()}})),e}}const Wn=(i,e,t)=>t*e+(1-t)*i;class Qn{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.slow=this.fast=this.smoothed=this.prevReported=e.initial,this.smoothed$=new a.ValueSubject(e.initial),this.debounced$=new a.ValueSubject(e.initial);const r=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ie(`raw_${r}`),this.smoothedSeries$=new Ie(`smoothed_${r}`),this.reportedSeries$=new Ie(`reported_${r}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let d=0;d<this.pastMeasures.length;d++)this.pastMeasures[d]!==void 0&&(t+=Math.pow(this.pastMeasures[d]-this.smoothed,2),r++);t/=r;const s=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*s,o=this.smoothed-this.params.deviationFactor*s;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.slow=Wn(this.slow,e,this.params.emaAlphaSlow),this.fast=Wn(this.fast,e,this.params.emaAlphaFast);const l=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=l(this.slow,this.fast),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>n||this.smoothed<o)&&(a.isNullable(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))}}var ge;(function(i){i[i.LOCAL_STORAGE=0]="LOCAL_STORAGE",i[i.SESSION_STORAGE=1]="SESSION_STORAGE",i[i.RUNTIME=2]="RUNTIME"})(ge||(ge={}));const Ml=new Map;let ut=ge.RUNTIME;const cs=`vk-videoplayer-dummy-key-${Math.random()}`,Jb=()=>{try{localStorage.setItem(cs,"test"),localStorage.removeItem(cs),ut=ge.LOCAL_STORAGE}catch(i){if(i instanceof DOMException||i instanceof TypeError)try{sessionStorage.getItem(cs),ut=ge.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)ut=ge.RUNTIME;else throw e}else throw i}};Jb();const Kb=i=>{var e,t;switch(ut){case ge.LOCAL_STORAGE:return(e=localStorage.getItem(i))!==null&&e!==void 0?e:void 0;case ge.SESSION_STORAGE:return(t=sessionStorage.getItem(i))!==null&&t!==void 0?t:void 0;case ge.RUNTIME:return Ml.get(i);default:a.assertNever(ut)}},Jn=(i,e)=>{switch(ut){case ge.LOCAL_STORAGE:try{localStorage.setItem(i,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case ge.SESSION_STORAGE:try{sessionStorage.setItem(i,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case ge.RUNTIME:return void Ml.set(i,e);default:a.assertNever(ut)}},Xb=5e3,Kn="one_video_throughput",Xn="one_video_rtt",Fe=window.navigator.connection,Zn=()=>{const i=Fe==null?void 0:Fe.downlink;if(a.isNonNullable(i)&&i!==10)return i*1e3},eo=()=>{const i=Fe==null?void 0:Fe.rtt;if(a.isNonNullable(i)&&i!==3e3)return i},to=(i,e,t)=>{const r=t*8,s=r/i;return r/(s+e)};class ti{constructor(e){var t,r;this.subscription=new a.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const s=ti.load(Kn)||(e.useBrowserEstimation?Zn():void 0)||Xb,n=(r=(t=ti.load(Xn))!==null&&t!==void 0?t:e.useBrowserEstimation?eo():void 0)!==null&&r!==void 0?r:0;if(this.throughput$=new a.ValueSubject(s),this.rtt$=new a.ValueSubject(n),this.rttAdjustedThroughput$=new a.ValueSubject(to(s,n,e.rttPenaltyRequestSize)),this.throughput=new Qn({initial:s,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:"throughput"}),this.rtt=new Qn({initial:n,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:"rtt"}),e.useBrowserEstimation){const o=()=>{const d=Zn();d&&this.throughput.next(d);const u=eo();a.isNonNullable(u)&&this.rtt.next(u)};Fe&&"onchange"in Fe&&this.subscription.add(a.fromEvent(Fe,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{Jn(Kn,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{Jn(Xn,o.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(a.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(a.map(({throughput:o,rtt:l})=>to(o,l,e.rttPenaltyRequestSize)),a.filter(o=>{const l=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(o-l)/l>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=a.now();const s=new a.Subscription;switch(this.subscription.add(s),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:s.add(a.fromEvent(e,"progress").pipe(a.once()).subscribe(n=>{t=n.loaded,r=a.now()}));break;case 1:case 0:s.add(a.fromEvent(e,"loadstart").subscribe(()=>{t=0,r=a.now()}));break}s.add(a.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,l=a.now(),d=o-t,u=l-r;this.addRawSpeed(d,u,1)}this.concurrentDownloads.delete(e),s.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let r=0;const s=a.now();let n=0,o=a.now();const l=u=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${u}`).catch(()=>{})},d=({done:u,value:c})=>J(this,void 0,void 0,function*(){u?(this.addRawSpeed(r,a.now()-s,1),this.concurrentDownloads.delete(e)):c&&(r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&a.now()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,a.now()-o,this.concurrentDownloads.size),n=0,o=a.now()),yield t==null?void 0:t.read().then(d,l))});this.concurrentDownloads.add(e),t==null||t.read().then(d,l)}addRawSpeed(e,t,r=1){if(ti.sanityCheck(e,t)){const s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||e<10*1024||t<=20)}static load(e){var t;const r=Kb(e);if(a.isNonNullable(r))return(t=parseInt(r,10))!==null&&t!==void 0?t:void 0}}const io={throughputEstimator:{emaAlphaSlow:.2,emaAlphaFast:.7,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:10,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.3,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},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},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,webrtc:{connectionRetryMaxNumber:3}},Zb=i=>{const e={};for(const t of Object.keys(io)){const r=io[t],s=i[t];Array.isArray(r)&&Array.isArray(s)?e[t]=s:typeof r=="object"&&typeof s=="object"?e[t]=Object.assign(Object.assign({},r),s):e[t]=s!=null?s:r}return e};var eg=({seekState:i,position$:e})=>a.merge(i.stateChangeEnded$.pipe(a.map(({to:t})=>{var r;return t.state===C.None?void 0:((r=t.position)!==null&&r!==void 0?r:NaN)/1e3}),a.filter(a.isNonNullable)),e.pipe(a.filter(()=>i.getState().state===C.None))),tg=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return a.assertNonNullable(e,`Wrong container or containerId {${i.container}}`),e};const ro=({playbackState:i,seekState:e,playbackAbort$:t,looped$:r,position$:s})=>new a.Observable(n=>{let o;const l=i.transitionEnded$.pipe(a.filter(p=>(p.from===exports.PlaybackState.PAUSED||p.from===exports.PlaybackState.STOPPED)&&p.to===exports.PlaybackState.PLAYING)),d=i.stateChangeEnded$.pipe(a.filter(p=>p.from===exports.PlaybackState.PLAYING&&p.to===exports.PlaybackState.PAUSED)),u=e.stateChangeEnded$.pipe(a.filter(({to:p})=>{var v,m;return p.state===C.Requested&&((m=(v=i.getTransition())===null||v===void 0?void 0:v.from)!==null&&m!==void 0?m:i.getState())===exports.PlaybackState.PLAYING})),c=e.stateChangeEnded$.pipe(a.filter(({from:p,to:v})=>{var m,S;return p.state===C.Applying&&v.state===C.None&&((S=(m=i.getTransition())===null||m===void 0?void 0:m.from)!==null&&S!==void 0?S:i.getState())===exports.PlaybackState.PLAYING})),h=a.merge(l,c).pipe(a.map(()=>s.getValue()),a.filter(a.isNonNullable)),f=a.merge(a.merge(d,u,t),r).pipe(a.map(()=>s.getValue()),a.filter(a.isNonNullable));return new a.Subscription().add(h.subscribe(p=>{o=p})).add(f.subscribe(p=>{if(a.isNullable(o)||o===p)return;const v={from:o,to:p};o=void 0,n.next(v)}))});class ig{constructor(e={}){if(this.subscription=new a.Subscription,this.logger=new a.Logger,this.isPlaybackStarted=!1,this.desiredState={playbackState:new Q(exports.PlaybackState.STOPPED),seekState:new Q({state:C.None}),volume:new Q({volume:1,muted:!1}),videoTrack:new Q(void 0),autoVideoTrackSwitching:new Q(!0),autoVideoTrackLimits:new Q({}),isLooped:new Q(!1),playbackRate:new Q(1),externalTextTracks:new Q([]),currentTextTrack:new Q(void 0),textTrackCuesSettings:new Q({})},this.info={playbackState$:new a.ValueSubject(exports.PlaybackState.STOPPED),position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),muted$:new a.ValueSubject(!1),volume$:new a.ValueSubject(1),availableQualities$:new a.ValueSubject([]),availableQualitiesFps$:new a.ValueSubject({}),currentQuality$:new a.ValueSubject(void 0),isAutoQualityEnabled$:new a.ValueSubject(!0),autoQualityLimitingAvailable$:new a.ValueSubject(!1),autoQualityLimits$:new a.ValueSubject({}),currentPlaybackRate$:new a.ValueSubject(1),currentBuffer$:new a.ValueSubject({start:0,end:0}),isBuffering$:new a.ValueSubject(!0),isStalled$:new a.ValueSubject(!1),isEnded$:new a.ValueSubject(!1),isLooped$:new a.ValueSubject(!1),isLive$:new a.ValueSubject(void 0),liveTime$:new a.ValueSubject(void 0),currentFormat$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),throughputEstimation$:new a.ValueSubject(void 0),rttEstimation$:new a.ValueSubject(void 0),videoBitrate$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),chromecastState$:new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new a.ValueSubject(void 0),intrinsicVideoSize$:new a.ValueSubject(void 0)},this.events={inited$:new a.Subject,started$:new a.Subject,willPause$:new a.Subject,willResume$:new a.Subject,willDestruct$:new a.Subject,watchCoverageRecord$:new a.Subject,watchCoverageLive$:new a.Subject,managedError$:new a.Subject,fatalError$:new a.Subject,ended$:new a.Subject,looped$:new a.Subject,seeked$:new a.Subject,willSeek$:new a.Subject,firstBytes$:new a.Subject,firstFrame$:new a.Subject,canplay$:new a.Subject,log$:new a.Subject},this.experimental={element$:new a.ValueSubject(void 0),enableDebugTelemetry$:new a.ValueSubject(!1),dumpTelemetry:DS},this.initLogs(),this.tuning=Zb(e),this.chromecastInitializer=new fu({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new ti(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,r,s)=>{const n=Reflect.get(t,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(l){const d=o.map(h=>JSON.stringify(h,(f,p)=>{const v=typeof p;return["number","string","boolean"].includes(v)?p:p===null?null:`<${v}>`})),u=`Player.${String(r)}`,c=`Exception calling ${u} (${d.join(", ")})`;throw this.events.fatalError$.next({id:u,category:a.ErrorCategory.WTF,message:c,thrown:l}),l}}}})}initVideo(e){var t,r,s;return this.config=e,this.domContainer=tg(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Qb({sources:e.sources,meta:(r=e.meta)!==null&&r!==void 0?r:{},failoverHosts:(s=e.failoverHosts)!==null&&s!==void 0?s:[],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.initDebugTelemetry(),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()===exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.READY),this}play(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PLAYING&&e.startTransitionTo(exports.PlaybackState.PLAYING),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PAUSED&&e.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(e,t=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:C.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){return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:this.desiredState.volume.getState().muted}),this}setMuted(e){return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(e):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:e}),this}setQuality(e){a.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const r=t.find(s=>s.quality===e);return r&&this.desiredState.videoTrack.startTransitionTo(r.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.setState(e),this}setPlaybackRate(e){var t;a.assertNonNullable(this.providerContainer);const r=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return r&&(this.desiredState.playbackRate.setState(e),r.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(r=>r.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(){a.assertNonNullable(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(a.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),r=t.state===C.None?void 0:t.position;return a.isNonNullable(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}initDesiredStateSubscriptions(){this.subscription.add(a.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(a.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(a.filter(({from:e})=>e===exports.PlaybackState.STOPPED),a.once()).subscribe(()=>{this.initedAt=a.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.pipe(a.filter(()=>!this.isPlaybackStarted),a.filter(e=>e.to===exports.PlaybackState.PLAYING)).subscribe(()=>{this.isPlaybackStarted=!0,this.events.started$.next()})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted&&this.events.willResume$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const d=this.desiredState.seekState.getState();d.state===C.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},d),{state:C.Applying})):this.events.managedError$.next({id:`WillSeekIn${d.state}`,category:a.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===C.Applying&&(this.desiredState.seekState.setState({state:C.None}),this.events.seeked$.next())})).add(e.current$.pipe(a.map(d=>d.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(a.map(d=>d.destination),a.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(a.map(d=>d.map(({quality:u})=>u).sort((u,c)=>Wi(u)?1:Wi(c)?-1:Ui(c,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(d=>{const u={};for(const c of d)c.fps&&(u[c.quality]=c.fps);this.info.availableQualitiesFps$.next(u)})).add(e.providerOutput.currentVideoTrack$.subscribe(d=>{this.info.currentQuality$.next(d==null?void 0:d.quality),this.info.videoBitrate$.next(d==null?void 0:d.bitrate);const u=e.providerOutput.element$.getValue();u&&this.info.intrinsicVideoSize$.next({width:u.videoWidth,height:u.videoHeight})})).add(e.providerOutput.hostname$.pipe(a.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(a.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(a.filterChanged()).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(a.map(d=>d?{start:d.from,end:d.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(a.map(d=>d.muted),a.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(a.map(d=>d.volume),a.filterChanged()).subscribe(this.info.volume$)).add(eg({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(a.merge(e.providerOutput.endedEvent$.pipe(a.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(a.mapTo(!1))).pipe(a.filterChanged()).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(a.map(d=>({id:"NoProviders",category:a.ErrorCategory.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(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(a.once(),a.map(()=>a.now()-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 a.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const r=new a.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(a.filter(({to:d})=>d===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>r.next(!1)));let s=0;const n=a.merge(e.providerOutput.isBuffering$,t,r).pipe(a.map(()=>{const d=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||r.getValue();return d&&!u}),a.filterChanged());this.subscription.add(n.subscribe(d=>{d?s=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(s),this.info.isStalled$.next(!1))}));const o=new a.Subscription;this.subscription.add(o);const l=a.merge(a.fromEvent(window,"beforeunload"),this.events.willDestruct$,e.current$.pipe(a.filter(d=>Boolean(d==null?void 0:d.provider))));e.providerOutput.isLive$.pipe(a.filterChanged()).subscribe(d=>{switch(a.assertNonNullable(this.providerContainer),o.unsubscribe(),d){case!0:{const u=new a.ValueSubject(void 0);o.add(this.providerContainer.providerOutput.liveTime$.subscribe(c=>u.next(c&&Math.floor(c/1e3)))),o.add(ro({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:l,looped$:this.events.looped$,position$:u}).pipe(a.map(({from:c,to:h})=>({start:c,end:h}))).subscribe(this.events.watchCoverageLive$));break}case!1:o.add(ro({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:l,position$:this.providerContainer.providerOutput.position$}).pipe(a.map(({from:u,to:c})=>({start:u,end:c}))).subscribe(this.events.watchCoverageRecord$));break}})}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(a.map(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 a.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(a.filterChanged((r,s)=>r.provider===s.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(a.filter(r=>r.length>0),a.once()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:r})=>r===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=di(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(a.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(a.map(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;a.assertNonNullable(this.providerContainer),a.assertNonNullable(t),CS(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>NS(r)),this.providerContainer.current$.subscribe(({type:r})=>Ri("provider",r)),t.duration$.subscribe(r=>Ri("duration",r)),t.availableVideoTracks$.pipe(a.filter(r=>!!r.length),a.once()).subscribe(r=>Ri("tracks",r)),this.events.fatalError$.subscribe(new Ie("fatalError")),this.events.managedError$.subscribe(new Ie("managedError")),t.position$.subscribe(new Ie("position")),t.currentVideoTrack$.pipe(a.map(r=>r==null?void 0:r.quality)).subscribe(new Ie("quality")),this.info.currentBuffer$.subscribe(new Ie("buffer")),t.isBuffering$.subscribe(new Ie("isBuffering"))].forEach(r=>this.subscription.add(r)),Ri("codecs",Fb())}}const rg=`${cu}@${du}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return a.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return a.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return a.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return a.ValueSubject}});exports.Player=ig;exports.SDK_VERSION=rg;
|