@vkontakte/videoplayer-core 2.0.87 → 2.0.88

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es2018.cjs.js CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.87
3
- * Mon, 19 Jun 2023 12:56:57 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-87/doc/
2
+ * @vkontakte/videoplayer-core v2.0.88
3
+ * Mon, 03 Jul 2023 18:19:16 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-88/doc/
5
5
  */
6
- "use strict";var go=Object.create;var ya=Object.defineProperty;var yo=Object.getOwnPropertyDescriptor;var To=Object.getOwnPropertyNames;var Eo=Object.getPrototypeOf,$o=Object.prototype.hasOwnProperty;var ko=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of To(e))!$o.call(s,a)&&a!==t&&ya(s,a,{get:()=>e[a],enumerable:!(i=yo(e,a))||i.enumerable});return s};var Ta=(s,e,t)=>(t=s!=null?go(Eo(s)):{},ko(e||!s||!s.__esModule?ya(t,"default",{value:s,enumerable:!0}):t,s));var r=require("@vkontakte/videoplayer-shared/es2018.cjs.js"),Po=require("lodash/debounce.js");const Yr="2.0.87";exports.PlaybackState=void 0;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(s){s.MPEG="MPEG",s.DASH="DASH",s.DASH_SEP="DASH_SEP",s.DASH_SEP_VK="DASH_SEP",s.DASH_WEBM="DASH_WEBM",s.DASH_WEBM_AV1="DASH_WEBM_AV1",s.DASH_WEBM_VK="DASH_WEBM",s.DASH_ONDEMAND="DASH_ONDEMAND",s.DASH_ONDEMAND_VK="DASH_ONDEMAND",s.DASH_LIVE="DASH_LIVE",s.DASH_LIVE_CMAF="DASH_LIVE_CMAF",s.DASH_LIVE_WEBM="DASH_LIVE_WEBM",s.HLS="HLS",s.HLS_ONDEMAND="HLS_ONDEMAND",s.HLS_JS="HLS",s.HLS_LIVE="HLS_LIVE",s.HLS_LIVE_CMAF="HLS_LIVE_CMAF",s.WEB_RTC_LIVE="WEB_RTC_LIVE"})(exports.VideoFormat||(exports.VideoFormat={}));var re;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(re||(re={}));exports.ChromecastState=void 0;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var O;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(O||(O={}));exports.Surface=void 0;(function(s){s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip"})(exports.Surface||(exports.Surface={}));var Ao=s=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class wo{constructor(e){var t;this.connection$=new r.ValueSubject(void 0),this.castState$=new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new r.Subject,this.realCastState$=new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new r.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const i="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${i}`}),e.isDisabled||!i)return;const a=r.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=Boolean(window.__onGCastApiAvailable);a?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||Ao("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:r.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 i,a,n;(n=(a=(i=cast.framework.CastContext.getInstance())===null||i===void 0?void 0:i.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0||n.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){r.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();r.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();r.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),i=cast.framework.CastContext.getInstance();this.subscription.add(r.fromEvent(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{var n,o;switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=i.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 r.assertNever(a.sessionState)}})).add(r.merge(r.fromEvent(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(r.tap(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),r.map(a=>a.castState)),r.observableFrom([i.getCastState()])).pipe(r.filterChanged(),r.map(_o),r.tap(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{var n;const o=a===exports.ChromecastState.CONNECTED,l=r.isNonNullable(this.connection$.getValue());if(o&&!l){const d=i.getCurrentSession();r.assertNonNullable(d);const u=d.getCastDevice(),c=(n=d.getMediaSession())===null||n===void 0?void 0:n.media.contentId;(r.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(a===exports.ChromecastState.CONNECTED?r.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:a)}))}initializeCastApi(){var e;let t,i,a;try{t=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,a=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:i,autoJoinPolicy:a}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:r.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const _o=s=>{switch(s){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 r.assertNever(s)}};var Ea=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},Be=function(s){try{return!!s()}catch(e){return!0}},Ro=Be,Ii=!Ro(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),Gr=Ii,zr=Function.prototype,Cs=zr.call,Io=Gr&&zr.bind.bind(Cs,Cs),Me=Gr?Io:function(s){return function(){return Cs.apply(s,arguments)}},Wr=Me,No=Wr({}.toString),Do=Wr("".slice),Ni=function(s){return Do(No(s),8,-1)},Co=Me,Lo=Be,xo=Ni,zi=Object,Oo=Co("".split),Bo=Lo(function(){return!zi("z").propertyIsEnumerable(0)})?function(s){return xo(s)=="String"?Oo(s,""):zi(s)}:zi,Di=function(s){return s==null},Mo=Di,Vo=TypeError,Gs=function(s){if(Mo(s))throw Vo("Can't call method on "+s);return s},Fo=Bo,Uo=Gs,jt=function(s){return Fo(Uo(s))},jo=function(){},$t={},Xt=function(s){return s&&s.Math==Math&&s},_e=Xt(typeof globalThis=="object"&&globalThis)||Xt(typeof window=="object"&&window)||Xt(typeof self=="object"&&self)||Xt(typeof Ea=="object"&&Ea)||function(){return this}()||Function("return this")(),Ls=typeof document=="object"&&document.all,Ho=typeof Ls=="undefined"&&Ls!==void 0,Qr={all:Ls,IS_HTMLDDA:Ho},Jr=Qr,qo=Jr.all,fe=Jr.IS_HTMLDDA?function(s){return typeof s=="function"||s===qo}:function(s){return typeof s=="function"},Yo=_e,Go=fe,$a=Yo.WeakMap,zo=Go($a)&&/native code/.test(String($a)),ka=fe,Kr=Qr,Wo=Kr.all,at=Kr.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:ka(s)||s===Wo}:function(s){return typeof s=="object"?s!==null:ka(s)},Qo=Be,We=!Qo(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),kt={},Jo=_e,Pa=at,xs=Jo.document,Ko=Pa(xs)&&Pa(xs.createElement),Xr=function(s){return Ko?xs.createElement(s):{}},Xo=We,Zo=Be,el=Xr,Zr=!Xo&&!Zo(function(){return Object.defineProperty(el("div"),"a",{get:function(){return 7}}).a!=7}),tl=We,il=Be,en=tl&&il(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),sl=at,al=String,rl=TypeError,rt=function(s){if(sl(s))return s;throw rl(al(s)+" is not an object")},nl=Ii,Zt=Function.prototype.call,Ve=nl?Zt.bind(Zt):function(){return Zt.apply(Zt,arguments)},zs={},Wi=zs,Qi=_e,ol=fe,Aa=function(s){return ol(s)?s:void 0},Ws=function(s,e){return arguments.length<2?Aa(Wi[s])||Aa(Qi[s]):Wi[s]&&Wi[s][e]||Qi[s]&&Qi[s][e]},ll=Me,Qs=ll({}.isPrototypeOf),ul=typeof navigator!="undefined"&&String(navigator.userAgent)||"",tn=_e,Ji=ul,wa=tn.process,_a=tn.Deno,Ra=wa&&wa.versions||_a&&_a.version,Ia=Ra&&Ra.v8,Se,yi;Ia&&(Se=Ia.split("."),yi=Se[0]>0&&Se[0]<4?1:+(Se[0]+Se[1]));!yi&&Ji&&(Se=Ji.match(/Edge\/(\d+)/),(!Se||Se[1]>=74)&&(Se=Ji.match(/Chrome\/(\d+)/),Se&&(yi=+Se[1])));var dl=yi,Na=dl,cl=Be,sn=!!Object.getOwnPropertySymbols&&!cl(function(){var s=Symbol();return!String(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Na&&Na<41}),hl=sn,an=hl&&!Symbol.sham&&typeof Symbol.iterator=="symbol",fl=Ws,pl=fe,ml=Qs,bl=an,vl=Object,rn=bl?function(s){return typeof s=="symbol"}:function(s){var e=fl("Symbol");return pl(e)&&ml(e.prototype,vl(s))},Sl=String,Js=function(s){try{return Sl(s)}catch(e){return"Object"}},gl=fe,yl=Js,Tl=TypeError,Ks=function(s){if(gl(s))return s;throw Tl(yl(s)+" is not a function")},El=Ks,$l=Di,Ci=function(s,e){var t=s[e];return $l(t)?void 0:El(t)},Ki=Ve,Xi=fe,Zi=at,kl=TypeError,Pl=function(s,e){var t,i;if(e==="string"&&Xi(t=s.toString)&&!Zi(i=Ki(t,s))||Xi(t=s.valueOf)&&!Zi(i=Ki(t,s))||e!=="string"&&Xi(t=s.toString)&&!Zi(i=Ki(t,s)))return i;throw kl("Can't convert object to primitive value")},Ti={},Al={get exports(){return Ti},set exports(s){Ti=s}},wl=!0,Da=_e,_l=Object.defineProperty,Rl=function(s,e){try{_l(Da,s,{value:e,configurable:!0,writable:!0})}catch(t){Da[s]=e}return e},Il=_e,Nl=Rl,Ca="__core-js_shared__",Dl=Il[Ca]||Nl(Ca,{}),nn=Dl,La=nn;(Al.exports=function(s,e){return La[s]||(La[s]=e!==void 0?e:{})})("versions",[]).push({version:"3.27.2",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.27.2/LICENSE",source:"https://github.com/zloirock/core-js"});var Cl=Gs,Ll=Object,Li=function(s){return Ll(Cl(s))},xl=Me,Ol=Li,Bl=xl({}.hasOwnProperty),Fe=Object.hasOwn||function(e,t){return Bl(Ol(e),t)},Ml=Me,Vl=0,Fl=Math.random(),Ul=Ml(1 .toString),on=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Ul(++Vl+Fl,36)},jl=_e,Hl=Ti,xa=Fe,ql=on,Yl=sn,Gl=an,bt=jl.Symbol,es=Hl("wks"),zl=Gl?bt.for||bt:bt&&bt.withoutSetter||ql,Te=function(s){return xa(es,s)||(es[s]=Yl&&xa(bt,s)?bt[s]:zl("Symbol."+s)),es[s]},Wl=Ve,Oa=at,Ba=rn,Ql=Ci,Jl=Pl,Kl=Te,Xl=TypeError,Zl=Kl("toPrimitive"),eu=function(s,e){if(!Oa(s)||Ba(s))return s;var t=Ql(s,Zl),i;if(t){if(e===void 0&&(e="default"),i=Wl(t,s,e),!Oa(i)||Ba(i))return i;throw Xl("Can't convert object to primitive value")}return e===void 0&&(e="number"),Jl(s,e)},tu=eu,iu=rn,Xs=function(s){var e=tu(s,"string");return iu(e)?e:e+""},su=We,au=Zr,ru=en,ei=rt,Ma=Xs,nu=TypeError,ts=Object.defineProperty,ou=Object.getOwnPropertyDescriptor,is="enumerable",ss="configurable",as="writable";kt.f=su?ru?function(e,t,i){if(ei(e),t=Ma(t),ei(i),typeof e=="function"&&t==="prototype"&&"value"in i&&as in i&&!i[as]){var a=ou(e,t);a&&a[as]&&(e[t]=i.value,i={configurable:ss in i?i[ss]:a[ss],enumerable:is in i?i[is]:a[is],writable:!1})}return ts(e,t,i)}:ts:function(e,t,i){if(ei(e),t=Ma(t),ei(i),au)try{return ts(e,t,i)}catch(a){}if("get"in i||"set"in i)throw nu("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var xi=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},lu=We,uu=kt,du=xi,Ht=lu?function(s,e,t){return uu.f(s,e,du(1,t))}:function(s,e,t){return s[e]=t,s},cu=Ti,hu=on,Va=cu("keys"),Zs=function(s){return Va[s]||(Va[s]=hu(s))},ea={},fu=zo,ln=_e,pu=at,mu=Ht,rs=Fe,ns=nn,bu=Zs,vu=ea,Fa="Object already initialized",Os=ln.TypeError,Su=ln.WeakMap,Ei,Ut,$i,gu=function(s){return $i(s)?Ut(s):Ei(s,{})},yu=function(s){return function(e){var t;if(!pu(e)||(t=Ut(e)).type!==s)throw Os("Incompatible receiver, "+s+" required");return t}};if(fu||ns.state){var ke=ns.state||(ns.state=new Su);ke.get=ke.get,ke.has=ke.has,ke.set=ke.set,Ei=function(s,e){if(ke.has(s))throw Os(Fa);return e.facade=s,ke.set(s,e),e},Ut=function(s){return ke.get(s)||{}},$i=function(s){return ke.has(s)}}else{var ct=bu("state");vu[ct]=!0,Ei=function(s,e){if(rs(s,ct))throw Os(Fa);return e.facade=s,mu(s,ct,e),e},Ut=function(s){return rs(s,ct)?s[ct]:{}},$i=function(s){return rs(s,ct)}}var Tu={set:Ei,get:Ut,has:$i,enforce:gu,getterFor:yu},Eu=Ii,un=Function.prototype,Ua=un.apply,ja=un.call,$u=typeof Reflect=="object"&&Reflect.apply||(Eu?ja.bind(Ua):function(){return ja.apply(Ua,arguments)}),ku=Ni,Pu=Me,dn=function(s){if(ku(s)==="Function")return Pu(s)},cn={},hn={},fn={}.propertyIsEnumerable,pn=Object.getOwnPropertyDescriptor,Au=pn&&!fn.call({1:2},1);hn.f=Au?function(e){var t=pn(this,e);return!!t&&t.enumerable}:fn;var wu=We,_u=Ve,Ru=hn,Iu=xi,Nu=jt,Du=Xs,Cu=Fe,Lu=Zr,Ha=Object.getOwnPropertyDescriptor;cn.f=wu?Ha:function(e,t){if(e=Nu(e),t=Du(t),Lu)try{return Ha(e,t)}catch(i){}if(Cu(e,t))return Iu(!_u(Ru.f,e,t),e[t])};var xu=Be,Ou=fe,Bu=/#|\.prototype\./,qt=function(s,e){var t=Vu[Mu(s)];return t==Uu?!0:t==Fu?!1:Ou(e)?xu(e):!!e},Mu=qt.normalize=function(s){return String(s).replace(Bu,".").toLowerCase()},Vu=qt.data={},Fu=qt.NATIVE="N",Uu=qt.POLYFILL="P",ju=qt,qa=dn,Hu=Ks,qu=Ii,Yu=qa(qa.bind),mn=function(s,e){return Hu(s),e===void 0?s:qu?Yu(s,e):function(){return s.apply(e,arguments)}},ti=_e,Gu=$u,zu=dn,Wu=fe,Qu=cn.f,Ju=ju,ht=zs,Ku=mn,ft=Ht,Ya=Fe,Xu=function(s){var e=function(t,i,a){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,a)}return Gu(s,this,arguments)};return e.prototype=s.prototype,e},Oi=function(s,e){var t=s.target,i=s.global,a=s.stat,n=s.proto,o=i?ti:a?ti[t]:(ti[t]||{}).prototype,l=i?ht:ht[t]||ft(ht,t,{})[t],d=l.prototype,u,c,h,f,p,b,g,S,m;for(f in e)u=Ju(i?f:t+(a?".":"#")+f,s.forced),c=!u&&o&&Ya(o,f),b=l[f],c&&(s.dontCallGetSet?(m=Qu(o,f),g=m&&m.value):g=o[f]),p=c&&g?g:e[f],!(c&&typeof b==typeof p)&&(s.bind&&c?S=Ku(p,ti):s.wrap&&c?S=Xu(p):n&&Wu(p)?S=zu(p):S=p,(s.sham||p&&p.sham||b&&b.sham)&&ft(S,"sham",!0),ft(l,f,S),n&&(h=t+"Prototype",Ya(ht,h)||ft(ht,h,{}),ft(ht[h],f,p),s.real&&d&&(u||!d[f])&&ft(d,f,p)))},Bs=We,Zu=Fe,bn=Function.prototype,ed=Bs&&Object.getOwnPropertyDescriptor,ta=Zu(bn,"name"),td=ta&&function(){}.name==="something",id=ta&&(!Bs||Bs&&ed(bn,"name").configurable),sd={EXISTS:ta,PROPER:td,CONFIGURABLE:id},vn={},ad=Math.ceil,rd=Math.floor,nd=Math.trunc||function(e){var t=+e;return(t>0?rd:ad)(t)},od=nd,ia=function(s){var e=+s;return e!==e||e===0?0:od(e)},ld=ia,ud=Math.max,dd=Math.min,cd=function(s,e){var t=ld(s);return t<0?ud(t+e,0):dd(t,e)},hd=ia,fd=Math.min,pd=function(s){return s>0?fd(hd(s),9007199254740991):0},md=pd,sa=function(s){return md(s.length)},bd=jt,vd=cd,Sd=sa,Ga=function(s){return function(e,t,i){var a=bd(e),n=Sd(a),o=vd(i,n),l;if(s&&t!=t){for(;n>o;)if(l=a[o++],l!=l)return!0}else for(;n>o;o++)if((s||o in a)&&a[o]===t)return s||o||0;return!s&&-1}},gd={includes:Ga(!0),indexOf:Ga(!1)},yd=Me,os=Fe,Td=jt,Ed=gd.indexOf,$d=ea,za=yd([].push),kd=function(s,e){var t=Td(s),i=0,a=[],n;for(n in t)!os($d,n)&&os(t,n)&&za(a,n);for(;e.length>i;)os(t,n=e[i++])&&(~Ed(a,n)||za(a,n));return a},Sn=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Pd=kd,Ad=Sn,wd=Object.keys||function(e){return Pd(e,Ad)},_d=We,Rd=en,Id=kt,Nd=rt,Dd=jt,Cd=wd;vn.f=_d&&!Rd?Object.defineProperties:function(e,t){Nd(e);for(var i=Dd(t),a=Cd(t),n=a.length,o=0,l;n>o;)Id.f(e,l=a[o++],i[l]);return e};var Ld=Ws,xd=Ld("document","documentElement"),Od=rt,Bd=vn,Wa=Sn,Md=ea,Vd=xd,Fd=Xr,Ud=Zs,Qa=">",Ja="<",Ms="prototype",Vs="script",gn=Ud("IE_PROTO"),ls=function(){},yn=function(s){return Ja+Vs+Qa+s+Ja+"/"+Vs+Qa},Ka=function(s){s.write(yn("")),s.close();var e=s.parentWindow.Object;return s=null,e},jd=function(){var s=Fd("iframe"),e="java"+Vs+":",t;return s.style.display="none",Vd.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(yn("document.F=Object")),t.close(),t.F},ii,mi=function(){try{ii=new ActiveXObject("htmlfile")}catch(e){}mi=typeof document!="undefined"?document.domain&&ii?Ka(ii):jd():Ka(ii);for(var s=Wa.length;s--;)delete mi[Ms][Wa[s]];return mi()};Md[gn]=!0;var Tn=Object.create||function(e,t){var i;return e!==null?(ls[Ms]=Od(e),i=new ls,ls[Ms]=null,i[gn]=e):i=mi(),t===void 0?i:Bd.f(i,t)},Hd=Be,qd=!Hd(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),Yd=Fe,Gd=fe,zd=Li,Wd=Zs,Qd=qd,Xa=Wd("IE_PROTO"),Fs=Object,Jd=Fs.prototype,En=Qd?Fs.getPrototypeOf:function(s){var e=zd(s);if(Yd(e,Xa))return e[Xa];var t=e.constructor;return Gd(t)&&e instanceof t?t.prototype:e instanceof Fs?Jd:null},Kd=Ht,$n=function(s,e,t,i){return i&&i.enumerable?s[e]=t:Kd(s,e,t),s},Xd=Be,Zd=fe,ec=at,tc=Tn,Za=En,ic=$n,sc=Te,Us=sc("iterator"),kn=!1,xe,us,ds;[].keys&&(ds=[].keys(),"next"in ds?(us=Za(Za(ds)),us!==Object.prototype&&(xe=us)):kn=!0);var ac=!ec(xe)||Xd(function(){var s={};return xe[Us].call(s)!==s});ac?xe={}:xe=tc(xe);Zd(xe[Us])||ic(xe,Us,function(){return this});var Pn={IteratorPrototype:xe,BUGGY_SAFARI_ITERATORS:kn},rc=Te,nc=rc("toStringTag"),An={};An[nc]="z";var aa=String(An)==="[object z]",oc=aa,lc=fe,bi=Ni,uc=Te,dc=uc("toStringTag"),cc=Object,hc=bi(function(){return arguments}())=="Arguments",fc=function(s,e){try{return s[e]}catch(t){}},Bi=oc?bi:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=fc(e=cc(s),dc))=="string"?t:hc?bi(e):(i=bi(e))=="Object"&&lc(e.callee)?"Arguments":i},pc=aa,mc=Bi,bc=pc?{}.toString:function(){return"[object "+mc(this)+"]"},vc=aa,Sc=kt.f,gc=Ht,yc=Fe,Tc=bc,Ec=Te,er=Ec("toStringTag"),wn=function(s,e,t,i){if(s){var a=t?s:s.prototype;yc(a,er)||Sc(a,er,{configurable:!0,value:e}),i&&!vc&&gc(a,"toString",Tc)}},$c=Pn.IteratorPrototype,kc=Tn,Pc=xi,Ac=wn,wc=$t,_c=function(){return this},Rc=function(s,e,t,i){var a=e+" Iterator";return s.prototype=kc($c,{next:Pc(+!i,t)}),Ac(s,a,!1,!0),wc[a]=_c,s},Ic=Oi,Nc=Ve,_n=sd,Dc=Rc,Cc=En,Lc=wn,tr=$n,xc=Te,ir=$t,Rn=Pn,Oc=_n.PROPER;_n.CONFIGURABLE;Rn.IteratorPrototype;var si=Rn.BUGGY_SAFARI_ITERATORS,cs=xc("iterator"),sr="keys",ai="values",ar="entries",Bc=function(){return this},Mc=function(s,e,t,i,a,n,o){Dc(t,e,i);var l=function(m){if(m===a&&f)return f;if(!si&&m in c)return c[m];switch(m){case sr:return function(){return new t(this,m)};case ai:return function(){return new t(this,m)};case ar:return function(){return new t(this,m)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=s.prototype,h=c[cs]||c["@@iterator"]||a&&c[a],f=!si&&h||l(a),p=e=="Array"&&c.entries||h,b,g,S;if(p&&(b=Cc(p.call(new s)),b!==Object.prototype&&b.next&&(Lc(b,d,!0,!0),ir[d]=Bc)),Oc&&a==ai&&h&&h.name!==ai&&(u=!0,f=function(){return Nc(h,this)}),a)if(g={values:l(ai),keys:n?f:l(sr),entries:l(ar)},o)for(S in g)(si||u||!(S in c))&&tr(c,S,g[S]);else Ic({target:e,proto:!0,forced:si||u},g);return o&&c[cs]!==f&&tr(c,cs,f,{name:a}),ir[e]=f,g},Vc=function(s,e){return{value:s,done:e}},Fc=jt,ra=jo,rr=$t,In=Tu,Uc=kt.f,jc=Mc,ri=Vc,Hc=wl,qc=We,Nn="Array Iterator",Yc=In.set,Gc=In.getterFor(Nn);jc(Array,"Array",function(s,e){Yc(this,{type:Nn,target:Fc(s),index:0,kind:e})},function(){var s=Gc(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,ri(void 0,!0)):t=="keys"?ri(i,!1):t=="values"?ri(e[i],!1):ri([i,e[i]],!1)},"values");var nr=rr.Arguments=rr.Array;ra();ra();ra();if(!Hc&&qc&&nr.name!=="values")try{Uc(nr,"name",{value:"values"})}catch(s){}var zc=Te,Wc=$t,Qc=zc("iterator"),Jc=Array.prototype,Kc=function(s){return s!==void 0&&(Wc.Array===s||Jc[Qc]===s)},Xc=Bi,or=Ci,Zc=Di,eh=$t,th=Te,ih=th("iterator"),Dn=function(s){if(!Zc(s))return or(s,ih)||or(s,"@@iterator")||eh[Xc(s)]},sh=Ve,ah=Ks,rh=rt,nh=Js,oh=Dn,lh=TypeError,uh=function(s,e){var t=arguments.length<2?oh(s):e;if(ah(t))return rh(sh(t,s));throw lh(nh(s)+" is not iterable")},dh=Ve,lr=rt,ch=Ci,hh=function(s,e,t){var i,a;lr(s);try{if(i=ch(s,"return"),!i){if(e==="throw")throw t;return t}i=dh(i,s)}catch(n){a=!0,i=n}if(e==="throw")throw t;if(a)throw i;return lr(i),t},fh=mn,ph=Ve,mh=rt,bh=Js,vh=Kc,Sh=sa,ur=Qs,gh=uh,yh=Dn,dr=hh,Th=TypeError,vi=function(s,e){this.stopped=s,this.result=e},cr=vi.prototype,Eh=function(s,e,t){var i=t&&t.that,a=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),d=fh(e,i),u,c,h,f,p,b,g,S=function(v){return u&&dr(u,"normal",v),new vi(!0,v)},m=function(v){return a?(mh(v),l?d(v[0],v[1],S):d(v[0],v[1])):l?d(v,S):d(v)};if(n)u=s.iterator;else if(o)u=s;else{if(c=yh(s),!c)throw Th(bh(s)+" is not iterable");if(vh(c)){for(h=0,f=Sh(s);f>h;h++)if(p=m(s[h]),p&&ur(cr,p))return p;return new vi(!1)}u=gh(s,c)}for(b=n?s.next:u.next;!(g=ph(b,u)).done;){try{p=m(g.value)}catch(v){dr(u,"throw",v)}if(typeof p=="object"&&p&&ur(cr,p))return p}return new vi(!1)},$h=Xs,kh=kt,Ph=xi,Ah=function(s,e,t){var i=$h(e);i in s?kh.f(s,i,Ph(0,t)):s[i]=t},wh=Oi,_h=Eh,Rh=Ah;wh({target:"Object",stat:!0},{fromEntries:function(e){var t={};return _h(e,function(i,a){Rh(t,i,a)},{AS_ENTRIES:!0}),t}});var Ih=zs,Nh=Ih.Object.fromEntries,Dh={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},Ch=Dh,Lh=_e,xh=Bi,Oh=Ht,hr=$t,Bh=Te,fr=Bh("toStringTag");for(var hs in Ch){var pr=Lh[hs],fs=pr&&pr.prototype;fs&&xh(fs)!==fr&&Oh(fs,fr,hs),hr[hs]=hr.Array}var Mh=Nh,Vh=Mh,Fh=Vh,Uh=Fh,Yt=Uh,St;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(St||(St={}));var gt=(s,e=0,t=St.OFFSET_P)=>{switch(t){case St.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case St.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}default:r.assertNever(t)}return s},P=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};exports.VideoQuality=void 0;(function(s){s.INVARIANT="Invariant quality",s.Q_144P="144p",s.Q_240P="240p",s.Q_360P="360p",s.Q_480P="480p",s.Q_720P="720p",s.Q_1080P="1080p",s.Q_1440P="1440p",s.Q_2160P="2160p",s.Q_4320P="4320p"})(exports.VideoQuality||(exports.VideoQuality={}));const ye={[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}},Si=(s,e)=>ye[s].height>ye[e].height,jh=(s,e)=>ye[s].height>=ye[e].height,Mt=(s,e)=>ye[s].height<ye[e].height,Hh=(s,e)=>ye[s].height<=ye[e].height,qh=s=>s.sort((e,t)=>e===t?0:e===exports.VideoQuality.INVARIANT?1:t===exports.VideoQuality.INVARIANT?-1:Mt(e,t)?1:-1)[0],Yh=Object.keys(ye).sort((s,e)=>Mt(s,e)?-1:1),nt=({width:s,height:e})=>{const t=Math.min(s,e),i=Math.max(s,e);return Yh.find(a=>{const n=ye[a];return n.width>=i&&n.height>=t})},Gh=s=>ye[s].height,ki=s=>s===exports.VideoQuality.INVARIANT;class Q{constructor(e){this.transitionStarted$=new r.Subject,this.transitionEnded$=new r.Subject,this.transitionUpdated$=new r.Subject,this.forceChanged$=new r.Subject,this.stateChangeStarted$=r.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=r.merge(this.transitionEnded$,this.forceChanged$),this.state=e}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||r.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:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}const zh=s=>{switch(s){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.DASH_WEBM_AV1:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_CMAF:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return r.assertNever(s)}};var C;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(C||(C={}));const Wh=5,Qh=5,Jh=500,mr=7e3;class Kh{constructor(e){this.subscription=new r.Subscription,this.loadMediaTimeoutSubscription=new r.Subscription,this.videoState=new Q(C.STOPPED),this.syncPlayback=()=>{const i=this.videoState.getState(),a=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: ${i}; videoTransition: ${JSON.stringify(a)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){i!==C.STOPPED&&(this.videoState.startTransitionTo(C.STOPPED),this.stop());return}if(!a){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===O.Requested&&i!==C.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(i){case C.PLAYING:case C.PAUSED:case C.READY:break;case C.STOPPED:this.videoState.startTransitionTo(C.READY),this.prepare();break;default:r.assertNever(i)}break}case exports.PlaybackState.PLAYING:{switch(i){case C.PLAYING:break;case C.PAUSED:this.videoState.startTransitionTo(C.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case C.READY:this.videoState.startTransitionTo(C.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case C.STOPPED:this.videoState.startTransitionTo(C.READY),this.prepare();break;default:r.assertNever(i)}break}case exports.PlaybackState.PAUSED:{switch(i){case C.PLAYING:this.videoState.startTransitionTo(C.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case C.PAUSED:break;case C.READY:this.videoState.startTransitionTo(C.PAUSED),this.videoState.setState(C.PAUSED);break;case C.STOPPED:this.videoState.startTransitionTo(C.READY),this.prepare();break;default:r.assertNever(i)}break}default:r.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(zh(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new r.Subscription;this.subscription.add(e),this.subscription.add(r.merge(this.videoState.stateChangeStarted$.pipe(r.map(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(r.map(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));const t=(a,n)=>this.subscription.add(a.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const a=new r.Subject;e.add(a.pipe(r.debounce(Jh)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(r.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===O.Applying||Math.abs(l-n)>Wh)&&a.next(l),n=l})),e.add(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);const{remotePlayer:n}=this.params.connection,o=a.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<Qh&&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:r.assertNever(o)}}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});const i=r.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(C.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(C.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:O.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===C.PAUSED||e===C.PLAYING)&&(this.videoState.setState(C.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)===C.PLAYING||e===C.PAUSED)&&(this.videoState.setState(C.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===C.READY&&this.videoState.setState(C.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()!==C.STOPPED&&this.videoState.setState(C.STOPPED)}handleRemoteVolumeChange(e){var t,i;const a=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:a.volume,muted:(i=e.muted)!==null&&i!==void 0?i:a.muted};(n.volume!==a.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const i=this.params.source;let a,n,o;switch(e){case exports.VideoFormat.MPEG:{const c=i[e];r.assertNonNullable(c);const h=qh(Object.keys(c));r.assertNonNullable(h);const f=c[h];r.assertNonNullable(f),a=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=i[e];r.assertNonNullable(c),a=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:case exports.VideoFormat.DASH_WEBM_AV1:{const c=i[e];r.assertNonNullable(c),a=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=i[e];r.assertNonNullable(c),a=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const c=i[e];r.assertNonNullable(c),a=gt(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:r.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 r.assertNever(e)}const l=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:a,n);l.contentUrl=a,l.streamType=o,l.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:d,subtitle:u}=this.params.meta;return r.isNonNullable(d)&&(l.metadata.title=d),r.isNonNullable(u)&&(l.metadata.subtitle=u),l}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===O.Applying||i.state===O.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((a,n)=>{this.loadMediaTimeoutSubscription.add(r.timeout(mr).subscribe(()=>n(`timeout(${mr})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===O.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},a=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:r.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:a})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}class br{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;const i=this.listeners[e];for(let a=0,n=i.length;a<n;a++)if(i[a].callback===t){i.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const i=this.listeners[e.type].slice();for(let a=0,n=i.length;a<n;a++){const o=i[a];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 Cn extends br{constructor(){super(),this.listeners||br.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 Ln=class{constructor(){Object.defineProperty(this,"signal",{value:new Cn,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(a){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(a){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Ln.prototype[Symbol.toStringTag]="AbortController",Cn.prototype[Symbol.toStringTag]="AbortSignal");function xn(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function Xh(s){typeof s=="function"&&(s={fetch:s});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=s;if(!xn({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||a)&&(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,b)=>{c.addEventListener("abort",()=>b(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,o(d,u)])}return o(d,u)},Request:n}}const Mi=xn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),On=Mi?Xh({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,yt=Mi?On.fetch:window.fetch;Mi?On.Request:window.Request;const st=Mi?Ln:window.AbortController,Lt=s=>s.range?s.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class Vt{constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){var t;const{url:i}=e.request,a=(t=this.dashJsRequestQueue.get(i))!==null&&t!==void 0?t:[];a.push(e),this.dashJsRequestQueue.set(i,a)}async executeNextRequests(){for(const[e,t]of this.dashJsRequestQueue.entries()){const i=this.activeRequests.get(e);if(i){t.length&&this.onBigRequestProgress(i);const a=t[0];if(!a||!a.request.range)continue;const[n,o]=Lt(a.request);if(n>=i.from&&o<=i.to)continue;this.activeRequests.delete(e)}if(t.length){const a=this.sendBigRequest(e,t.map(({request:n})=>n));this.activeRequests.set(e,a)}}}abort(e){var t;if(e){const{request:i}=e,a=((t=this.dashJsRequestQueue.get(i.url))!==null&&t!==void 0?t:[]).includes(e),n=this.activeRequests.get(i.url);a&&n&&n.abortController.abort()}else for(const{abortController:i}of this.activeRequests.values())i.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const i=t.map(Lt),a=i[0][0];let n=i[0][1];for(let f=1;f<i.length&&n<this.params.minDataSize;f++){const p=i[f][1];p-a<=2*this.params.minDataSize&&(n=Math.max(n,p))}a===0?n=Math.max(n,a+this.params.minInitSize):n=Math.max(n,a+this.params.minDataSize);const o=new URL(e,location.href);o.searchParams.append("bytes",`${a}-${n}`);const l=o.toString(),d=new st,u=d.signal,c={url:e,from:a,to:n,loaded:0,data:null,abortController:d};u.addEventListener("abort",()=>this.onBigRequestAbort(c));const h=f=>{var p,b;throw(b=(p=this.params).onError)===null||b===void 0||b.call(p,{id:"BigRequestParsing",category:r.ErrorCategory.PARSER,message:"Error parsing response data",thrown:f}),f};return yt(l,{signal:u}).then(f=>{var p,b,g;if(c.response=f,!f.ok||!f.body){this.onBigRequestError(c);return}const[S,m]=f.body.tee();(b=(p=this.params).onDownloadStream)===null||b===void 0||b.call(p,m);const v=S.getReader(),y=parseInt((g=f.headers.get("Content-Length"))!==null&&g!==void 0?g:"",10)||n-a+1;c.data=new ArrayBuffer(y);const T=new Uint8Array(c.data),E=async({done:A,value:L})=>{A?this.onBigRequestProgress(c):L&&(T.set(L,c.loaded),c.loaded+=L.byteLength,this.onBigRequestProgress(c),await(v==null?void 0:v.read().then(E,Vt.suppressStreamErrors).catch(h)))};v==null||v.read().then(E,Vt.suppressStreamErrors).catch(h)},Vt.suppressAbort).catch(f=>this.onBigRequestError(c,f)),c}onBigRequestProgress({url:e,from:t,to:i,loaded:a,data:n,response:o}){var l,d,u,c,h,f,p,b;if(!this.activeRequests.has(e)||!n)return;const g=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const S of g){const{request:m}=S,[v,y]=Lt(m),T=v>=t&&y<=t+a,E=t>=v&&t+a<y,A=n.slice(v-t,Math.min(y-t+1,a));if((T||E)&&(m.requestStartDate=(d=m.requestStartDate)!==null&&d!==void 0?d:new Date,m.firstByteDate=(u=m.firstByteDate)!==null&&u!==void 0?u:new Date,m.bytesLoaded=A.byteLength,m.bytesTotal=i-t),T){m.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((c=this.dashJsRequestQueue.get(e))!==null&&c!==void 0?c:[]).filter(R=>R!==S)),(h=S.success)===null||h===void 0||h.call(S,A,"",e);const L=o?Array.from(o.headers.entries()).map(([R,N])=>`${R}: ${N}`).join(`\r
7
- `):"";(f=this.dashMetrics)===null||f===void 0||f.addHttpRequest(m,e,(p=o==null?void 0:o.status)!==null&&p!==void 0?p:200,L,[])}else E&&((b=S.progress)===null||b===void 0||b.call(S,{loaded:a,total:i-t,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:t,to:i},a){var n,o,l,d;if((o=(n=this.params).onError)===null||o===void 0||o.call(n,{id:"BigRequest",category:r.ErrorCategory.NETWORK,message:"Download error",thrown:a}),!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]=Lt(c.request);(h>=t&&h<i||f>t&&f<=i)&&((d=c==null?void 0:c.error)===null||d===void 0||d.call(c,c.request,String(a)))}if(this.activeRequests.delete(e),a)throw a}onBigRequestAbort({url:e,from:t,to:i}){var a,n;if(!this.activeRequests.has(e))return;const o=(a=this.dashJsRequestQueue.get(e))!==null&&a!==void 0?a:[];for(const l of o){const[d,u]=Lt(l.request);(d>=t&&d<i||u>t&&u<=i)&&((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 Pi{constructor(e,t,i){this.baseLoader=e,this.config=i,this.bigRequest=t,t.setMetrics(i.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(Pi.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;Pi.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const Zh=(s,e)=>t=>({create:i=>{const a=s(t).create(i);return new Pi(a,e,i)}}),ef=(s,e)=>{const t=new Vt(e);return s.extend("SchemeLoaderFactory",function(){const{parent:i}=this,a=i.getLoader;return{getLoader:n=>{const o=a(n);return Zh(o,t)}}},!0),()=>t.destroy()};var tf=s=>{let e,t=!1,i=!1;s.on("playbackTimeUpdated",({timeToEnd:a})=>{i=a<=3,t&&i&&(e==null||e())}),s.extend("MediaSourceController",function(){const{parent:a}=this,n=a.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&i&&(e==null||e())}}},!0)},sf=s=>{const e=new r.ValueSubject(1/0),t=new r.Subject,i=new r.ValueSubject(void 0),a=new r.ValueSubject(void 0);let n=NaN,o=!1;const l=()=>{n=Date.now(),o=!1},d=c=>{var h,f,p,b,g;const S=Yt(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(y=>y.split(": ")));if("x-playback-duration"in S||"x-playback-duration-millis"in S){const y=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:y*1e3)!==null&&p!==void 0?p:NaN;r.isNonNullable(E)&&!isNaN(E)&&e.next(E)}const m=(b=S["x-delivery-type"])!==null&&b!==void 0?b:exports.HttpConnectionType.HTTP1,v=(g={1:!0,0:!1}[S["x-reused"]])!==null&&g!==void 0?g:void 0;i.next(m),a.next(v)},u=c=>{c.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return s.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,b=f.progress;f.onload=function(...g){return d(this),p(...g)},f.progress=function(...g){return u(this),b(...g)},l()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:a,connectionType$:i}},Tt=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},af=s=>s.extend("RequestModifier",()=>({modifyRequestURL:Tt}),!0),rf=s=>{s.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[a,n]=i.request.range.split("-").map(l=>parseInt(l,10)),o=new URL(i.request.url,location.href);o.searchParams.append("bytes",`${a}-${n}`),i.request.url=o.toString(),i.request.range=void 0}t(i)}}},!0)};const ge=(s,e,t,{equal:i=(o,l)=>o===l,changed$:a,onError:n}={})=>{const o=s.getState(),l=e(),d=r.isNullable(a),u=new r.Subscription;return a&&u.add(a.subscribe(c=>{const h=s.getState();i(c,h)&&s.setState(c)},n)),i(l,o)||(t(o),d&&s.setState(o)),u.add(s.stateChangeStarted$.subscribe(c=>{t(c.to),d&&s.setState(c.to)},n)),u},ot=(s,e,t)=>ge(e,()=>s.loop,i=>{r.isNonNullable(i)&&(s.loop=i)},{onError:t}),Ue=(s,e,t,i)=>ge(e,()=>({muted:s.muted,volume:s.volume}),a=>{r.isNonNullable(a)&&(s.muted=a.muted,s.volume=a.volume)},{equal:(a,n)=>a===n||(a==null?void 0:a.muted)===(n==null?void 0:n.muted)&&(a==null?void 0:a.volume)===(n==null?void 0:n.volume),changed$:t,onError:i}),Qe=(s,e,t,i)=>ge(e,()=>s.playbackRate,a=>{r.isNonNullable(a)&&(s.playbackRate=a)},{changed$:t,onError:i}),nf=s=>["__",s.language,s.label].join("|"),of=(s,e)=>{if(s.id===e)return!0;const[t,i,a]=e.split("|");return s.language===i&&s.label===a};class Re{constructor(){this.available$=new r.Subject,this.current$=new r.ValueSubject(void 0),this.error$=new r.Subject,this.subscription=new r.Subscription,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const a=n=>{this.error$.next({id:"TextTracksManager",category:r.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(ge(t.internalTextTracks,()=>Object.values(this.internalTracks),n=>{r.isNonNullable(n)&&this.setInternal(n)},{equal:(n,o)=>r.isNonNullable(n)&&r.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},d)=>l===o[d].id),changed$:this.available$.pipe(r.map(n=>n.filter(({type:o})=>o==="internal"))),onError:a})),this.subscription.add(ge(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{r.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>r.isNonNullable(n)&&r.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},d)=>l===o[d].id),changed$:this.available$.pipe(r.map(n=>n.filter(({type:o})=>o==="external"))),onError:a})),this.subscription.add(ge(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:a})),this.subscription.add(ge(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){r.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(r.fromEvent(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();this.select(i)})),this.subscription.add(r.merge(r.fromEvent(e,"addtrack"),r.fromEvent(e,"removetrack"),r.observableFrom(["init"])).pipe(r.map(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),r.filterChanged((i,a)=>i.length===a.length&&i.every(({id:n},o)=>n===a[o].id))).subscribe(this.available$)),this.subscription.add(r.merge(r.fromEvent(e,"change"),r.observableFrom(["init"])).pipe(r.map(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),r.map(i=>i&&this.htmlTextTrackToITextTrack(i).id),r.filterChanged()).subscribe(this.current$));const t=i=>{var a,n;return this.applyCueSettings((n=(a=i.target)===null||a===void 0?void 0:a.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(r.fromEvent(e,"addtrack").subscribe(i=>{var a,n;(a=i.track)===null||a===void 0||a.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=i.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(r.fromEvent(e,"removetrack").subscribe(i=>{var a;(a=i.track)===null||a===void 0||a.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const a=i;r.isNonNullable(t.align)&&(a.align=t.align),r.isNonNullable(t.position)&&(a.position=t.position),r.isNonNullable(t.size)&&(a.size=t.size),r.isNonNullable(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){r.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Re.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,a=e.id!==""?e.id:nf(e);return this.externalTracks.has(a)?{id:a,type:"external",language:t,label:i,url:this.externalTracks.get(a).url}:{id:a,type:"internal",language:t,label:i,url:this.internalTracks.get(a).url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.id===""&&e.label===""&&e.language==="")}setExternal(e){e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){e.filter(({id:t})=>!this.internalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.internalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}select(e){r.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))r.isNonNullable(e)&&of(t,e)?t.mode="showing":t.mode="disabled"}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){r.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),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){r.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const na=s=>{s.removeAttribute("src"),s.load()},lf=s=>{try{s.pause(),s.playbackRate=0,na(s),s.remove()}catch(e){console.error(e)}};class uf{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}}const js=window.WeakMap?new WeakMap:new uf,je=s=>{let e=s.querySelector("video");const t=Boolean(e);return e?na(e):(e=document.createElement("video"),s.appendChild(e)),js.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},He=s=>{const e=js.get(s);js.delete(s),e?na(s):lf(s)};class oa{constructor(){this.pausedTime=0,this.streamOffset=0,this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}}const Bn=s=>{var e;let t=s;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},vr=s=>{const e=Bn(s);return Boolean(e&&e.fullscreenElement&&e.fullscreenElement===s)},df=s=>{const e=Bn(s);return Boolean(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)};var Mn=()=>{const{userAgent:s}=window.navigator;return!/chrome/i.test(s)&&/webkit|safari|khtml/i.test(s)};const Hs=3;class cf{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let a=this._source.buffered.start(t);const n=this._source.buffered.end(t);a>e&&a-e<Hs&&(a=e),this._buffer.push({from:a,to:n,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||Hs))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:a,to:n})=>{const o=a>=e&&a<t,l=n>=e&&n<t;o&&l||(o?i(t,n):l?i(a,e):a<e&&n>t?(i(t,n),i(a,e)):i(a,n))})}destroy(){this._buffer=[]}}var Vn=(s,e,t=Hs)=>{let i=0,a=0;for(let n=0;n<s.length;n++){const o=s.start(n),l=s.end(n);if(o<=e&&e<=l){if(i=o,a=l,!t)return{from:i,to:a};for(let d=n-1;d>=0;d--)s.end(d)+t>=i&&(i=s.start(d));for(let d=n+1;d<s.length;d++)s.start(d)-t<=a&&(a=s.end(d))}}return{from:i,to:a}};const hf=1e3,ff=s=>s.webkitAudioDecodedByteCount!==void 0?!!s.webkitAudioDecodedByteCount:s.mozHasAudio!==void 0?s.mozHasAudio:s.audioTracks?!!s.audioTracks.length:!0,qe=s=>{const e=y=>r.fromEvent(s,y).pipe(r.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],i=r.merge(...t.map(y=>r.fromEvent(s,y))).pipe(r.map(y=>y.type==="ended"?s.readyState<2:s.readyState<3),r.filterChanged()),a=r.merge(r.fromEvent(s,"progress"),r.fromEvent(s,"timeupdate")).pipe(r.map(()=>Vn(s.buffered,s.currentTime))),n=Mn()?r.combine({play:e("play").pipe(r.once()),playing:e("playing")}).pipe(r.mapTo(void 0)):e("playing"),o=r.fromEvent(s,"playing").pipe(r.debounce(hf),r.map(()=>ff(s))),l=r.fromEvent(s,"volumechange").pipe(r.map(()=>({muted:s.muted,volume:s.volume}))),d=r.fromEvent(s,"ratechange").pipe(r.map(()=>s.playbackRate)),u=r.fromEvent(s,"error").pipe(r.filter(()=>Boolean(s.error||s.played.length)),r.map(()=>{var y;const T=s.error;return{id:T?`MediaError#${T.code}`:"HtmlVideoError",category:r.ErrorCategory.VIDEO_PIPELINE,message:T?T.message:"Error event from HTML video element",thrown:(y=s.error)!==null&&y!==void 0?y:void 0}})),c=r.fromEvent(s,"timeupdate").pipe(r.map(()=>s.currentTime)),h=new r.Subject,f=.3;let p;c.subscribe(y=>{s.loop&&r.isNonNullable(p)&&r.isNonNullable(y)&&p>=s.duration-f&&y<=f&&h.next(p),p=y});const b=r.fromEvent(s,"enterpictureinpicture"),g=r.fromEvent(s,"leavepictureinpicture"),S=new r.ValueSubject(df(s));b.subscribe(()=>S.next(!0)),g.subscribe(()=>S.next(!1));const m=new r.ValueSubject(vr(s));return r.fromEvent(s,"fullscreenchange").pipe(r.map(()=>vr(s))).subscribe(m),{playing$:n,pause$:e("pause").pipe(r.filter(()=>!s.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:h,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:r.fromEvent(s,"durationchange").pipe(r.map(()=>s.duration)),isBuffering$:i,currentBuffer$:a,volumeState$:l,isAudioAvailable$:o,playbackRateState$:d,inPiP$:S,inFullscreen$:m}},la=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var pf=Oi,mf=Li,bf=sa,vf=ia;pf({target:"Array",proto:!0},{at:function(e){var t=mf(this),i=bf(t),a=vf(e),n=a>=0?a:i+a;return n<0||n>=i?void 0:t[n]}});var Sf=Ws,Fn=Sf,gf=Fn,yf=gf("Array","at"),Tf=yf,Ef=Tf,$f=Ef,kf=$f,Ne=kf;let ua=!1,Ce={};const Pf=s=>{ua=s},Af=()=>{Ce={}},wf=s=>{s(Ce)},ni=(s,e)=>{var t;ua&&(Ce.meta=(t=Ce.meta)!==null&&t!==void 0?t:{},Ce.meta[s]=e)};class Ae{constructor(e){this.name=e}next(e){var t,i;if(!ua)return;Ce.series=(t=Ce.series)!==null&&t!==void 0?t:{};const a=(i=Ce.series[this.name])!==null&&i!==void 0?i:[];a.push([Date.now(),e]),Ce.series[this.name]=a}}const _f=new Ae("best_bitrate"),Rf=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class If{constructor(){this.history={}}recordSelection(e){this.history[e.id]=r.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Gt=(s,{container:e,throughput:t,tuning:i,limits:a,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:d,history:u})=>{var c,h,f,p;const b=i.usePixelRatio&&(c=window.devicePixelRatio)!==null&&c!==void 0?c:1,g=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*b*i.containerSizeFactor,height:e.height*b*i.containerSizeFactor},S=g&&nt(g),m=i.considerPlaybackRate&&r.isNonNullable(l)?l:1,v=s.filter(I=>!ki(I.quality)).sort((I,_)=>Si(I.quality,_.quality)?-1:1),y=(h=Ne(v,-1))===null||h===void 0?void 0:h.quality,T=(f=Ne(v,0))===null||f===void 0?void 0:f.quality,E=r.isNullable(a)||r.isNonNullable(a.min)&&r.isNonNullable(a.max)&&Mt(a.max,a.min)||r.isNonNullable(a.min)&&T&&Si(a.min,T)||r.isNonNullable(a.max)&&y&&Mt(a.max,y),A=m*Rf(o!=null?o:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),R=v.filter(I=>{const _=S?Mt(I.quality,S):!0,j=r.isNonNullable(t)&&isFinite(t)&&r.isNonNullable(I.bitrate)?t-n>=I.bitrate*A:!0,W=i.lazyQualitySwitch&&r.isNonNullable(i.minBufferToSwitchUp)&&d&&!ki(d.quality)&&(o!=null?o:0)<i.minBufferToSwitchUp&&Si(I.quality,d.quality),X=E||(r.isNullable(a.max)||Hh(I.quality,a.max))&&(r.isNullable(a.min)||jh(I.quality,a.min));return _&&j&&!W&&X})[0];R&&R.bitrate&&_f.next(R.bitrate);const N=(p=R!=null?R:v[Math.ceil((v.length-1)/2)])!==null&&p!==void 0?p:s[0],M=N&&u&&u.history[N.id]&&r.now()-u.history[N.id]<=i.trackCooldown&&(!u.last||N.id!==u.last.id);if(N!=null&&N.id&&u&&!M&&u.recordSelection(N),M&&(u!=null&&u.last)){const I=u.last;return u==null||u.recordSwitch(I),I}return u==null||u.recordSwitch(N),N};var oe=s=>new URL(s).hostname;const Nf=300,Ai=(s,e=Nf)=>new r.Observable(t=>{const{width:i,height:a}=s.getBoundingClientRect();if(t.next({width:i,height:a}),!window.ResizeObserver)return;const n=new ResizeObserver(Po(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),r.isNonNullable(d)&&r.isNonNullable(u)&&t.next({width:d,height:u})},e));return n.observe(s),()=>n.disconnect()}),Df=5e3,xt={};var B;(function(s){s.DOWNLOADING_LIB="downloading_lib",s.STOPPED="stopped",s.STREAM_INITIALIZED="stream_initialized",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(B||(B={}));const te=(s,e)=>new r.Observable(t=>{const i=a=>t.next(a);return s.on(e,i),()=>s.off(e,i)});class Sr{constructor(e){this.subscription=new r.Subscription,this.videoState=new Q(B.DOWNLOADING_LIB),this.textTracksManager=new Re,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new r.ValueSubject(void 0),this.maxSeekBackTime$=new r.ValueSubject(1/0),this.availableFrom$=new r.ValueSubject(void 0),this.elementSize$=new r.ValueSubject(void 0),this.liveOffset=new oa,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState(),o=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===B.DOWNLOADING_LIB||t===B.STREAM_INITIALIZED))switch((a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&n.state===O.Requested&&t!==B.STOPPED&&i!==exports.PlaybackState.STOPPED&&(o?this.seek(n.position-this.liveOffset.getTotalPausedTime()):this.seek(n.position)),i){case exports.PlaybackState.STOPPED:{switch(t){case B.STOPPED:break;case B.PLAYING:case B.PAUSED:case B.READY:this.stop();break;default:r.assertNever(t)}break}case exports.PlaybackState.READY:{switch(t){case B.STOPPED:this.prepare();break;case B.PLAYING:case B.PAUSED:case B.READY:break;default:r.assertNever(t)}break}case exports.PlaybackState.PLAYING:{switch(t){case B.PLAYING:break;case B.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 B.READY:this.play();break;case B.STOPPED:this.prepare();break;default:r.assertNever(t)}break}case exports.PlaybackState.PAUSED:{switch(t){case B.PLAYING:this.pause(),this.liveOffset.pause();break;case B.PAUSED:break;case B.READY:this.videoState.setState(B.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case B.STOPPED:this.prepare();break;default:r.assertNever(t)}break}default:r.assertNever(i)}},this.video=je(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=a=>{var n;e||this.params.output.error$.next({id:a==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:r.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${(n=a==null?void 0:a.toString)===null||n===void 0?void 0:n.call(a)}`,thrown:a}),e=!0},i=window.setTimeout(()=>t("timeout"),Df);import("dashjs/dist/dash.mediaplayer.min.js").then(a=>{e||(xt.MediaPlayer=a.MediaPlayer,xt.Debug=a.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){r.assertNonNullable(xt.MediaPlayer,"dashjs not loaded"),r.assertNonNullable(xt.Debug,"dashjs not loaded"),this.player=xt.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?la(t.frameRate+""):void 0),!0)),(this.params.format===exports.VideoFormat.DASH_WEBM||this.params.format===exports.VideoFormat.DASH_WEBM_AV1)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=ef(this.player,{minInitSize:this.params.tuning.bigRequestMinInitSize,minDataSize:this.params.tuning.bigRequestMinDataSize,onError:t=>this.params.output.error$.next(t),onDownloadStream:t=>this.params.dependencies.throughputEstimator.trackStream(t)}):this.params.tuning.stripRangeHeader&&rf(this.player),tf(this.player),this.params.tuning.requestQuick&&af(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(B.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=m=>{e.error$.next({id:"DashIFProvider",category:r.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:m})},a=(m,v)=>this.subscription.add(m.subscribe(v,i));a(Ai(this.video),this.elementSize$),a(te(this.player,"error").pipe(r.map(m=>{const v=typeof m.error=="object"?m.error.code:m.error,y=typeof m.error=="object"?m.error.message:void 0;return{id:`DashJS#${v}`,message:y}})),e.error$),a(te(this.player,"playbackError").pipe(r.map(m=>({id:"DashJSPlayback",message:m.error}))),e.error$);const n=te(this.player,"qualityChangeRendered").pipe(r.filter(({mediaType:m})=>m==="video"),r.map(({newQuality:m})=>{var v;return(v=this.videoTracks.find(({bitrateInfo:y})=>y.qualityIndex===m))===null||v===void 0?void 0:v.track}));n.pipe(r.filter(r.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(r.filter(({to:m})=>m===B.STREAM_INITIALIZED),r.once()).subscribe(()=>{this.subscription.add(ge(t.videoTrack,()=>{var m,v;const y=this.player.getQualityFor("video");return(v=(m=this.videoTracks.find(({bitrateInfo:T})=>T.qualityIndex===y))===null||m===void 0?void 0:m.track)===null||v===void 0?void 0:v.id},m=>{var v;if(r.isNullable(m))return;const y=(v=this.videoTracks.find(({track:T})=>T.id===m))===null||v===void 0?void 0:v.bitrateInfo;y&&this.player.setQualityFor("video",y.qualityIndex)},{changed$:n.pipe(r.map(m=>m==null?void 0:m.id)),onError:i}))},i)),this.subscription.add(ge(t.autoVideoTrackSwitching,()=>{var m,v,y;return(y=(v=(m=this.player.getSettings().streaming)===null||m===void 0?void 0:m.abr)===null||v===void 0?void 0:v.autoSwitchBitrate)===null||y===void 0?void 0:y.video},m=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:m}}}}),{onError:i})),a(te(this.player,"bufferStateChanged").pipe(r.filter(({mediaType:m})=>m==="video"),r.map(({state:m})=>m==="bufferStalled")),e.isBuffering$),a(te(this.player,"fragmentLoadingStarted"),({mediaType:m,request:{url:v}})=>{var y,T;const E=this.player.getDashMetrics(),A=E.getLatestFragmentRequestHeaderValueByID(m,"X-Reused"),L=(y=E.getLatestFragmentRequestHeaderValueByID(m,"X-Delivery-Type"))!==null&&y!==void 0?y:exports.HttpConnectionType.HTTP1,R=(T={1:!0,0:!1}[A])!==null&&T!==void 0?T:void 0;this.params.output.httpConnectionType$.next(L),this.params.output.httpConnectionReused$.next(R),e.hostname$.next(oe(v))}),a(te(this.player,"streamInitialized"),({streamInfo:{duration:m,manifestInfo:{isDynamic:v,availableFrom:y}}})=>{this.isLive$.next(v),this.availableFrom$.next(y.getTime()),v||e.duration$.next(m),this.videoTracks=[];const T=this.player.getQualityFor("video");let E;for(const A of this.player.getBitrateInfoListFor("video")){const L=A.qualityIndex.toString(10),R=nt(A),N=A.bitrate/1e3,M={width:A.width,height:A.height},I=this.frameRatesByFrameHeight[A.height];if(R){const _={id:L,quality:R,bitrate:N,size:M,fps:I};this.videoTracks.push({track:_,bitrateInfo:A}),A.qualityIndex===T&&(E=_)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:A})=>A)),E&&e.currentVideoTrack$.next(E),this.videoState.setState(B.STREAM_INITIALIZED),this.videoState.startTransitionTo(B.READY)}),a(te(this.player,"fragmentLoadingCompleted"),({request:m})=>{if(!m.requestEndDate||!m.firstByteDate||!m.bytesLoaded)return;const v=m.requestEndDate.getTime()-m.firstByteDate.getTime(),y=m.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(y,v)}),a(r.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(),v=Gt(this.videoTracks.map(({track:T})=>T),{container:this.elementSize$.getValue(),throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),y=this.videoTracks.find(({track:T})=>T===v);y!=null&&y.bitrateInfo&&this.player.setQualityFor("video",y==null?void 0:y.bitrateInfo.qualityIndex,!1)}),a(r.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(r.filter(r.isNonNullable))}).pipe(r.filter(({isLive:m})=>m),r.map(({maxSeekBackTime:m})=>-m/1e3)),this.params.output.duration$);const o=te(this.player,"playbackTimeUpdated").pipe(r.map(({time:m})=>m!=null?m:0));a(r.combine({availableFrom:this.availableFrom$.pipe(r.filter(r.isNonNullable)),currentTime:o}),({availableFrom:m,currentTime:v})=>this.params.output.liveTime$.next(m+v*1e3)),a(o.pipe(r.filter(()=>this.isLive$.getValue()===!1)),e.position$),a(te(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),a(te(this.player,"playbackEnded"),e.endedEvent$),a(te(this.player,"playbackProgress").pipe(r.map(()=>Vn(this.video.buffered,this.video.currentTime))),e.currentBuffer$),a(te(this.player,"playbackPlaying"),()=>{this.videoState.setState(B.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)}),a(te(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(B.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),a(te(this.player,"playbackPaused"),()=>{this.videoState.setState(B.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)}),a(te(this.player,"canPlay"),()=>{var m;((m=this.videoState.getTransition())===null||m===void 0?void 0:m.to)===B.READY&&this.videoState.setState(B.READY)}),a(this.isLive$,e.isLive$),a(Ai(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const l=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));a(l,this.syncPlayback);const{playbackDuration$:d,ping$:u,connectionType$:c,connectionReused$:h}=sf(this.player);a(c,this.params.output.httpConnectionType$),a(h,this.params.output.httpConnectionReused$),a(d,this.maxSeekBackTime$),a(u.pipe(r.once()),e.firstBytesEvent$),a(te(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&a(r.combine({isLive:this.isLive$,isShort:e.duration$.pipe(r.map(m=>m<60))}),({isLive:m,isShort:v})=>{const y=!m&&v;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:y}}})}),a(o.pipe(r.filter(m=>m>this.params.tuning.insufficientBufferRuleMargin),r.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(te(this.player,"manifestLoaded").pipe(r.once()).subscribe(()=>{this.subscription.add(te(this.player,"playbackPlaying").pipe(r.once(),r.mapTo(void 0)).subscribe(e.firstFrameEvent$,i))},i)),a(te(this.player,"manifestLoaded"),m=>{var v,y,T,E,A,L,R;if(!((y=(v=m.data)===null||v===void 0?void 0:v.Period)===null||y===void 0)&&y.AdaptationSet){const N=[];for(const M of(E=(T=m.data)===null||T===void 0?void 0:T.Period)===null||E===void 0?void 0:E.AdaptationSet)if(M.contentType==="text"){const I=(A=M.Representation)===null||A===void 0?void 0:A.id,_=new URL((L=M.Representation)===null||L===void 0?void 0:L.BaseURL,(R=m.data)===null||R===void 0?void 0:R.baseUri).toString(),j="internal",W=M.lang,X=Boolean(I.includes("auto"));N.push({id:I,url:_,type:j,language:W,isAuto:X})}t.internalTextTracks.startTransitionTo(N)}}),this.subscription.add(ot(this.video,t.isLooped,i));const{volumeState$:f,looped$:p,playbackRateState$:b,inPiP$:g,inFullscreen$:S}=qe(this.video);this.subscription.add(Ue(this.video,t.volume,f,i)),this.subscription.add(f.subscribe(e.volume$,i)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(Qe(this.video,t.playbackRate,b,i)),this.subscription.add(g.subscribe(e.inPiP$)),this.subscription.add(S.subscribe(e.inFullscreen$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(B.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(B.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const a=gt(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,St.PLAYBACK_SHIFT);this.player.attachSource(a)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(B.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(B.PAUSED),this.video.pause()}destroy(){var e,t;this.subscription.unsubscribe(),this.textTracksManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(i){}He(this.video),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var zt=s=>{switch(s){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}};const gr=s=>{if(s instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(s.message))throw s;return!(s instanceof DOMException&&(s.code===20||s.name==="AbortError"))};var Je=async s=>{const e=s.muted;try{await s.play()}catch(t){if(!gr(t))return!1;if(e)return console.warn(t),!1;s.muted=!0;try{await s.play()}catch(i){return gr(i)&&(s.muted=!1,console.warn(i)),!1}}return!0};function ne(){return r.now()}function Un(s){return ne()-s}function yr(s){const e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,a=o=>i.test(o);return{resolve:(o,l,d=!1)=>{a(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 Cf(s,e,t){const i=(...a)=>{t.apply(null,a),s.removeEventListener(e,i)};s.addEventListener(e,i)}function gi(s,e,t,i){const a=window.XMLHttpRequest;let n,o,l,d=!1,u=0,c,h,f=!1,p="arraybuffer",b=7e3,g=2e3,S=()=>{if(d)return;r.assertNonNullable(c);const _=Un(c);let j;if(_<g){j=g-_,setTimeout(S,j);return}g*=2,g>b&&(g=b),o&&o.abort(),o=new a,A()};const m=_=>(n=_,I),v=_=>(h=_,I),y=()=>(p="json",I),T=()=>{if(!d){if(--u>=0){S(),i&&i();return}d=!0,h&&h(),t&&t()}},E=_=>(f=_,I),A=()=>{c=ne(),o=new a,o.open("get",s);let _=0,j,W=0;const X=()=>(r.assertNonNullable(c),Math.max(c,Math.max(j||0,W||0)));if(n&&o.addEventListener("progress",k=>{const D=ne();n.updateChunk&&k.loaded>_&&(n.updateChunk(X(),k.loaded-_),_=k.loaded,j=D)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>T())),o.addEventListener("load",()=>{if(d)return;r.assertNonNullable(o);const k=o.status;if(k>=200&&k<300){if(o.response.byteLength&&n){const D=o.response.byteLength-_;D&&n.updateChunk&&n.updateChunk(X(),D)}h&&h(),o&&e(o.response)}else T()}),o.addEventListener("error",()=>{T()}),f){const k=()=>{r.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(W=ne(),o.removeEventListener("readystatechange",k))};o.addEventListener("readystatechange",k)}return o.responseType=p,o.send(),I},I={withBitrateReporting:m,withParallel:E,withJSONResponse:y,withRetryCount:_=>(u=_,I),withRetryInterval:(_,j)=>(r.isNonNullable(_)&&(g=_),r.isNonNullable(j)&&(b=j),I),withTimeout:_=>(l=_,I),withFinally:v,send:A,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return I}const Lf=100,xf=2e3,Of=500;let Bf=class{constructor(e){this.intervals=[],this.currentRate=0,this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-Of;if(t-e>xf){let i=0,a=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)i+=n.end-n.start,a+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,l=n.end-n.start;i+=o;const d=n.bytes*o/l;a+=d,n.start=t,n.bytes-=d}}}if(a>0&&i>0){const n=a*8/(i/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(a)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>Lf&&(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 Mf{constructor(e,t,i,a,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=i,this.MAX_PARALLEL_REQUESTS=a,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 i=ne(),a=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=ne()-i,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=gi(t,n,()=>a("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=ne()}_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=ne();if(Object.keys(this.activeRequests).length>=e)return!1;const i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,a){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=i,o._retryCB=a,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}`),i(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=i,n._retryCB=a,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 oi=1e4,li=3,Vf=300,Ff=2e3,Uf=6e4,jf=10,Hf=1,qf=500;class Yf{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 Bf(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=yr(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=yr(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;Boolean(e.error)&&!this.destroyed&&(t(`Video element error: ${(i=e.error)===null||i===void 0?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,i=t.buffered.length;let a;i!==0&&(a=t.buffered.start(i-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){const{videoElement:t}=this.params;let i,a,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)?(!a||n.bitrate>a.bitrate)&&(a=n):(!i||i.bitrate>n.bitrate)&&(i=n));return a||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||r.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:i,videoElement:a,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{Cf(a,"progress",()=>{a.buffered.length?(a.currentTime=a.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 Mf(li,oi,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,playerCallback:a}=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,A)=>{d&&d.abort(),d=gi(this.urlResolver.resolve(T,!1),E,A,()=>this._retryCallback()).withTimeout(oi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(li).withFinally(()=>{d=null}).send()},p=(T,E,A)=>{r.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),E,A,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},b=T=>{const E=i.playbackRate;i.playbackRate!==T&&(t(`Playback rate switch: ${E}=>${T}`),i.playbackRate=T)},g=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)b(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){b(1);return}const A=ne()-1e4;let L=0;for(let N=0;N<this.bufferStates.length;N++){const M=this.bufferStates[N];T=Math.min(T,M.buf),M.ts<A&&L++}this.bufferStates.splice(0,L),t(`update playback rate; minBuffer=${T} drop=${L} jitter=${this.sourceJitter}`);let R=T-Hf;this.sourceJitter>=0?R-=this.sourceJitter/2:this.sourceJitter-=1,R>3?b(1.15):R>1?b(1.1):R>.3?b(1.05):b(1)}},m=T=>{let E;const A=()=>E&&E.start?E.start.length:0,L=k=>E.start[k]/1e3,R=k=>E.dur[k]/1e3,N=k=>E.fragIndex+k,M=(k,D)=>({chunkIdx:N(k),startTS:L(k),dur:R(k),discontinuity:D}),I=()=>{let k=0;if(E&&E.dur){let D=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,G=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Z=D;this.sourceJitter>1&&(Z+=this.sourceJitter-1);let ie=E.dur.length-1;for(;ie>=0&&(Z-=E.dur[ie],!(Z<=0));--ie);k=Math.min(ie,E.dur.length-1-G),k=Math.max(k,0)}return M(k,!0)},_=k=>{const D=A();if(!(D<=0)){if(r.isNonNullable(k)){for(let G=0;G<D;G++)if(L(G)>k)return M(G)}return I()}},j=k=>{const D=A(),G=k?k.chunkIdx+1:0,Z=G-E.fragIndex;if(!(D<=0)){if(!k||Z<0||Z-D>jf)return t(`Resync: offset=${Z} bChunks=${D} chunk=`+JSON.stringify(k)),I();if(!(Z>=D))return M(G-E.fragIndex,!1)}},W=(k,D,G)=>{u&&u.abort(),u=gi(this.urlResolver.resolve(k,!0,this.lowLatency),D,G,()=>this._retryCallback()).withTimeout(oi).withRetryCount(li).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(k,D)=>{W(T,G=>{if(!h())return;E=G;const Z=Boolean(E.lowLatency);Z!==this.lowLatency&&g(Z);let ie=0;for(let le=0;le<E.dur.length;++le)ie+=E.dur[le];ie>0&&(r.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ie/E.dur.length)),a({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,k(_(D))},()=>this._handleNetworkError())},nextChunk:j}},v=()=>{n=!1,l&&l.abort(),d&&d.abort(),u&&u.abort(),r.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:T=>{const{videoElement:E,logger:A}=this.params;let L=m(e.jidxUrl),R,N,M,I,_=0,j,W,X;const k=()=>{j&&(clearTimeout(j),j=void 0);const F=Math.max(qf,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),se=_+F,ue=ne(),me=Math.min(1e4,se-ue);_=ue;const Ie=()=>{u||h()&&L.seek(()=>{h()&&(_=ne(),D(),k())})};me>0?j=window.setTimeout(()=>{this.paused?k():Ie()},me):Ie()},D=()=>{let F;for(;F=L.nextChunk(I);)I=F,Ee(F);const se=L.nextChunk(M);if(se){if(M&&se.discontinuity){A("Detected discontinuity; restarting playback"),this.paused?k():(v(),this._initPlayerWith(e));return}le(se)}else k()},G=(F,se)=>{if(!h()||!this.sourceBuffer)return;let ue,me,Ie;const Ke=Ye=>{window.setTimeout(()=>{h()&&G(F,se)},Ye)};if(this.sourceBuffer.updating)A("Source buffer is updating; delaying appendBuffer"),Ke(100);else{const Ye=ne(),lt=E.currentTime;!this.paused&&E.buffered.length>1&&W===lt&&Ye-X>500&&(A("Stall suspected; trying to fix"),this._fixupStall()),W!==lt&&(W=lt,X=Ye);const $e=this._getBufferSizeSec();if($e>30)A(`Buffered ${$e} seconds; delaying appendBuffer`),Ke(2e3);else try{this.sourceBuffer.appendBuffer(F),this.videoPlayStarted?(this.bufferStates.push({ts:Ye,buf:$e}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),se&&se()}catch(Pt){if(Pt.name==="QuotaExceededError")A("QuotaExceededError; delaying appendBuffer"),Ie=this.sourceBuffer.buffered.length,Ie!==0&&(ue=this.sourceBuffer.buffered.start(0),me=lt,me-ue>4&&this.sourceBuffer.remove(ue,me-3)),Ke(1e3);else throw Pt}}},Z=()=>{N&&R&&(A([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(M)]),G(N,function(){N=null,D()}))},ie=F=>e.fragUrlTemplate.replace("%%id%%",F.chunkIdx),le=F=>{h()&&p(ie(F),(se,ue)=>{if(h()){if(ue/=1e3,N=se,M=F,o=F.startTS,ue){const me=Math.min(10,F.dur/ue);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*me:me}Z()}},()=>this._handleNetworkError())},Ee=F=>{h()&&(r.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ie(F),!1)))},pe=F=>{h()&&(e.cachedHeader=F,G(F,()=>{R=!0,Z()}))};n=!0,L.seek(F=>{if(h()){if(_=ne(),!F){k();return}I=F,!r.isNullable(T)||F.startTS>T?le(F):(M=F,D())}},T),e.cachedHeader?pe(e.cachedHeader):f(e.headerUrl,pe,()=>this._handleNetworkError())},stop:v,getTimestampSec:()=>o},c}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),r.isNonNullable(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,r.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return r.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=h=>{if(!this.autoQuality)return;let f,p,b;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(p=this._getBufferSizeSec(),b=h/this.bitrate,p>10&&b>.8||p>15&&b>.5||p>20&&b>.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 b=ne();if(this.chunkRateEstimator.addInterval(f,b,p)){const S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:b-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&&Un(o)<3e4)return;i(h)}d=this.autoQuality};return{updateChunk:(h,f)=>{const p=n.updateChunk(h,f);return p&&u(),p},notifySwitch:h=>{const f=ne();h<l&&(o=f),l=h}}}_fetchManifest(e,t,i){this.manifestRequest=gi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(oi).withRetryCount(li).withRetryInterval(Vf,Ff).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;Je(t).then(i=>{i||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:a}=this.params,n=o=>{const l=[];return o!=null&&o.length?(o.forEach((d,u)=>{d.video&&a.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}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Uf))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var x;(function(s){s.STOPPED="stopped",s.MANIFEST_READY="manifest_ready",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(x||(x={}));const Gf=[x.PAUSED,x.PLAYING,x.READY],zf=[x.PAUSED,x.PLAYING,x.READY];class Wf{constructor(e){this.subscription=new r.Subscription,this.videoState=new Q(x.STOPPED),this.representations$=new r.ValueSubject([]),this.textTracksManager=new Re,this.maxSeekBackTime$=new r.ValueSubject(1/0),this.zeroTime$=new r.ValueSubject(void 0),this.liveOffset=new oa,this._dashCb=a=>{var n,o,l,d;switch(a.name){case"buffering":{const u=a.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${a.type}`,category:r.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=a.manifest,c=[];for(const h of u){const f=(n=h.name)!==null&&n!==void 0?n:h.index.toString(10),p=(o=zt(h.name))!==null&&o!==void 0?o:nt(h.video),b=h.bitrate/1e3,g={...h.video};if(!p)continue;const S={id:f,quality:p,bitrate:b,size:g};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)===x.MANIFEST_READY&&this.videoState.setState(x.MANIFEST_READY);break}case"qualitySwitch":{const u=a.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),r.isNonNullable(c)&&this.params.output.currentVideoTrack$.next(c);break}case"bandwidth":{const{size:u,duration:c}=a;this.params.dependencies.throughputEstimator.addRawSpeed(u,c);break}case"index":{this.maxSeekBackTime$.next(a.shiftDuration),this.zeroTime$.next(a.zeroTime);break}}},this.syncPlayback=()=>{var a;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!==x.STOPPED&&(this.videoState.startTransitionTo(x.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(x.STOPPED));return}if(!o){if(zf.includes(n)){const c=(a=this.params.desiredState.videoTrack.getTransition())===null||a===void 0?void 0:a.to;r.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===O.Requested&&Gf.includes(n)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(n){case x.STOPPED:this.videoState.startTransitionTo(x.MANIFEST_READY),this.dash.attachSource(gt(this.params.source.url));return;case x.MANIFEST_READY:this.videoState.startTransitionTo(x.READY),this.prepare();break;case x.READY:if(l===exports.PlaybackState.PAUSED)this.videoState.setState(x.PAUSED);else if(l===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(x.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(x.PAUSED)})}return;case x.PLAYING:l===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(x.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case x.PAUSED:l===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(x.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(x.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return r.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=a=>{e.output.error$.next({id:"DashLiveProvider",category:r.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:a})};r.merge(this.videoState.stateChangeStarted$.pipe(r.map(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(a)}`})}),this.video=je(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(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=qe(this.video);this.subscription.add(i.canplay$.subscribe(()=>{var a;((a=this.videoState.getTransition())===null||a===void 0?void 0:a.to)===x.READY&&this.videoState.setState(x.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(x.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===O.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(x.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(r.filterChanged(),r.map(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(r.combine({zeroTime:this.zeroTime$.pipe(r.filter(r.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:a,position:n})=>this.params.output.liveTime$.next(a+n*1e3),t)).add(ot(this.video,this.params.desiredState.isLooped,t)).add(Ue(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Qe(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:a}})=>{const n=a&&Gh(a);this.dash.setMaxAutoQuality(n)})).add(this.videoState.stateChangeEnded$.subscribe(a=>{var n;switch(a.to){case x.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case x.MANIFEST_READY:case x.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 x.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case x.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return r.assertNever(a.to)}},t)).add(r.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),He(this.video)}createLiveDashPlayer(){const e=new Yf({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,i,a,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=(a=(i=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||i===void 0?void 0:i.to)!==null&&a!==void 0?a:this.params.desiredState.autoVideoTrackSwitching.getState(),c=!u&&r.isNonNullable(d)?d:(n=Gt(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;r.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 i=(t=this.representations$.getValue().find(({track:a})=>a.id===e))===null||t===void 0?void 0:t.representation;r.assertNonNullable(i,`No such representation ${e}`),this.dash.switchByName(i.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),a=t===exports.PlaybackState.PAUSED&&i===x.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(gt(this.params.source.url,o)),a&&this.dash.pause(),this.liveOffset.resetTo(o,a)}}var jn=s=>{var e,t;const i=s.get("X-Delivery-Type"),a=s.get("X-Reused"),n=i===null?exports.HttpConnectionType.HTTP1:(e=i)!==null&&e!==void 0?e:void 0,o=a===null?void 0:(t={1:!0,0:!1}[a])!==null&&t!==void 0?t:void 0;return{type:n,reused:o}},it=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){const a=s.start(i)*1e3,n=s.end(i)*1e3;a<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const Qf=s=>{const e=document.createElement("a");return e.href=s,e.origin},Jf=s=>{const e=document.createElement("a");return e.href=s,e.host};class Hn{constructor(e,t=[],i,a,n,o){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=i,this._progressCb=a,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,i,a,n,o,l,d,u;if(r.assertNonNullable(this._xhr),((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(i=this._errorCb)===null||i===void 0||i.call(this,`Http${(a=this._xhr)===null||a===void 0?void 0:a.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=Yt(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 i;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(i=this._errorCb)===null||i===void 0||i.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let a;this._failoverIndex>=this._failoverHosts.length?(a=this._url,this._failoverIndex=0):(a=this._url.replace(Jf(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",a,!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 wi{constructor(e){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t==null||t()}catch(i){if(i.name==="QuotaExceededError"){this._isFull=!0;const a=this._sourceBuffer.buffered;let n=0;for(let o=0,l=a.length;o<l;o++)n+=a.end(o)-a.start(o);n&&(this._maxBufferDuration=Math.round(n))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",i),i}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,i,a,n,o,l){this.abort(()=>{let d=0;const u=Date.now();let c=0,h=0,f=0;const p=g=>{a(wi._str2ua(g.substr(d))),d=g.length};let b=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(b=Tt(b)),this._lastXhr=new Hn(b,e.failoverHosts,g=>{this._lastXhr=void 0,p(g);const S=Date.now()-u;this._params.onBandwidthChange({size:g.length,duration:S,speed:8*g.length/(S/1e3)}),this._onDashCallback("loading",{size:g.length,done:!0}),n==null||n()},g=>{if(g.length-d>l&&p(g),h===0){h=Date.now();return}f=g.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=g.length,h=Date.now()),this._onDashCallback("loading",{size:g.length,done:!1})},o,(g,S,m)=>this._params.onError(g,S,m))})}abort(e){var t;(t=this._lastXhr)===null||t===void 0||t.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e==null||e()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(i){throw this._params.onError("SourceBuffer","Source Buffer update error",i),i}};return this._sourceBuffer.addEventListener("updateend",t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener("updateend",e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=wi._concatUint8(this._appendPromiseUint8Array,e):(this._appendPromiseUint8Array=e,this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,()=>{this._appendPromiseUint8Array=void 0,t&&this._sbUpdatingWatch(t)})}))}endOfStream(){this._mediaSource.readyState==="open"&&this._sbUpdatingWatch(()=>this._mediaSource.endOfStream())}static _concatUint8(e,t){const i=new Uint8Array(e.byteLength+t.byteLength);return i.set(e,0),i.set(t,e.byteLength),i}static _str2ua(e){const t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}remove(e,t){this._sbUpdatingWatch(()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(e,t),this._maxBufferDuration=Number.POSITIVE_INFINITY})}destroy(){var e;(e=this._lastXhr)===null||e===void 0||e.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._mediaSource.readyState==="open"&&this._sourceBuffer.abort()}}class Kf{constructor(e){var t;this._representations=[],this._appendVector={},this._cachingPaused=!1,this._duration=0,this.STREAM_END_THRESHOLD=1,this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=(t=e.onDashCallback)!==null&&t!==void 0?t:()=>{},this._config=e.config}_parseDurationFromISO8601(e){const t=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/,i=(l,d)=>{const u=l?parseFloat(l.replace(",",".")):NaN;return(isNaN(u)?0:u)*d},a=t.exec(e),n=(a==null?void 0:a[1])==="-"?-1:1,o={years:i(a==null?void 0:a[2],n),months:i(a==null?void 0:a[3],n),weeks:i(a==null?void 0:a[4],n),days:i(a==null?void 0:a[5],n),hours:i(a==null?void 0:a[6],n),minutes:i(a==null?void 0:a[7],n),seconds:i(a==null?void 0:a[8],n)};return o.hours*3600+o.minutes*60+o.seconds}getRepresentations(){return this._representations}attachSource(e,t){let i=e;this._config.REQUEST_QUIC&&(i=Tt(i)),new Hn(i,t,a=>{this.attachManifest(a,t,Qf(i))},void 0,a=>{this._params.onResponseHeaders(a)},(a,n,o)=>this._params.onError(a,n,o))}attachManifest(e,t,i){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,b,g,S,m,v,y,T,E,A,L,R,N,M,I,_;const j=u.getElementsByTagName("SegmentBase")[0],W=j&&o(j,"indexRange").split("-"),X=j&&j.getElementsByTagName("Initialization")[0],k=X&&o(X,"range").split("-");if(!k||!W){const Ee=u.parentElement;if((Ee==null?void 0:Ee.getAttribute("contentType"))==="text"){const pe=(c=u.getAttribute("id"))!==null&&c!==void 0?c:void 0,F=(i?i+"/":"")+((b=(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||b===void 0?void 0:b.data),se=(g=Ee.getAttribute("lang"))!==null&&g!==void 0?g:void 0,ue=pe==null?void 0:pe.includes("auto");F&&d.push({id:pe,url:F,language:se,isAuto:ue})}return}const D=.1,G=Number((S=u.attributes.getNamedItem("bandwidth"))===null||S===void 0?void 0:S.value),Z=(i?i+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ie;const le=(v=(m=u.attributes.getNamedItem("frameRate"))===null||m===void 0?void 0:m.value)!==null&&v!==void 0?v:void 0;ie=le?la(le):void 0,l.push({width:Number((y=u.attributes.getNamedItem("width"))===null||y===void 0?void 0:y.value),height:Number((T=u.attributes.getNamedItem("height"))===null||T===void 0?void 0:T.value),bandwidth:G,baseURL:Z,failoverHosts:t,indexFrom:Number(W[0]),indexTo:Number(W[1]),initFrom:Number(k[0]),initTo:Number(k[1]),codecs:(A=(E=u.attributes.getNamedItem("codecs"))===null||E===void 0?void 0:E.value)!==null&&A!==void 0?A:void 0,mimeType:(R=(L=u.attributes.getNamedItem("mimeType"))===null||L===void 0?void 0:L.value)!==null&&R!==void 0?R:void 0,fps:ie,bufferSize:D*G/8,bufferLength:D,name:(M=(N=u.attributes.getNamedItem("okQuality"))===null||N===void 0?void 0:N.value)!==null&&M!==void 0?M:void 0,id:(_=(I=u.attributes.getNamedItem("id"))===null||I===void 0?void 0:I.value)!==null&&_!==void 0?_: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");h&&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({representations:this._representations,textRepresentations:d})}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const i=Date.now();this._stream.load(e,e.initFrom,e.indexTo,a=>{let n=e.initTo-e.initFrom+1;if(!a.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(a.buffer,0,n);const o=new DataView(a.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),b=d+o.getUint32(n+4,!1);n+=12,e.refs.push({fromTime:d/l,toTime:b/l,fromOffset:u,toOffset:p-1}),u=p,d=b}const h=e.refs[e.refs.length-1];h.toTime-h.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,a=>{this._params.onResponseHeaders(a),this._params.onIdxRequestPing(Date.now()-i)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const i=new t;let a,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!==a&&(a=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 b=this._buffer.getNextWithGap(p);b&&(this._video.currentTime=b.from)}catch(b){throw this._params.onError("GapSyncError",`Seek Error ${String(b)}`,b),b}},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=i.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new wi({mediaSource:i,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),i.duration||(i.duration=this._duration),this._loopTimeout||l(),i.removeEventListener("sourceopen",d),i.removeEventListener("webkitsourceopen",d)};i.addEventListener("sourceopen",d,!1),i.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),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,i=!1,a=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const n=this._findRef(t);if(n){if(i){this._isLastRef(n)&&t>=n.toTime&&(t=n.fromTime);const o=this._findRef(this._video.currentTime),l=Math.abs(this._video.currentTime-t),d=a||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 i=this._buffer.getByTime(this._video.currentTime),a=this._findRef(this._video.currentTime);if(!i||!a){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(a.toTime<i.to+n){const o=this._findRef(a.toTime);o&&o.toTime<i.to+n?(this._buffer.smartRemove(a.fromTime-n,o.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(a.fromTime-n,a.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,a.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||r.isNullable(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return;if(Array.isArray(i)&&i.length===0){this._params.onError("emptyrefs","Empty refs");return}let a;for(let n=0;n<i.length;n++){const o=i[n];if(o.fromTime<=e&&o.toTime>e)return o;o.fromTime>e&&(!a||o.fromTime<a.fromTime)&&(a=o)}if(!a){const n=i[i.length-1];if(e>n.toTime)return n}return a}_isLastRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return!1;const a=i[i.length-1];return e.fromTime===a.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const i=this._video.buffered.start(t),a=this._video.buffered.end(t);if(e>i&&e<a)return Math.round(a*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var V;(function(s){s.STOPPED="stopped",s.MANIFEST_LOADED="manifest-loaded",s.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",s.METADATA_LOADED="metadata-loaded",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(V||(V={}));const Xf=[V.PAUSED,V.PLAYING];class Zf{constructor(e){this.videoState=new Q(V.STOPPED),this.subscription=new r.Subscription,this.representations$=new r.ValueSubject([]),this.currentRepresentation$=new r.ValueSubject(void 0),this.textTracksManager=new Re,this.elementSize$=new r.ValueSubject(void 0),this.dashLiteEvents={idxRequestPing$:new r.Subject,responseHeaders$:new r.Subject,manifestReady$:new r.Subject,representationPlay$:new r.Subject,error$:new r.Subject},this.handleManifestReady=({representations:t,textRepresentations:i})=>{var a,n,o;const l=[];for(const d of t){const u=(n=(a=d.name)!==null&&a!==void 0?a:d.id)!==null&&n!==void 0?n:d.height.toString(10),c=(o=d.name&&zt(d.name))!==null&&o!==void 0?o:nt(d),h=d.bandwidth/1e3,f={width:d.width,height:d.height},p=d.fps;if(!c)continue;const b={id:u,quality:c,bitrate:h,size:f,fps:p};l.push({track:b,representation:d})}if(this.representations$.next(l),this.params.output.availableVideoTracks$.next(l.map(({track:d})=>d)),(i==null?void 0:i.length)>0){const d=[];for(const u of i){const c=u.id||`${u.language}_${Date.now()}`;d.push({id:c,type:"internal",url:u.url||"",language:u.language,isAuto:u.isAuto})}this.params.desiredState.internalTextTracks.startTransitionTo(d)}this.videoState.setState(V.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var i;const a=(i=this.representations$.getValue().find(({representation:n})=>n===t))===null||i===void 0?void 0:i.track;a&&(this.params.output.currentVideoTrack$.next(a),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(a.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return r.assertNonNullable(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${a}; seekState: ${JSON.stringify(o)};`}),a===exports.PlaybackState.STOPPED){t!==V.STOPPED&&(this.videoState.startTransitionTo(V.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(V.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!i)switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&o.state===O.Requested&&Xf.includes(t)&&this.seek(o.position,o.forcePrecise),t){case V.STOPPED:this.videoState.startTransitionTo(V.MANIFEST_LOADED),this.prepare();return;case V.MANIFEST_LOADED:this.videoState.startTransitionTo(V.INITIAL_REPRESENTATION_SELECTED);return;case V.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(V.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case V.METADATA_LOADED:this.videoState.startTransitionTo(V.READY),this.dash.updateRefsForCurrentTime();return;case V.READY:a===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):a===exports.PlaybackState.PAUSED?(this.videoState.setState(V.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):a===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(V.PLAYING),this.playIfAllowed());return;case V.PLAYING:a===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(V.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case V.PAUSED:a===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(V.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),r.merge(this.videoState.stateChangeStarted$.pipe(r.map(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=je(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new cf(this.video),this.dash=new Kf({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:({representations:t,textRepresentations:i})=>this.dashLiteEvents.manifestReady$.next({representations:t,textRepresentations:i}),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,i,a)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:i,thrown:a,category:r.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,i=l=>{e.error$.next({id:"DashProvider",category:r.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:l})},a=()=>{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,i));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$),o(n.isAudioAvailable$,e.isAudioAvailable$),o(n.inPiP$,e.inPiP$),o(n.inFullscreen$,e.inFullscreen$),this.subscription.add(n.seeking$.subscribe(()=>{r.isNullable(this.params.desiredState.seekState.getState().state!==O.Applying)&&(this.videoState.getState()===V.PLAYING||this.videoState.getState()===V.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(Ue(this.video,t.volume,n.volumeState$,i)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Qe(this.video,t.playbackRate,n.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),o(Ai(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===V.READY&&this.videoState.setState(V.READY)},i)).add(n.pause$.subscribe(()=>{this.videoState.setState(V.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(V.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},i)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(V.METADATA_LOADED)},i)).add(n.currentBuffer$.subscribe(l=>{this.buffer.fill(),e.currentBuffer$.next(l)},i)).add(this.dashLiteEvents.error$.pipe(r.map(({id:l,message:d,thrown:u})=>({id:`DashLite_${l}`,category:r.ErrorCategory.WTF,message:d,thrown:u}))).subscribe(this.params.output.error$)).add(r.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$,r.fromEvent(this.video,"progress")).pipe(r.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(),b=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),g=this.elementSize$.getValue(),S=a();f&&this.params.desiredState.autoVideoTrackSwitching.setState(f.to);let m;if(!S&&r.isNonNullable(p))m=p;else{const v=it(this.video.buffered,this.video.currentTime*1e3),y=S?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,T=Math.min(v/y,1);m=(d=Gt(h.map(({track:E})=>E),{container:g,throughput:b,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 r.isNonNullable(m)?(u=h.find(({track:v})=>v.id===m))===null||u===void 0?void 0:u.representation:void 0}),r.filterChanged()).subscribe(this.currentRepresentation$,i)).add(r.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(r.filter(l=>l.to===V.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(r.filter(r.isNonNullable))}).pipe(r.once()).subscribe(()=>this.videoState.setState(V.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(r.filter(r.isNonNullable),r.filterChanged((l,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&a()?l.height<=d.height:l===d)).subscribe(l=>{const d=it(this.video.buffered,this.video.currentTime*1e3),u=Math.min(d/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||u<=.5||!a())&&(this.dash.setQualityByRepresentation(l,!0),this.params.output.hostname$.next(oe(l.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(l=>{const{type:d,reused:u}=jn(l);this.params.output.httpConnectionType$.next(d),this.params.output.httpConnectionReused$.next(u)})).add(this.dashLiteEvents.idxRequestPing$.pipe(r.once(),r.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,i)).add(this.dashLiteEvents.representationPlay$.pipe(r.filter(r.isNonNullable)).subscribe(this.handleRepresentationPlay,i)).add(r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),He(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return r.assertNever(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){Je(this.video).then(e=>{e||(this.videoState.setState(V.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}}var ae;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(ae||(ae={}));var _i;(function(s){s.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",s.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(_i||(_i={}));var he;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(he||(he={}));var H;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(H||(H={}));var Et;(function(s){s.MP4="mp4",s.WEBM="webm"})(Et||(Et={}));var qs=(s,e)=>{for(let t=0;t<s.length;t++)if(s.start(t)*1e3<=e&&s.end(t)*1e3>e)return!0;return!1};const ep=(s,e={})=>{const i=e.timeout||1,a=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-a-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},tp=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Tr=tp?ep:window.requestIdleCallback;var ps,ms;let qn=!1;try{qn=Mn()&&parseInt((ms=(ps=navigator.userAgent.match(/Version\/(\d+)/))===null||ps===void 0?void 0:ps[1])!==null&&ms!==void 0?ms:"",10)<16}catch(s){console.error(s)}class ip{constructor(e){this.bufferFull$=new r.Subject,this.error$=new r.Subject,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const i=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!i),this.currentTask=null}this.queue.length&&this.pull()}catch(i){this.error$.next({id:"BufferTaskQueueUnknown",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const a={operation:"append",data:e,signal:t,callback:i};this.queue.push(a),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(a=>{const n={operation:"remove",from:e,to:t,signal:i,callback:a};this.queue.unshift(n),this.pull()})}async abort(e){return new Promise(t=>{let i;qn&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:a}of this.queue)a(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask);try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:i}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&i==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${i}`,category:r.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:r.assertNever(t)}}}var Er=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};const Yn=new TextDecoder("ascii"),Gn=s=>{let e=0,t=s.getUint32(e);e+=4;const i=new DataView(s.buffer,s.byteOffset+e,4),a=Yn.decode(i);e+=4,t===0?t=1/0:t===1&&(e+=8,t=1/0);const n=Math.min(t,s.byteLength)-e,o=new DataView(s.buffer,s.byteOffset+e,n);return{id:a,size:t,contents:o}},sp=s=>Yn.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",ap=(s,e,t)=>{const i=Gn(s),a=[];let n=0;const o=()=>{const g=i.contents.getUint32(n);return n+=4,g};if((o()&4278190080)!==0)throw new SyntaxError("Unsupported sidx version");o();const u=o(),c=o(),h=o(),f=o()&4294967295;let p=c/u*1e3,b=(t?t.to+1:s.byteOffset+s.byteLength)+h;for(let g=0;g<f;g++){const S=o(),m=S>>>31,v=S<<1>>>1,y=o();if(o(),m!==0)throw new Error("Unsupported multilevel sidx");const T=y/u*1e3;a.push({status:H.NONE,time:{from:p,to:p+T},byte:{from:b,to:b+v-1}}),p+=T,b+=v}return a},rp=s=>{let e=0,t=!1,i=!1;for(;e<=s.byteLength&&!t;){const a=new DataView(s.buffer,s.byteOffset+e);try{const n=Gn(a);if(i||(i=n.id==="mdat"),e+n.size<=s.byteLength)e+=n.size;else break}catch(n){t=!0}}return e>0&&e<=s.byteLength&&i?new DataView(s.buffer,s.byteOffset,e):null},np={validateData:sp,parseInit:()=>null,getIndexRange:()=>{},parseSegments:ap,parseFeedableSegmentChunk:rp};var $;(function(s){s[s.EBML=440786851]="EBML",s[s.EBMLVersion=17030]="EBMLVersion",s[s.EBMLReadVersion=17143]="EBMLReadVersion",s[s.EBMLMaxIDLength=17138]="EBMLMaxIDLength",s[s.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",s[s.DocType=17026]="DocType",s[s.DocTypeVersion=17031]="DocTypeVersion",s[s.DocTypeReadVersion=17029]="DocTypeReadVersion",s[s.Void=236]="Void",s[s.Segment=408125543]="Segment",s[s.SeekHead=290298740]="SeekHead",s[s.Seek=19899]="Seek",s[s.SeekID=21419]="SeekID",s[s.SeekPosition=21420]="SeekPosition",s[s.Info=357149030]="Info",s[s.TimestampScale=2807729]="TimestampScale",s[s.Duration=17545]="Duration",s[s.Tracks=374648427]="Tracks",s[s.Chapters=272869232]="Chapters",s[s.Cluster=524531317]="Cluster",s[s.Timestamp=231]="Timestamp",s[s.SilentTracks=22612]="SilentTracks",s[s.SilentTrackNumber=22743]="SilentTrackNumber",s[s.Position=167]="Position",s[s.PrevSize=171]="PrevSize",s[s.SimpleBlock=163]="SimpleBlock",s[s.BlockGroup=160]="BlockGroup",s[s.EncryptedBlock=175]="EncryptedBlock",s[s.Attachments=423732329]="Attachments",s[s.Tags=307544935]="Tags",s[s.Cues=475249515]="Cues",s[s.CuePoint=187]="CuePoint",s[s.CueTime=179]="CueTime",s[s.CueTrackPositions=183]="CueTrackPositions",s[s.CueTrack=247]="CueTrack",s[s.CueClusterPosition=241]="CueClusterPosition",s[s.CueRelativePosition=240]="CueRelativePosition",s[s.CueDuration=178]="CueDuration",s[s.CueBlockNumber=21368]="CueBlockNumber",s[s.CueCodecState=234]="CueCodecState",s[s.CueReference=219]="CueReference",s[s.CueRefTime=150]="CueRefTime"})($||($={}));var w;(function(s){s.SignedInteger="int",s.UnsignedInteger="uint",s.Float="float",s.String="string",s.UTF8="utf8",s.Date="date",s.Master="master",s.Binary="binary"})(w||(w={}));const $r={[$.EBML]:{type:w.Master},[$.EBMLVersion]:{type:w.UnsignedInteger},[$.EBMLReadVersion]:{type:w.UnsignedInteger},[$.EBMLMaxIDLength]:{type:w.UnsignedInteger},[$.EBMLMaxSizeLength]:{type:w.UnsignedInteger},[$.DocType]:{type:w.String},[$.DocTypeVersion]:{type:w.UnsignedInteger},[$.DocTypeReadVersion]:{type:w.UnsignedInteger},[$.Void]:{type:w.Binary},[$.Segment]:{type:w.Master},[$.SeekHead]:{type:w.Master},[$.Seek]:{type:w.Master},[$.SeekID]:{type:w.Binary},[$.SeekPosition]:{type:w.UnsignedInteger},[$.Info]:{type:w.Master},[$.TimestampScale]:{type:w.UnsignedInteger},[$.Duration]:{type:w.Float},[$.Tracks]:{type:w.Master},[$.Chapters]:{type:w.Master},[$.Cluster]:{type:w.Master},[$.Timestamp]:{type:w.UnsignedInteger},[$.SilentTracks]:{type:w.Master},[$.SilentTrackNumber]:{type:w.UnsignedInteger},[$.Position]:{type:w.UnsignedInteger},[$.PrevSize]:{type:w.UnsignedInteger},[$.SimpleBlock]:{type:w.Binary},[$.BlockGroup]:{type:w.Master},[$.EncryptedBlock]:{type:w.Binary},[$.Attachments]:{type:w.Master},[$.Tags]:{type:w.Master},[$.Cues]:{type:w.Master},[$.CuePoint]:{type:w.Master},[$.CueTime]:{type:w.UnsignedInteger},[$.CueTrackPositions]:{type:w.Master},[$.CueTrack]:{type:w.UnsignedInteger},[$.CueClusterPosition]:{type:w.UnsignedInteger},[$.CueRelativePosition]:{type:w.UnsignedInteger},[$.CueDuration]:{type:w.UnsignedInteger},[$.CueBlockNumber]:{type:w.UnsignedInteger},[$.CueCodecState]:{type:w.UnsignedInteger},[$.CueReference]:{type:w.Master},[$.CueRefTime]:{type:w.UnsignedInteger}},zn=s=>{const e=s.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=Ri(s,t),a=i in $r,n=a?$r[i].type:w.Binary,o=s.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(s.buffer,s.byteOffset+t+1,l-1),u=o&255>>l,c=Ri(d),h=u*2**((l-1)*8)+c,f=t+l;let p;return f+h>s.byteLength?p=new DataView(s.buffer,s.byteOffset+f):p=new DataView(s.buffer,s.byteOffset+f,h),{tag:a?i:"0x"+i.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:p,valueSize:h}},Ri=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{const t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Le=(s,e)=>{switch(e){case w.SignedInteger:return s.getInt8(0);case w.UnsignedInteger:return Ri(s);case w.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case w.String:return new TextDecoder("ascii").decode(s);case w.UTF8:return new TextDecoder("utf-8").decode(s);case w.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case w.Master:return s;case w.Binary:return s;default:r.assertNever(e)}},Wt=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),a=zn(i);if(!e(a))return;a.type===w.Master&&Wt(a.value,e),t=a.value.byteOffset-s.byteOffset+a.valueSize}},op=s=>{if(s.getUint32(0)!==$.EBML)return!1;let e,t,i;const a=zn(s);return Wt(a.value,({tag:n,type:o,value:l})=>(n===$.EBMLReadVersion?e=Le(l,o):n===$.DocType?t=Le(l,o):n===$.DocTypeReadVersion&&(i=Le(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Wn=[$.Info,$.SeekHead,$.Tracks,$.Chapters,$.Cluster,$.Cues,$.Attachments,$.Tags],lp=[$.Timestamp,$.SilentTracks,$.SilentTrackNumber,$.Position,$.PrevSize,$.SimpleBlock,$.BlockGroup,$.EncryptedBlock],up=s=>{let e,t,i,a,n=!1,o=!1,l=!1,d,u;return Wt(s,({tag:c,type:h,value:f,valueSize:p})=>{if(c===$.SeekID){const b=Le(f,h);u=Ri(b)}else c!==$.SeekPosition&&(u=void 0);return c===$.Segment?(e=f.byteOffset,t=f.byteOffset+p):c===$.Info?n=!0:c===$.SeekHead?o=!0:c===$.TimestampScale?i=Le(f,h):c===$.Duration?a=Le(f,h):c===$.SeekPosition&&u===$.Cues?d=Le(f,h):n&&o&&Wn.includes(c)&&(l=!0),!l}),r.assertNonNullable(e,"Failed to parse webm Segment start"),r.assertNonNullable(t,"Failed to parse webm Segment end"),r.assertNonNullable(a,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(a/1e9*i*1e3),cuesSeekPosition:d}},dp=s=>{if(r.isNullable(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},cp=(s,e)=>{let t=!1,i=!1;const a=l=>r.isNonNullable(l.time)&&r.isNonNullable(l.position),n=[];let o;return Wt(s,({tag:l,type:d,value:u})=>{switch(l){case $.Cues:t=!0;break;case $.CuePoint:o&&a(o)&&n.push(o),o={};break;case $.CueTime:o&&(o.time=Le(u,d));break;case $.CueTrackPositions:break;case $.CueClusterPosition:o&&(o.position=Le(u,d));break;default:t&&Wn.includes(l)&&(i=!0)}return!(t&&i)}),o&&a(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}}})},hp=s=>{let e=0,t=!1;try{Wt(s,i=>i.tag===$.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):lp.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[$.SimpleBlock,$.BlockGroup,$.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},fp={validateData:op,parseInit:up,getIndexRange:dp,parseSegments:cp,parseFeedableSegmentChunk:hp};class kr{constructor(e,t,i,a,{fetcher:n,tuning:o,getCurrentPosition:l,compatibilityMode:d=!1}){switch(this.onLastSegment$=new r.ValueSubject(!1),this.fullyBuffered$=new r.ValueSubject(!1),this.playingRepresentation$=new r.ValueSubject(void 0),this.error$=new r.Subject,this.gaps=[],this.subscription=new r.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new st,this.destroyAbortController=new st,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=r.abortable(this.destroyAbortController.signal,async function*(u){const c=this.representations.get(u);r.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 ip(this.sourceBuffer),this.subscription.add(r.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},b=>this.error$.next({id:"SegmentEjection",category:r.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:b}))),this.subscription.add(r.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:r.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(b=>{if(!this.sourceBuffer)return;const g=Math.min(this.bufferLimit,Er(this.sourceBuffer.buffered)*.8);this.bufferLimit=g,this.pruneBuffer(this.getCurrentPosition(),b)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(b=>this.error$.next(b))),yield this.loadInit(c,"high",!0);const h=this.initData.get(c.id),f=this.segments.get(c.id);if(r.assertNonNullable(h,"No init buffer for starting representation"),r.assertNonNullable(f,"No segments for starting representation"),!(h instanceof ArrayBuffer))return;let p=0;for(const b of f)b.time.from-p>0&&this.gaps.push({representation:c.id,from:p,to:b.time.from}),p=b.time.to;r.isNonNullable(c.duration)&&c.duration-p>0&&this.gaps.push({representation:c.id,from:p,to:c.duration}),yield this.sourceBufferTaskQueue.append(h,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId)}.bind(this)),this.switchTo=r.abortable(this.destroyAbortController.signal,async function*(u){if(u===this.downloadingRepresentationId||u===this.switchingToRepresentationId)return;this.switchingToRepresentationId=u;const c=this.representations.get(u);r.assertNonNullable(c,`No such representation ${u}`);let h=this.initData.get(u);if(r.isNullable(h)?yield this.loadInit(c,"high",!1):h instanceof Promise&&(yield h),h=this.initData.get(u),!h||!(h instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=u,this.abort(),yield this.sourceBufferTaskQueue.append(h,this.downloadAbortController.signal);const f=this.getCurrentPosition();r.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=i,i){case Et.MP4:this.containerParser=np;break;case Et.WEBM:this.containerParser=fp;break;default:r.assertNever(i)}this.initData=new Map(a.map(u=>[u.id,null])),this.segments=new Map,this.representations=new Map(a.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 st,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(r.isNullable(e)||r.isNullable(this.downloadingRepresentationId)||r.isNullable(this.playingRepresentationId)||r.isNullable(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(r.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const a=i.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=it(this.sourceBuffer.buffered,e),h=a?a.time.to+100:-1/0;a&&c>=a.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&Er(this.sourceBuffer.buffered)>=this.bufferLimit){const u=it(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(i,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(l.includes(a))u="high";else{const c=Ne(l,0);c&&c.time.from-a.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status===H.FED&&!l.length&&it(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=Ne(i,-1);d&&d.status===H.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(a===d))}findSegmentStartTime(e){var t,i,a;const n=(i=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&i!==void 0?i: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(a=l==null?void 0:l.time.from)!==null&&a!==void 0?a:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){const a=e.findIndex(({status:h,time:{from:f,to:p}},b)=>{const g=f<=i&&p>=i,S=f>i||g||b===0&&i===0,m=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&f<=i+m||p<=i+m;return(h===H.NONE||h===H.PARTIALLY_EJECTED&&S&&v&&this.sourceBuffer&&!qs(this.sourceBuffer.buffered,i))&&S&&v});if(a===-1)return[];if(t!==he.BYTE_RANGE)return e.slice(a,a+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=a;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}async loadSegments(e,t,i="auto"){if(!e.length)return;let a,n,o=e;const{type:l}=t.segmentReference;switch(l){case he.BYTE_RANGE:{a=t.segmentReference.url,n={from:Ne(e,0).byte.from,to:Ne(e,-1).byte.to};break}case he.TEMPLATE:{const u=Ne(e,0);a=new URL(u.url,t.segmentReference.baseUrl).toString(),o=[u];break}default:r.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&&(await r.abortable(d,async function*(){const u=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield 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(a,{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:r.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}},signal:d,priority:i}).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 i=!1;const a=this.getCurrentPosition();this.sourceBuffer&&r.isNonNullable(a)&&(i=it((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,a)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,i||this.error$.next({id:"SegmentDownload",category:r.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,i,a,n){if(!this.activeSegments.size)return;const o=()=>{this.abort()},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 b of(f=this.segments.get(p.id))!==null&&f!==void 0?f:[])b.status===H.FED&&b.time.from===h.segment.time.from&&b.time.to===h.segment.time.to&&(b.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===he.BYTE_RANGE,b=p?f.byte.to-f.byte.from+1:c;if(h.representationId!==t||!(!p||f.byte.from>=i&&f.byte.to<i+e.byteLength))continue;if(n.aborted){o();continue}const S=p?f.byte.from-i:0,m=p?f.byte.to-i:e.byteLength,v=S<a,y=m<=a;if(f.status===H.DOWNLOADING&&v&&y){f.status=H.DOWNLOADED,this.activeSegments.delete(h);const T=new DataView(e.buffer,e.byteOffset+S,b);this.sourceBufferTaskQueue.append(T,n).then(E=>E&&!n.aborted?l(h):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&v&&(h.loadedBytes=Math.min(b,a-S),h.loadedBytes>h.feedingBytes)){const T=new DataView(e.buffer,e.byteOffset+S+h.feedingBytes,h.loadedBytes-h.feedingBytes),E=h.loadedBytes===b?T:this.containerParser.parseFeedableSegmentChunk(T);E!=null&&E.byteLength&&(f.status=H.PARTIALLY_FED,h.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,n).then(A=>{if(n.aborted)o();else if(A)h.fedBytes+=E.byteLength,h.fedBytes===b&&l(h);else{if(h.feedingBytes<b)return;o()}}))}}}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[a,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=Tr(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const a=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!i&&this.failedDownloads>0?r.abortable(this.destroyAbortController.signal,async function*(){const l=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,l))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,a)).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),i&&this.error$.next({id:"LoadInits",category:r.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||r.isNullable(e)||this.sourceBuffer.updating)return!1;let a=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;a+=h};for(const u of this.segments.values())for(const c of u){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;c.status===H.FED&&d(c)}if(l=isFinite(n)&&isFinite(o),!l){a=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)||a>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&&i){a=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 i of t){let a={representation:e,from:i.time.from,to:i.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<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&l>=i.time.to){a=void 0;break}l>i.time.from&&l<i.time.to&&(a.from=l),o<i.time.to&&o>i.time.from&&(a.to=o)}}a&&a.to-a.from>=1&&!this.gaps.some(n=>a&&n.from===a.from&&n.to===a.to)&&this.gaps.push(a)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Tr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:r.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(r.isNullable(this.sourceBuffer)||r.isNullable(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const a=Math.round(this.sourceBuffer.buffered.start(i)*1e3),n=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:a,to:n})}const t=1;for(const i of this.segments.values())for(const a of i){const{status:n}=a;if(n!==H.FED&&n!==H.PARTIALLY_EJECTED)continue;const o=Math.floor(a.time.from),l=Math.ceil(a.time.to),d=e.some(c=>c.from-t<=o&&c.to+t>=l),u=e.filter(c=>o>=c.from-t&&o<=c.to+t||l>=c.from-t&&l<=c.to+t);d||(u.length===1?a.status=H.PARTIALLY_EJECTED:a.status=H.NONE)}}}var vt;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(vt||(vt={}));class pp{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new r.ValueSubject(void 0),this.lastConnectionReused$=new r.ValueSubject(void 0),this.lastRequestFirstBytes$=new r.ValueSubject(void 0),this.abortAllController=new st,this.subscription=new r.Subscription,this.fetchManifest=r.abortable(this.abortAllController.signal,async function*(a){let n=a;this.requestQuic&&(n=Tt(n));const o=yield yt(n,{signal:this.abortAllController.signal}).catch(Ot);return o?(this.onHeadersReceived(o.headers),o.text()):null}.bind(this)),this.fetch=r.abortable(this.abortAllController.signal,async function*(a,{rangeMethod:n=this.compatibilityMode?vt.HEADER:vt.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0}={}){var h,f,p,b;let g=a;const S=new Headers;if(o)switch(n){case vt.HEADER:{S.append("Range",`bytes=${o.from}-${o.to}`);break}case vt.PARAM:{const k=new URL(g,location.href);k.searchParams.append("bytes",`${o.from}-${o.to}`),g=k.toString();break}default:r.assertNever(n)}this.requestQuic&&(g=Tt(g));let m=this.abortAllController.signal;if(u){const k=new st;if(this.subscription.add(r.merge(r.fromEvent(this.abortAllController.signal,"abort"),r.fromEvent(u,"abort")).subscribe(()=>{try{k.abort()}catch(D){Ot(D)}})),this.abortAllController.signal.aborted||u.aborted)try{k.abort()}catch(D){Ot(D)}m=k.signal}const v=r.now(),y=yield yt(g,{priority:d,headers:S,signal:m}).catch(Ot),T=r.now();if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(T-v),!y)return null;if(!y.ok||!y.body)return Promise.reject(new Error(`Fetch error ${y.status}: ${y.statusText}`));this.onHeadersReceived(y.headers);const E=parseInt((f=y.headers.get("Content-Length"))!==null&&f!==void 0?f:"",10)||o&&o.to-o.from+1||NaN;if(!E){const k=yield y.arrayBuffer();return(p=this.throughputEstimator)===null||p===void 0||p.addRawSpeed(k.byteLength,r.now()-T),l==null||l(new DataView(k),k.byteLength),k}if(!l&&!c)return y.arrayBuffer();const[A,L]=y.body.tee(),R=A.getReader();c&&((b=this.throughputEstimator)===null||b===void 0||b.trackStream(L));let N=0;const M=new ArrayBuffer(E),I=new Uint8Array(M),_=new DataView(M);let j=!1;const W=k=>{j=!0,Ot(k)},X=r.abortable(m,async function*({done:k,value:D}){N===0&&this.lastRequestFirstBytes$.next(r.now()-v),!m.aborted&&!k&&D&&(I.set(D,N),N+=D.byteLength,l==null||l(_,N),yield R==null?void 0:R.read().then(X,W))}.bind(this));return yield R==null?void 0:R.read().then(X,W),j?null:M}.bind(this)),this.fetchByteRangeRepresentation=r.abortable(this.abortAllController.signal,async function*(a,n,o){var l;if(a.type!==he.BYTE_RANGE)return null;const{from:d,to:u}=a.initRange;let c=d,h=u,f=!1,p,b;a.indexRange&&(p=a.indexRange.from,b=a.indexRange.to,f=u+1===p,f&&(c=Math.min(p,d),h=Math.max(b,u))),c=Math.min(c,0);const g=yield this.fetch(a.url,{range:{from:c,to:h},priority:o,measureThroughput:!1});if(!g)return null;const S=new DataView(g,d-c,u-c+1);if(!n.validateData(S))throw new Error("Invalid media file");const m=n.parseInit(S),v=(l=a.indexRange)!==null&&l!==void 0?l:n.getIndexRange(m);if(!v)throw new ReferenceError("No way to load representation index");let y;if(f)y=new DataView(g,v.from-c,v.to-v.from+1);else{const E=yield this.fetch(a.url,{range:v,priority:o,measureThroughput:!1});if(!E)return null;y=new DataView(E)}const T=n.parseSegments(y,m,v);return{dataView:new DataView(g),segments:T}}.bind(this)),this.fetchTemplateRepresentation=r.abortable(this.abortAllController.signal,async function*(a,n){if(a.type!==he.TEMPLATE)return null;const o=new URL(a.initUrl,a.baseUrl).toString(),l=yield this.fetch(o,{priority:n,measureThroughput:!1});return l?{segments:a.segments.map(u=>({...u,status:H.NONE,size:void 0})),dataView:new DataView(l)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=jn(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var a,n;const{type:o}=e;switch(o){case he.BYTE_RANGE:return(a=await this.fetchByteRangeRepresentation(e,t,i))!==null&&a!==void 0?a:null;case he.TEMPLATE:return(n=await this.fetchTemplateRepresentation(e,i))!==null&&n!==void 0?n:null;default:r.assertNever(o)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Ot=s=>{if(!(s instanceof DOMException)||!(s.name==="AbortError"||s.code===20))throw s};var mp=at,bp=Ni,vp=Te,Sp=vp("match"),gp=function(s){var e;return mp(s)&&((e=s[Sp])!==void 0?!!e:bp(s)=="RegExp")},yp=Bi,Tp=String,Ep=function(s){if(yp(s)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return Tp(s)},$p=rt,kp=function(){var s=$p(this),e="";return s.hasIndices&&(e+="d"),s.global&&(e+="g"),s.ignoreCase&&(e+="i"),s.multiline&&(e+="m"),s.dotAll&&(e+="s"),s.unicode&&(e+="u"),s.unicodeSets&&(e+="v"),s.sticky&&(e+="y"),e},Pp=Ve,Ap=Fe,wp=Qs,_p=kp,Pr=RegExp.prototype,Rp=function(s){var e=s.flags;return e===void 0&&!("flags"in Pr)&&!Ap(s,"flags")&&wp(Pr,s)?Pp(_p,s):e},da=Me,Ip=Li,Np=Math.floor,bs=da("".charAt),Dp=da("".replace),vs=da("".slice),Cp=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Lp=/\$([$&'`]|\d{1,2})/g,xp=function(s,e,t,i,a,n){var o=t+s.length,l=i.length,d=Lp;return a!==void 0&&(a=Ip(a),d=Cp),Dp(n,d,function(u,c){var h;switch(bs(c,0)){case"$":return"$";case"&":return s;case"`":return vs(e,0,t);case"'":return vs(e,o);case"<":h=a[vs(c,1,-1)];break;default:var f=+c;if(f===0)return u;if(f>l){var p=Np(f/10);return p===0?u:p<=l?i[p-1]===void 0?bs(c,1):i[p-1]+bs(c,1):u}h=i[f-1]}return h===void 0?"":h})},Op=Oi,Bp=Ve,ca=Me,Ar=Gs,Mp=fe,Vp=Di,Fp=gp,pt=Ep,Up=Ci,jp=Rp,Hp=xp,qp=Te,Yp=qp("replace"),Gp=TypeError,Qn=ca("".indexOf),zp=ca("".replace),wr=ca("".slice),Wp=Math.max,_r=function(s,e,t){return t>s.length?-1:e===""?t:Qn(s,e,t)};Op({target:"String",proto:!0},{replaceAll:function(e,t){var i=Ar(this),a,n,o,l,d,u,c,h,f,p=0,b=0,g="";if(!Vp(e)){if(a=Fp(e),a&&(n=pt(Ar(jp(e))),!~Qn(n,"g")))throw Gp("`.replaceAll` does not allow non-global regexes");if(o=Up(e,Yp),o)return Bp(o,e,i,t);if(a)return zp(pt(i),e,t)}for(l=pt(i),d=pt(e),u=Mp(t),u||(t=pt(t)),c=d.length,h=Wp(1,c),p=_r(l,d,0);p!==-1;)f=u?pt(t(d,p,l)):Hp(d,l,p,[],void 0,t),g+=wr(l,b,p)+f,b=p+c,p=_r(l,d,p+h);return b<l.length&&(g+=wr(l,b)),g}});var Qp=Fn,Jp=Qp("String","replaceAll"),Kp=Jp,Xp=Kp,Zp=Xp,em=Zp,Rr=em;const Ir=s=>{if(!s.startsWith("P"))return;const e=(o,l)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*l},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),a=(i==null?void 0:i[1])==="-"?-1:1,n={days:e(i==null?void 0:i[5],a),hours:e(i==null?void 0:i[6],a),minutes:e(i==null?void 0:i[7],a),seconds:e(i==null?void 0:i[8],a)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},Ss=(s,e)=>{let t=s;t=Rr(t,"$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[a,n]of Object.entries(i)){const o=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=Rr(t,o,(l,d)=>r.isNullable(n)?l:r.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},tm=(s,e)=>{var t,i,a,n,o,l,d,u,c,h,f,p,b,g,S,m,v,y,T,E,A,L,R,N,M,I,_,j,W,X,k,D,G,Z,ie,le,Ee,pe,F,se;const me=new DOMParser().parseFromString(s,"application/xml"),Ie={video:[],audio:[],text:[]},Ke=me.children[0],Ye=Ke.getElementsByTagName("Period")[0],lt=Ye.children;let $e;const Pt=Ke.getAttribute("mediaPresentationDuration"),ha=Ye.getAttribute("duration");if(Pt)$e=Ir(Pt);else if(ha){const be=Ir(ha);r.isNonNullable(be)&&($e=be)}let io=0;const Fi=(i=(t=Ke.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],so=Fi.includes(_i.WEBM_AS_IN_FFMPEG)||Fi.includes(_i.WEBM_AS_IN_SPEC)?Et.WEBM:Et.MP4;for(const be of lt){const Qt=be.getAttribute("mimeType"),ao=be.getAttribute("codecs"),fa=(a=be.getAttribute("contentType"))!==null&&a!==void 0?a:Qt==null?void 0:Qt.split("/")[0],ro=(o=(n=be.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],pa=be.querySelectorAll("Representation"),no=be.querySelector("SegmentTemplate");if(fa===ae.TEXT){for(const ee of pa){const Ge=ee.getAttribute("id")||"",Jt=be.getAttribute("lang"),ut=(u=(d=(l=ee.querySelector("BaseURL"))===null||l===void 0?void 0:l.textContent)===null||d===void 0?void 0:d.trim())!==null&&u!==void 0?u:"",Ui=Ge.includes("auto"),ji=new URL(ut,e).toString();Ie[ae.TEXT].push({id:Ge,lang:Jt,kind:ae.TEXT,url:ji,isAuto:Ui})}continue}for(const ee of pa){const Ge=(c=ee.getAttribute("mimeType"))!==null&&c!==void 0?c:Qt,Jt=(f=(h=ee.getAttribute("codecs"))!==null&&h!==void 0?h:ao)!==null&&f!==void 0?f:"",ut=(b=(p=ee.getAttribute("contentType"))!==null&&p!==void 0?p:Ge==null?void 0:Ge.split("/")[0])!==null&&b!==void 0?b:fa,Ui=(S=(g=be.getAttribute("profiles"))===null||g===void 0?void 0:g.split(","))!==null&&S!==void 0?S:[],ji=parseInt((m=ee.getAttribute("width"))!==null&&m!==void 0?m:"",10),ma=parseInt((v=ee.getAttribute("height"))!==null&&v!==void 0?v:"",10),ba=parseInt((y=ee.getAttribute("bandwidth"))!==null&&y!==void 0?y:"",10)/1e3,va=(T=ee.getAttribute("frameRate"))!==null&&T!==void 0?T:"",oo=(E=ee.getAttribute("quality"))!==null&&E!==void 0?E:void 0,lo=va?la(va):void 0,uo=(A=ee.getAttribute("id"))!==null&&A!==void 0?A:(io++).toString(10),co=ut==="video"?`${ma}p`:ut==="audio"?`${ba}Kbps`:Jt,ho=`${uo}@${co}`,fo=(N=(R=(L=ee.querySelector("BaseURL"))===null||L===void 0?void 0:L.textContent)===null||R===void 0?void 0:R.trim())!==null&&N!==void 0?N:"",Sa=new URL(fo,e).toString(),po=[...Fi,...ro,...Ui];let Hi;const mo=ee.querySelector("SegmentBase"),Xe=(M=ee.querySelector("SegmentTemplate"))!==null&&M!==void 0?M:no;if(mo){const At=(_=(I=ee.querySelector("SegmentBase Initialization"))===null||I===void 0?void 0:I.getAttribute("range"))!==null&&_!==void 0?_:"",[wt,Yi]=At.split("-").map(Ze=>parseInt(Ze,10)),_t={from:wt,to:Yi},Rt=(j=ee.querySelector("SegmentBase"))===null||j===void 0?void 0:j.getAttribute("indexRange"),[Gi,Kt]=Rt?Rt.split("-").map(Ze=>parseInt(Ze,10)):[],It=Rt?{from:Gi,to:Kt}:void 0;Hi={type:he.BYTE_RANGE,url:Sa,initRange:_t,indexRange:It}}else if(Xe){const At={representationId:(W=ee.getAttribute("id"))!==null&&W!==void 0?W:void 0,bandwidth:(X=ee.getAttribute("bandwidth"))!==null&&X!==void 0?X:void 0},wt=parseInt((k=Xe.getAttribute("timescale"))!==null&&k!==void 0?k:"",10),Yi=(D=Xe.getAttribute("initialization"))!==null&&D!==void 0?D:"",_t=Xe.getAttribute("media"),Rt=(Z=parseInt((G=Xe.getAttribute("startNumber"))!==null&&G!==void 0?G:"",10))!==null&&Z!==void 0?Z:1,Gi=Ss(Yi,At);if(!_t)throw new ReferenceError("No media attribute in SegmentTemplate");const Kt=(ie=Xe.querySelectorAll("SegmentTimeline S"))!==null&&ie!==void 0?ie:[],It=[];if(Kt.length){let Ze=Rt,et=0;for(const Nt of Kt){const dt=parseInt((le=Nt.getAttribute("d"))!==null&&le!==void 0?le:"",10)*1e3,Dt=parseInt((Ee=Nt.getAttribute("r"))!==null&&Ee!==void 0?Ee:"",10)||0,Ct=(F=parseInt((pe=Nt.getAttribute("t"))!==null&&pe!==void 0?pe:"",10))!==null&&F!==void 0?F:void 0;for(let ga=0;ga<Dt+1;ga++){const bo=Ss(_t,{...At,segmentNumber:Ze.toString(10),segmentTime:Ct.toString(10)}),vo=Ct?Ct/wt:et;et+=dt/wt;const So=et;Ze++,It.push({time:{from:vo,to:So},url:bo})}}}else if(r.isNonNullable($e)){const et=parseInt((se=Xe.getAttribute("duration"))!==null&&se!==void 0?se:"",10)/wt*1e3,Nt=Math.ceil($e/et);let dt=0;for(let Dt=1;Dt<Nt;Dt++){const Ct=Ss(_t,{...At,segmentNumber:Dt.toString(10),segmentTime:dt.toString(10)});It.push({time:{from:dt,to:dt+et},url:Ct}),dt+=et}}Hi={type:he.TEMPLATE,baseUrl:Sa,initUrl:Gi,segments:It}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ut||!Ge)continue;const qi={video:ae.VIDEO,audio:ae.AUDIO,text:ae.TEXT}[ut];qi&&Ie[qi].push({id:ho,kind:qi,segmentReference:Hi,profiles:po,duration:$e,bitrate:ba,mime:Ge,codecs:Jt,width:ji,height:ma,fps:lo,quality:oo})}}return{duration:$e,container:so,representations:Ie}},im=["timeupdate","progress","play","seeked","stalled","waiting"];var ce;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(ce||(ce={}));let sm=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new r.Subscription,this.state$=new Q(ce.NONE),this.currentVideoRepresentation$=new r.ValueSubject(void 0),this.error$=new r.Subject,this.lastConnectionType$=new r.ValueSubject(void 0),this.lastConnectionReused$=new r.ValueSubject(void 0),this.lastRequestFirstBytes$=new r.ValueSubject(void 0),this.forceEnded$=new r.Subject,this.gapWatchdogStarted=!1,this.destroyController=new st,this.initManifest=r.abortable(this.destroyController.signal,async function*(t,i){this.element=t,this.state$.startTransitionTo(ce.MANIFEST_READY);const a=yield this.fetcher.fetchManifest(i).catch(l=>this.error$.next({id:"LoadManifest",category:r.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:l}));if(!a)return;let n;try{n=tm(a!=null?a:"",i)}catch(l){this.error$.next({id:"ManifestParsing",category:r.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:l})}if(!n)return;const o=({kind:l,mime:d,codecs:u})=>{var c,h,f;return Boolean(((c=t.canPlayType)===null||c===void 0?void 0:c.call(t,d))&&((f=(h=window.MediaSource)===null||h===void 0?void 0:h.isTypeSupported)===null||f===void 0?void 0:f.call(h,`${d}; codecs="${u}"`))||l===ae.TEXT)};this.manifest={...n,representations:Yt(Object.entries(n.representations).map(([l,d])=>[l,d.filter(o)]))},this.manifest.representations.video.length?this.state$.setState(ce.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:r.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this)),this.initRepresentations=r.abortable(this.destroyController.signal,async function*(t,i){r.assertNonNullable(this.manifest),r.assertNonNullable(this.element),this.state$.startTransitionTo(ce.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const a={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0};this.videoBufferManager=new kr(ae.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,a),this.bufferManagers=[this.videoBufferManager],r.isNonNullable(i)&&(this.audioBufferManager=new kr(ae.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,a),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=r.merge(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(r.map(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),o=r.merge(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(r.map(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.subscription.add(r.merge(this.forceEnded$,r.combine({allBuffersFull:n,someBufferEnded:o}).pipe(r.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:r.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.subscription.add(r.merge(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(l=>{var d;return(d=this.source)===null||d===void 0?void 0:d.addEventListener("sourceopen",l)})),r.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&r.isNonNullable(i)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)]):yield this.videoBufferManager.startWith(t),this.state$.setState(ce.REPRESENTATIOS_READY)}.bind(this)),this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;const a=this.element.currentTime*1e3;this.videoBufferManager.maintain(a),(t=this.audioBufferManager)===null||t===void 0||t.maintain(a),(this.videoBufferManager.gaps.length||!((i=this.audioBufferManager)===null||i===void 0)&&i.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=r.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),n=>{this.error$.next({id:"GapWatchdog",category:r.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new pp({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initBuffer(){r.assertNonNullable(this.element),this.state$.setState(ce.RUNNING),this.subscription.add(r.merge(...im.map(e=>r.fromEvent(this.element,e)),r.fromEvent(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:r.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(r.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(r.fromEvent(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&qs(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){const i={[ae.VIDEO]:this.videoBufferManager,[ae.AUDIO]:this.audioBufferManager,[ae.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)}seek(e,t){var i,a,n,o,l;r.assertNonNullable(this.element),r.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((i=this.videoBufferManager.findSegmentStartTime(e))!==null&&i!==void 0?i:e,(n=(a=this.audioBufferManager)===null||a===void 0?void 0:a.findSegmentStartTime(e))!==null&&n!==void 0?n:e),qs(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(ce.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)===null||e===void 0?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3,t=[];for(const i of this.bufferManagers)for(const a of i.gaps)i.playingRepresentation$.getValue()===a.representation&&a.from<=e&&a.to>e&&(this.element.duration*1e3-a.to<this.tuning.endGapTolerance?t.push(1/0):t.push(a.to));if(t.length){const i=Math.max(...t);i===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=i/1e3}}};var J;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(J||(J={}));const am=({id:s,width:e,height:t,bitrate:i,fps:a,quality:n})=>{var o;const l=(o=n?zt(n):void 0)!==null&&o!==void 0?o:nt({width:e,height:t});return l&&{id:s,quality:l,bitrate:i,size:{width:e,height:t},fps:a}},rm=({id:s,bitrate:e})=>({id:s,bitrate:e}),nm=({id:s,lang:e,url:t,isAuto:i})=>({id:s,url:t,isAuto:i,type:"internal",language:e}),om=(s,e,t)=>{var i;const a=e.indexOf(t);return(i=Ne(s,Math.round(s.length*a/e.length)))!==null&&i!==void 0?i:Ne(s,-1)};class lm{constructor(e){this.subscription=new r.Subscription,this.videoState=new Q(J.STOPPED),this.elementSize$=new r.ValueSubject(void 0),this.textTracksManager=new Re,this.videoTracks=[],this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new If,this.textTracks=[],this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(n.state===O.Requested&&(a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&t!==J.STOPPED&&i!==exports.PlaybackState.STOPPED&&this.seek(n.position,n.forcePrecise),i===exports.PlaybackState.STOPPED){t!==J.STOPPED&&(this.videoState.startTransitionTo(J.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(J.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(t){case J.STOPPED:this.videoState.startTransitionTo(J.READY),this.prepare();return;case J.READY:i===exports.PlaybackState.PAUSED?(this.videoState.setState(J.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===exports.PlaybackState.READY&&P(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case J.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(J.PAUSED),this.video.pause()):(a==null?void 0:a.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case J.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(t)}}},this.params=e,this.video=je(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new sm({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=qe(this.video),a=u=>{e.error$.next({id:"DashVKProvider",category:r.ErrorCategory.WTF,message:"DashVKProvider internal logic error",thrown:u})},n=(u,c)=>this.subscription.add(u.subscribe(c,a));n(i.timeUpdate$,e.position$),n(i.durationChange$,e.duration$),n(i.ended$,e.endedEvent$),n(i.looped$,e.loopedEvent$),n(i.error$,e.error$),n(i.isBuffering$,e.isBuffering$),n(i.currentBuffer$,e.currentBuffer$),n(i.playing$,e.firstFrameEvent$),n(i.canplay$,e.canplay$),n(i.isAudioAvailable$,e.isAudioAvailable$),n(i.inPiP$,e.inPiP$),n(i.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.lastRequestFirstBytes$.pipe(r.filter(r.isNonNullable),r.once()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(ot(this.video,t.isLooped,a)),this.subscription.add(Ue(this.video,t.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Qe(this.video,t.playbackRate,i.playbackRateState$,a)),n(Ai(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(J.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},a)).add(i.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},a)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===J.PLAYING&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var c;if(u===ce.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();r.assertNonNullable(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((S,m)=>m.bitrate-S.bitrate),p=Array.from(h.video).sort((S,m)=>m.bitrate-S.bitrate),b=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const S of f){const m=rm(S);m&&this.audioTracks.push({track:m,representation:S})}for(const S of p){const m=am(S);if(m){this.videoTracks.push({track:m,representation:S});const v=!this.params.tuning.isAudioDisabled&&om(f,p,S);v&&this.audioRepresentations.set(S.id,v)}}for(const S of b){const m=nm(S);m&&this.textTracks.push({track:m,representation:S})}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:S})=>S)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:S})=>S)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:S})=>S));const g=this.selectVideoRepresentation();r.assertNonNullable(g),this.player.initRepresentations(g.id,(c=this.audioRepresentations.get(g.id))===null||c===void 0?void 0:c.id)}else u===ce.REPRESENTATIOS_READY&&(this.videoState.setState(J.READY),this.player.initBuffer())},a));const o=u=>e.error$.next({id:"RepresentationSwitch",category:r.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(r.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,r.fromEvent(this.video,"progress")).subscribe(()=>{const u=this.player.state$.getState(),c=this.player.state$.getTransition();if(u!==ce.RUNNING||c||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const h=this.selectVideoRepresentation();if(h){this.player.switchRepresentation(ae.VIDEO,h.id).catch(o);const f=this.audioRepresentations.get(h.id);f&&this.player.switchRepresentation(ae.AUDIO,f.id).catch(o)}},a)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(r.filterChanged(),r.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$,a)),this.textTracksManager.connect(this.video,t,e);const l=t.playbackState.stateChangeStarted$.pipe(r.map(({to:u})=>u===exports.PlaybackState.READY),r.filterChanged());this.subscription.add(r.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(r.merge(l,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,a))}selectVideoRepresentation(){var e,t,i,a,n,o;const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.videoTrack.getState(),u=(e=this.videoTracks.find(({track:{id:m}})=>m===d))===null||e===void 0?void 0:e.track,c=this.params.output.currentVideoTrack$.getValue(),h=it(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),b=Math.max(u&&!l&&(i=(t=this.audioRepresentations.get(u.id))===null||t===void 0?void 0:t.bitrate)!==null&&i!==void 0?i:0,c&&(n=(a=this.audioRepresentations.get(c.id))===null||a===void 0?void 0:a.bitrate)!==null&&n!==void 0?n:0),g=Gt(this.videoTracks.map(({track:m})=>m),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:b,forwardBufferHealth:p,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),S=l?g!=null?g:u:u!=null?u:g;return S&&((o=this.videoTracks.find(({track:m})=>m===S))===null||o===void 0?void 0:o.representation)}async prepare(){this.player.initManifest(this.video,this.params.source.url)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),He(this.video)}playIfAllowed(){Je(this.video).then(e=>{e||(this.videoState.setState(J.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}}const um=5e3,Pe={};var U;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(U||(U={}));const Bt=(s,e)=>new r.Observable(t=>{const i=(a,n)=>t.next(n);return s.on(e,i),()=>s.off(e,i)});class dm{constructor(e){this.subscription=new r.Subscription,this.videoState=new Q(U.INITIALIZING),this.textTracksManager=new Re,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(t!==U.INITIALIZING)switch((a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&n.state===O.Requested&&this.seek(n.position),i){case exports.PlaybackState.STOPPED:switch(t){case U.STOPPED:break;case U.READY:case U.PLAYING:case U.PAUSED:this.stop();break;default:r.assertNever(t)}break;case exports.PlaybackState.READY:switch(t){case U.STOPPED:this.prepare();break;case U.READY:case U.PLAYING:case U.PAUSED:break;default:r.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case U.PLAYING:break;case U.STOPPED:this.prepare();break;case U.READY:case U.PAUSED:this.playIfAllowed();break;default:r.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case U.PAUSED:break;case U.STOPPED:this.prepare();break;case U.READY:this.videoState.setState(U.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case U.PLAYING:this.pause();break;default:r.assertNever(t)}break;default:r.assertNever(i)}},this.video=je(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)===null||e===void 0||e.detachMedia(),(t=this.hls)===null||t===void 0||t.destroy(),this.params.output.element$.next(void 0),He(this.video)}loadHlsJs(){let e=!1;const t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:r.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},i=window.setTimeout(()=>t("timeout"),um);import("hls.js").then(a=>{e||(Pe.Hls=a.default,Pe.Events=a.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){r.assertNonNullable(Pe.Hls,"hls.js not loaded"),this.hls=new Pe.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(U.STOPPED)}subscribe(){r.assertNonNullable(Pe.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=u=>{t.error$.next({id:"HlsJsProvider",category:r.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=qe(this.video),n=(u,c)=>this.subscription.add(u.subscribe(c,i));n(a.timeUpdate$,t.position$),n(a.durationChange$,t.duration$),n(a.ended$,t.endedEvent$),n(a.looped$,t.loopedEvent$),n(a.error$,t.error$),n(a.isBuffering$,t.isBuffering$),n(a.currentBuffer$,t.currentBuffer$),n(a.loadStart$,t.firstBytesEvent$),n(a.playing$,t.firstFrameEvent$),n(a.canplay$,t.canplay$),n(a.seeked$,t.seekedEvent$),n(a.isAudioAvailable$,t.isAudioAvailable$),n(a.inPiP$,t.inPiP$),n(a.inFullscreen$,t.inFullscreen$),this.subscription.add(ot(this.video,e.isLooped,i)),this.subscription.add(Ue(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Qe(this.video,e.playbackRate,a.playbackRateState$,i)),this.subscription.add(Bt(this.hls,Pe.Events.ERROR).subscribe(u=>{var c;u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:r.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(a.playing$.subscribe(()=>{this.videoState.setState(U.PLAYING),P(e.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(U.PAUSED),P(e.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===U.READY&&this.videoState.setState(U.READY),this.videoState.getState()===U.PLAYING&&this.playIfAllowed()},i)),n(Bt(this.hls,Pe.Events.MANIFEST_PARSED).pipe(r.map(({levels:u})=>u.reduce((c,h)=>{var f,p;const b=h.name||h.height.toString(10),{width:g,height:S}=h,m=(p=zt((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&p!==void 0?p:nt({width:g,height:S});if(!m)return c;const v=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,y={id:b.toString(),quality:m,bitrate:h.bitrate/1e3,size:{width:g,height:S},fps:v};return this.trackLevels.set(b,{track:y,level:h}),c.push(y),c},[]))),t.availableVideoTracks$),n(Bt(this.hls,Pe.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){const c=[];for(const h of u.subtitleTracks){const f=h.name,p=h.attrs.URI||"",b=h.lang,g="internal",S=f.includes("auto");c.push({id:f,url:p,language:b,type:g,isAuto:S})}e.internalTextTracks.startTransitionTo(c)}}),n(Bt(this.hls,Pe.Events.LEVEL_LOADING).pipe(r.map(({url:u})=>oe(u))),t.hostname$),this.subscription.add(ge(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:i}));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=Bt(this.hls,Pe.Events.LEVEL_SWITCHED).pipe(r.map(({level:u})=>o(this.hls.levels[u])));l.pipe(r.filter(r.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(ge(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(r.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,b=this.hls.levels[p];!b||h.bitrate>b.bitrate?this.hls.nextLevel=f:(this.hls.loadLevel=f,this.hls.loadLevel=f)},{changed$:l.pipe(r.map(u=>u==null?void 0:u.id)),onError:i})),n(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=r.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(U.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(U.PLAYING),await Je(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState(U.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(U.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(U.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const Nr="X-Playback-Duration";var Dr=async s=>{const e=await yt(s,{method:"HEAD"});return e.headers.has(Nr)?parseInt(e.headers.get(Nr),10):void 0};const cm=s=>{let e=null;if(s.QUALITY&&(e=zt(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(a=>parseInt(a,10));e=nt({width:t,height:i})}return e!=null?e:null},Jn=async(s,e=s)=>{var t;const n=(await(await yt(s)).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=Yt(u[1].split(",").map(m=>m.split("="))),h=(t=c.QUALITY)!==null&&t!==void 0?t:`stream-${c.BANDWIDTH}`,f=cm(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 b=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0;let g;if(c.RESOLUTION){const[m,v]=c.RESOLUTION.split("x").map(y=>parseInt(y,10));m&&v&&(g={width:m,height:v})}const S=new URL(n[++l],e).toString();f&&o.push({id:h,quality:f,url:S,bandwidth:p,size:g,fps:b})}return o};var q;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(q||(q={}));class hm{constructor(e){var t;this.subscription=new r.Subscription,this.videoState=new Q(q.STOPPED),this.textTracksManager=new Re,this.manifests$=new r.ValueSubject([]),this.liveOffset=new oa,this.manifestStartTime$=new r.ValueSubject(void 0),this.syncPlayback=()=>{const a=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){a!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(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(a===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===O.None&&this.params.desiredState.seekState.setState({state:O.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&c.state===O.Requested){this.videoState.startTransitionTo(q.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(a){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 r.assertNever(a)}},this.params=e,this.video=je(e.container),this.params.output.element$.next(this.video);const i={id:"master",quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([i]),Jn(gt(this.params.source.url),this.params.source.url).then(a=>{this.manifests$.next([i,...a])},a=>this.params.output.error$.next({id:"ExtractHlsQualities",category:r.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:a})),this.params.output.isLive$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),this.maxSeekBackTime$=new r.ValueSubject((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:a}=this.params.desiredState,n=i.getState(),o=a.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:a.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d)return;const u=n?"master":l;return n&&!o&&a.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"HlsLiveProvider",category:r.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:l})},a=qe(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,i));n(a.ended$,e.endedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.isAudioAvailable$,e.isAudioAvailable$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Ue(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Qe(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(q.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(q.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.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()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(r.filterChanged(),r.map(l=>-l/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(a.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&&r.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(oe(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===q.CHANGING_MANIFEST&&this.videoState.setState(d.to),l&&l.state===O.Requested&&this.seek(l.position)},i)),this.subscription.add(a.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)},i)),this.subscription.add(r.combine({startTime:this.manifestStartTime$.pipe(r.filter(r.isNonNullable)),currentTime:a.timeUpdate$}).subscribe(({startTime:l,currentTime:d})=>this.params.output.liveTime$.next(l+d*1e3),i)),this.subscription.add(this.manifests$.pipe(r.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$,i));const o=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),He(this.video)}prepare(){const e=this.selectManifest();if(r.isNullable(e))return;const t=gt(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),Dr(t).then(i=>{var a;if(!r.isNullable(i))this.maxSeekBackTime$.next(i);else{const n=(a=this.params.source.maxSeekBackTime)!==null&&a!==void 0?a:this.maxSeekBackTime$.getValue();if(r.isNullable(n)||!isFinite(n))try{yt(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();Dr(u).then(c=>{r.isNullable(c)||this.maxSeekBackTime$.next(c)})}})}catch(o){}}})}playIfAllowed(){Je(this.video).then(e=>{e||(this.videoState.setState(q.PAUSED),this.liveOffset.pause(),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}var z;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(z||(z={}));class fm{constructor(e){this.subscription=new r.Subscription,this.videoState=new Q(z.STOPPED),this.textTracksManager=new Re,this.manifests$=new r.ValueSubject([]),this.syncPlayback=()=>{const i=this.videoState.getState(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a===exports.PlaybackState.STOPPED){i!==z.STOPPED&&(this.videoState.startTransitionTo(z.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(z.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.seekState.getState();if(i===z.STOPPED){this.videoState.startTransitionTo(z.READY),this.prepare();return}if(o||l){const c=this.videoState.getState();this.videoState.setState(z.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),u.state===O.None&&this.params.desiredState.seekState.setState({state:O.Requested,position:h*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&u.state===O.Requested&&this.seek(u.position),i){case z.READY:a===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):a===exports.PlaybackState.PAUSED?(this.videoState.setState(z.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):a===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed());return;case z.PLAYING:a===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(z.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case z.PAUSED:a===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case z.CHANGING_MANIFEST:break;default:return r.assertNever(i)}},this.params=e,this.video=je(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.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),Jn(this.params.source.url).then(i=>{this.manifests$.next([t,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:r.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:a}=this.params.desiredState,n=i.getState(),o=a.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:a.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d)return;const u=n?"master":l;return n&&!o&&a.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"HlsProvider",category:r.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:l})},a=qe(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.seeked$,e.seekedEvent$),n(a.isAudioAvailable$,e.isAudioAvailable$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(Ue(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Qe(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(z.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.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()},i).add(a.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&&r.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(oe(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===z.CHANGING_MANIFEST&&this.videoState.setState(d.to),l.state===O.Requested&&this.seek(l.position)},i))),this.subscription.add(this.manifests$.pipe(r.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$,i));const o=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),He(this.video)}prepare(){const e=this.selectManifest();r.isNullable(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){Je(this.video).then(e=>{e||(this.videoState.setState(z.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var K;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(K||(K={}));class pm{constructor(e){this.subscription=new r.Subscription,this.videoState=new Q(K.STOPPED),this.trackUrls={},this.textTracksManager=new Re,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition();if(i===exports.PlaybackState.STOPPED){t!==K.STOPPED&&(this.videoState.startTransitionTo(K.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(K.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===K.STOPPED){this.videoState.startTransitionTo(K.READY),this.prepare();return}if(o){const{currentTime:d}=this.video;this.prepare(),l.state===O.None&&this.params.desiredState.seekState.setState({state:O.Requested,position:d*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&l.state===O.Requested&&this.seek(l.position),t){case K.READY:i===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(K.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed());return;case K.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(K.PAUSED),this.video.pause()):(a==null?void 0:a.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case K.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(t)}},this.params=e,this.video=je(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach(([t,i],a)=>{const n=a.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"MpegProvider",category:r.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:l})},a=qe(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,i));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.seeked$,e.seekedEvent$),n(a.isAudioAvailable$,e.isAudioAvailable$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(ot(this.video,t.isLooped,i)),this.subscription.add(Ue(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Qe(this.video,t.playbackRate,a.playbackRateState$,i)),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(K.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(K.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===K.READY&&this.videoState.setState(K.READY);const d=this.params.desiredState.videoTrack.getTransition();d&&r.isNonNullable(d.to)&&(this.params.desiredState.videoTrack.setState(d.to),this.params.output.currentVideoTrack$.next(this.trackUrls[d.to].track)),this.videoState.getState()===K.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const o=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),He(this.video)}prepare(){var e,t;const i=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState();r.assertNonNullable(i,"MpegProvider: track is not selected");let{url:a}=this.trackUrls[i];r.assertNonNullable(a,`MpegProvider: No url for ${i}`),this.params.tuning.requestQuick&&(a=Tt(a)),this.video.setAttribute("src",a),this.video.load(),this.params.output.hostname$.next(oe(a))}playIfAllowed(){Je(this.video).then(e=>{e||(this.videoState.setState(K.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}const Cr=["stun:videostun.mycdn.me:80"],mm=1e3,bm=3,gs=()=>null;class vm{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=gs,this.externalStopCallback=gs,this.externalErrorCallback=gs,this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:Cr}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:r.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),mm)}normalizeOptions(e={}){const t={stunServerList:Cr,maxRetryNumber:bm,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var Y;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Y||(Y={}));class Sm{constructor(e){this.videoState=new Q(Y.STOPPED),this.maxSeekBackTime$=new r.ValueSubject(0),this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition();if(i===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:i===exports.PlaybackState.PAUSED?(this.videoState.setState(Y.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed());return;case Y.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Y.PAUSED),this.video.pause()):(a==null?void 0:a.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Y.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(t)}},this.subscription=new r.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=je(e.container),this.liveStreamClient=new vm(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),He(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"WebRTCLiveProvider",category:r.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};r.merge(this.videoState.stateChangeStarted$.pipe(r.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:l})=>{this.log({message:`[videoState change] ${l}: ${JSON.stringify(o)}`})});const a=qe(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,i));n(a.timeUpdate$,e.liveTime$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(a.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===Y.READY&&this.videoState.setState(Y.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED)},i)).add(a.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING)},i)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ue(this.video,t.volume,a.volumeState$,i)).add(a.volumeState$.subscribe(e.volume$,i)).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 r.assertNever(o.to)}},i)).add(r.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality: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:r.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Je(this.video).then(e=>{e||(this.videoState.setState(Y.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class Lr{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 gm=()=>{var s,e;const t=window.navigator;return t.userAgentData?((e=(s=t.userAgentData)===null||s===void 0?void 0:s.platform)===null||e===void 0?void 0:e.toLowerCase())==="android":window.navigator.userAgent.toLowerCase().includes("android")},ys,Ts,Es,$s,ks,Ps,ui,As,di,ws,ci,_s,hi,Rs,fi,Is,pi,Ns;const Kn=gm(),ze=document.createElement("video"),ym='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Tm='video/mp4; codecs="hev1.1.6.L93.B0"',Xn='video/webm; codecs="vp09.00.10.08"',Zn='video/webm; codecs="av01.0.00M.08"',Em='audio/mp4; codecs="mp4a.40.2"',$m='audio/webm; codecs="opus"',ve={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&((Ts=(ys=window.SourceBuffer)===null||ys===void 0?void 0:ys.prototype)===null||Ts===void 0?void 0:Ts.appendBuffer)),hls:Boolean(((Es=ze.canPlayType)===null||Es===void 0?void 0:Es.call(ze,"application/x-mpegurl"))||(($s=ze.canPlayType)===null||$s===void 0?void 0:$s.call(ze,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection),ws:Boolean(window.WebSocket)},de={mp4:Boolean((ks=ze.canPlayType)===null||ks===void 0?void 0:ks.call(ze,"video/mp4")),webm:Boolean((Ps=ze.canPlayType)===null||Ps===void 0?void 0:Ps.call(ze,"video/webm")),cmaf:!0},we={h264:Boolean((As=(ui=window.MediaSource)===null||ui===void 0?void 0:ui.isTypeSupported)===null||As===void 0?void 0:As.call(ui,ym)),h265:Boolean((ws=(di=window.MediaSource)===null||di===void 0?void 0:di.isTypeSupported)===null||ws===void 0?void 0:ws.call(di,Tm)),vp9:Boolean((_s=(ci=window.MediaSource)===null||ci===void 0?void 0:ci.isTypeSupported)===null||_s===void 0?void 0:_s.call(ci,Xn)),av1:Boolean((Rs=(hi=window.MediaSource)===null||hi===void 0?void 0:hi.isTypeSupported)===null||Rs===void 0?void 0:Rs.call(hi,Zn)),aac:Boolean((Is=(fi=window.MediaSource)===null||fi===void 0?void 0:fi.isTypeSupported)===null||Is===void 0?void 0:Is.call(fi,Em)),opus:Boolean((Ns=(pi=window.MediaSource)===null||pi===void 0?void 0:pi.isTypeSupported)===null||Ns===void 0?void 0:Ns.call(pi,$m))},mt=(we.h264||we.h265)&&we.aac;var De;(function(s){s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient"})(De||(De={}));let tt;const km=async()=>{if(!window.navigator.mediaCapabilities)return;const s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:Zn}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:Xn}})]);tt={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}};try{km()}catch(s){console.error(s)}const Vi=ve.hls&&de.mp4,Pm=()=>Object.keys(we).filter(s=>we[s]),Am=(s,e=!1)=>s.filter(t=>{switch(t){case exports.VideoFormat.DASH:return ve.mse&&de.mp4&&mt;case exports.VideoFormat.DASH_SEP:return ve.mse&&de.mp4&&mt;case exports.VideoFormat.DASH_WEBM:return ve.mse&&de.webm&&we.vp9&&we.opus;case exports.VideoFormat.DASH_WEBM_AV1:return ve.mse&&de.webm&&we.av1&&we.opus;case exports.VideoFormat.DASH_LIVE:return ve.mse&&de.mp4&&mt;case exports.VideoFormat.DASH_LIVE_CMAF:return ve.mse&&de.mp4&&mt&&de.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return ve.mse&&de.mp4&&mt;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.HLS_ONDEMAND:return Vi||e&&ve.mse&&de.mp4&&mt;case exports.VideoFormat.MPEG:return de.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return ve.webrtc&&ve.ws&&we.h264&&(de.mp4||de.webm);default:return r.assertNever(t)}}),Ds=s=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(s){case De.VP9:return[e,t];case De.AV1:return[t,e];case De.NONE:return[];case De.SMOOTH:return tt?tt[t].smooth?[t,e]:tt[e].smooth?[e,t]:[t,e]:[e,t];case De.POWER_EFFICIENT:return tt?tt[t].powerEfficient?[t,e]:tt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:r.assertNever(s)}return[e,t]},wm=(s=De.VP9)=>Kn?[exports.VideoFormat.MPEG,...Ds(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND]:Vi?[...Ds(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[...Ds(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG],_m=()=>Kn?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF]:Vi?[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF]:[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],xr=s=>s?[exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_WEBM_AV1,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var Rm=s=>new r.Observable(e=>{const t=new r.Subscription,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(r.map(({from:u,to:c})=>`${u}-${c}`)),a=s.desiredPlaybackState$.stateChangeEnded$,n=s.providerChanged$.pipe(r.map(({type:u})=>u!==void 0)),o=new r.Subject;let l=0,d="unknown";return t.add(i.subscribe(u=>{l&&window.clearTimeout(l),d=u,l=window.setTimeout(()=>o.next(u),s.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(l),d="provider change",l=0})),t.add(n.subscribe(u=>{l&&window.clearTimeout(l),u&&(l=window.setTimeout(()=>o.next(d),s.maxTransitionInterval))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const Or={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},Im={cacheDuration:12e4},Nm={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Dm={maxPausedTime:3e4},Br={maxPausedTime:3e4};class Cm{constructor(e){this.current$=new r.ValueSubject({type:void 0}),this.providerError$=new r.Subject,this.noAvailableProvidersError$=new r.Subject,this.providerOutput={position$:new r.ValueSubject(0),duration$:new r.ValueSubject(1/0),volume$:new r.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new r.ValueSubject(void 0),availableVideoTracks$:new r.ValueSubject([]),availableAudioTracks$:new r.ValueSubject([]),isAudioAvailable$:new r.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new r.ValueSubject(!1),currentBuffer$:new r.ValueSubject(void 0),isBuffering$:new r.ValueSubject(!0),error$:new r.Subject,willSeekEvent$:new r.Subject,seekedEvent$:new r.Subject,loopedEvent$:new r.Subject,endedEvent$:new r.Subject,firstBytesEvent$:new r.Subject,firstFrameEvent$:new r.Subject,canplay$:new r.Subject,isLive$:new r.ValueSubject(void 0),liveTime$:new r.ValueSubject(void 0),availableTextTracks$:new r.ValueSubject([]),currentTextTrack$:new r.ValueSubject(void 0),hostname$:new r.ValueSubject(void 0),httpConnectionType$:new r.ValueSubject(void 0),httpConnectionReused$:new r.ValueSubject(void 0),inPiP$:new r.ValueSubject(!1),inFullscreen$:new r.ValueSubject(!1),element$:new r.ValueSubject(void 0)},this.subscription=new r.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Am([..._m(),...wm(this.params.tuning.webmCodec)],this.params.tuning.useHlsJs).filter(l=>r.isNonNullable(e.sources[l])),{forceFormat:i,formatsToAvoid:a}=this.params.tuning;let n=[];i?n=[i]:a.length?n=[...t.filter(l=>!a.includes(l)),...t.filter(l=>a.includes(l))]:n=t,this.screenFormatsIterator=new Lr(n);const o=[...xr(!0),...xr(!1)];this.chromecastFormatsIterator=new Lr(o.filter(l=>r.isNonNullable(e.sources[l])))}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(r.isNullable(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:r.ErrorCategory.WTF,message:"Failed to create provider",thrown:a})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),a=i.state!==O.None;this.params.desiredState.seekState.setState({state:O.Requested,position:a?i.position:t,forcePrecise:a?i.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 re.SCREEN:return this.createScreenProvider(t);case re.CHROMECAST:return this.createChromecastProvider(t);default:return r.assertNever(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:a}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Zf({...o,source:l,config:Im})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.DASH_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),this.params.tuning.useDashJs?new Sr({...o,source:l,format:e,config:Br}):new lm({...o,source:l})}case exports.VideoFormat.DASH_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Sr({...o,source:l,format:e,config:Br})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),Vi||!this.params.tuning.useHlsJs?new fm({...o,source:l}):new dm({...o,source:l})}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new hm({...o,source:l,config:Dm})}case exports.VideoFormat.MPEG:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new pm({...o,source:l})}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Wf({...o,source:l,config:Nm})}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Sm({container:i,source:l,desiredState:a,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 r.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:a,meta:n}=this.params,o=this.providerOutput,l=this.params.dependencies.chromecastInitializer.connection$.getValue();return r.assertNonNullable(l),new Kh({connection:l,meta:n,container:i,source:t,format:e,desiredState:a,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?re.CHROMECAST:re.SCREEN}chooseFormat(e){switch(e){case re.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case re.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return r.assertNever(e)}}skipFormat(e){switch(e){case re.SCREEN:return this.screenFormatsIterator.next();case re.CHROMECAST:return this.chromecastFormatsIterator.next();default:return r.assertNever(e)}}handleNoFormatsError(e){switch(e){case re.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case re.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return r.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=a=>{const n=new URL(a);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{...e,url:i(e.url)}}return Yt(Object.entries(e).map(([a,n])=>[a,i(n)]))}initProviderErrorHandling(){const e=new r.Subscription;let t=!1,i=0;return e.add(r.merge(this.providerOutput.error$,Rm({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:Or.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(r.map(a=>({id:`ProviderHangup:${a}`,category:r.ErrorCategory.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const a=this.params.desiredState.playbackState.transitionEnded$.pipe(r.filter(({to:n})=>n===exports.PlaybackState.PLAYING),r.once()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{const n=this.current$.getValue().destination;if(n===re.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(re.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const o=a.category===r.ErrorCategory.NETWORK,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<Or.providerErrorLimit;l&&(o&&t||!d)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(i++,this.reinitProvider()):this.switchToNextProvider(n!=null?n:re.SCREEN)}})),e}}const Ys=(s,e,t)=>t*e+(1-t)*s,eo=(s,e)=>s.reduce((t,i)=>t+i,0)/e,Lm=(s,e,t,i)=>{let a=0,n=t;const o=eo(s,e),l=e<i?e:i;for(let d=0;d<l;d++)s[n]>o?a++:a--,n=(s.length+n-1)%s.length;return Math.abs(a)===l};class to{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new r.ValueSubject(e.initial),this.debounced$=new r.ValueSubject(e.initial);const i=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ae(`raw_${i}`),this.smoothedSeries$=new Ae(`smoothed_${i}`),this.reportedSeries$=new Ae(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let l=0;l<this.pastMeasures.length;l++)this.pastMeasures[l]!==void 0&&(t+=(this.pastMeasures[l]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const a=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*a,o=this.smoothed-this.params.deviationFactor*a;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>n||this.smoothed<o)&&(r.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))}}class xm extends to{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ys(this.slow,e,this.params.emaAlphaSlow),this.fast=Ys(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Om extends to{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=eo(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ys(this.emaSmoothed,e,this.params.emaAlpha);const i=Lm(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class Mr{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new xm({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Om({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}}const Bm=5e3,Vr="one_video_throughput",Fr="one_video_rtt",Oe=window.navigator.connection,Ur=()=>{const s=Oe==null?void 0:Oe.downlink;if(r.isNonNullable(s)&&s!==10)return s*1e3},jr=()=>{const s=Oe==null?void 0:Oe.rtt;if(r.isNonNullable(s)&&s!==3e3)return s},Hr=(s,e,t)=>{const i=t*8,a=i/s;return i/(a+e)};class Ft{constructor(e){var t,i;this.subscription=new r.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const a=Ft.load(Vr)||(e.useBrowserEstimation?Ur():void 0)||Bm,n=(i=(t=Ft.load(Fr))!==null&&t!==void 0?t:e.useBrowserEstimation?jr():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new r.ValueSubject(a),this.rtt$=new r.ValueSubject(n),this.rttAdjustedThroughput$=new r.ValueSubject(Hr(a,n,e.rttPenaltyRequestSize)),this.throughput=Mr.getSmoothedValue(a,-1,e),this.rtt=Mr.getSmoothedValue(n,1,e),e.useBrowserEstimation){const o=()=>{const d=Ur();d&&this.throughput.next(d);const u=jr();r.isNonNullable(u)&&this.rtt.next(u)};Oe&&"onchange"in Oe&&this.subscription.add(r.fromEvent(Oe,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{r.safeStorage.set(Vr,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{r.safeStorage.set(Fr,o.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(r.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(r.map(({throughput:o,rtt:l})=>Hr(o,l,e.rttPenaltyRequestSize)),r.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,i=r.now();const a=new r.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(r.fromEvent(e,"progress").pipe(r.once()).subscribe(n=>{t=n.loaded,i=r.now()}));break;case 1:case 0:a.add(r.fromEvent(e,"loadstart").subscribe(()=>{t=0,i=r.now()}));break}a.add(r.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,l=r.now(),d=o-t,u=l-i;this.addRawSpeed(d,u,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let i=0;const a=r.now();let n=0,o=r.now();const l=u=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${u}`).catch(()=>{})},d=async({done:u,value:c})=>{u?(this.addRawSpeed(i,r.now()-a,1),this.concurrentDownloads.delete(e)):c&&(i+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&r.now()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,r.now()-o,this.concurrentDownloads.size),n=0,o=r.now()),await(t==null?void 0:t.read().then(d,l)))};this.concurrentDownloads.add(e),t==null||t.read().then(d,l)}addRawSpeed(e,t,i=1){if(Ft.sanityCheck(e,t)){const a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||e<10*1024||t<=20)}static load(e){var t;const i=r.safeStorage.get(e);if(r.isNonNullable(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const qr={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,webmCodec:De.VP9,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useHlsJs:!0,isAudioDisabled:!1,webrtc:{connectionRetryMaxNumber:3}},Mm=s=>{const e={};for(const t of Object.keys(qr)){const i=qr[t],a=s[t];Array.isArray(i)&&Array.isArray(a)?t==="configName"?e[t]=[...a,...i]:e[t]=a:typeof i=="object"&&typeof a=="object"?e[t]={...i,...a}:e[t]=a!=null?a:i}return e};var Vm=({seekState:s,position$:e})=>r.merge(s.stateChangeEnded$.pipe(r.map(({to:t})=>{var i;return t.state===O.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),r.filter(r.isNonNullable)),e.pipe(r.filter(()=>s.getState().state===O.None))),Fm=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return r.assertNonNullable(e,`Wrong container or containerId {${s.container}}`),e};class Um{constructor(e={configName:[]}){if(this.subscription=new r.Subscription,this.logger=new r.Logger,this.isPlaybackStarted=!1,this.desiredState={playbackState:new Q(exports.PlaybackState.STOPPED),seekState:new Q({state:O.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([]),internalTextTracks:new Q([]),currentTextTrack:new Q(void 0),textTrackCuesSettings:new Q({})},this.info={playbackState$:new r.ValueSubject(exports.PlaybackState.STOPPED),position$:new r.ValueSubject(0),duration$:new r.ValueSubject(1/0),muted$:new r.ValueSubject(!1),volume$:new r.ValueSubject(1),availableQualities$:new r.ValueSubject([]),availableQualitiesFps$:new r.ValueSubject({}),availableAudioTracks$:new r.ValueSubject([]),isAudioAvailable$:new r.ValueSubject(!0),currentQuality$:new r.ValueSubject(void 0),isAutoQualityEnabled$:new r.ValueSubject(!0),autoQualityLimitingAvailable$:new r.ValueSubject(!1),autoQualityLimits$:new r.ValueSubject({}),currentPlaybackRate$:new r.ValueSubject(1),currentBuffer$:new r.ValueSubject({start:0,end:0}),isBuffering$:new r.ValueSubject(!0),isStalled$:new r.ValueSubject(!1),isEnded$:new r.ValueSubject(!1),isLooped$:new r.ValueSubject(!1),isLive$:new r.ValueSubject(void 0),atLiveEdge$:new r.ValueSubject(void 0),liveTime$:new r.ValueSubject(void 0),currentFormat$:new r.ValueSubject(void 0),availableTextTracks$:new r.ValueSubject([]),currentTextTrack$:new r.ValueSubject(void 0),throughputEstimation$:new r.ValueSubject(void 0),rttEstimation$:new r.ValueSubject(void 0),videoBitrate$:new r.ValueSubject(void 0),hostname$:new r.ValueSubject(void 0),httpConnectionType$:new r.ValueSubject(void 0),httpConnectionReused$:new r.ValueSubject(void 0),surface$:new r.ValueSubject(exports.Surface.NONE),chromecastState$:new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new r.ValueSubject(void 0),intrinsicVideoSize$:new r.ValueSubject(void 0)},this.events={inited$:new r.Subject,ready$:new r.Subject,started$:new r.Subject,playing$:new r.Subject,paused$:new r.Subject,stopped$:new r.Subject,willStart$:new r.Subject,willResume$:new r.Subject,willPause$:new r.Subject,willStop$:new r.Subject,willDestruct$:new r.Subject,watchCoverageRecord$:new r.Subject,watchCoverageLive$:new r.Subject,managedError$:new r.Subject,fatalError$:new r.Subject,ended$:new r.Subject,looped$:new r.Subject,seeked$:new r.Subject,willSeek$:new r.Subject,firstBytes$:new r.Subject,firstFrame$:new r.Subject,canplay$:new r.Subject,log$:new r.Subject},this.experimental={element$:new r.ValueSubject(void 0),tuningConfigName$:new r.ValueSubject([]),enableDebugTelemetry$:new r.ValueSubject(!1),dumpTelemetry:wf},this.initLogs(),this.tuning=Mm(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new wo({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Ft(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,a)=>{const n=Reflect.get(t,i,a);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 b=typeof p;return["number","string","boolean"].includes(b)?p:p===null?null:`<${b}>`})),u=`Player.${String(i)}`,c=`Exception calling ${u} (${d.join(", ")})`;throw this.events.fatalError$.next({id:u,category:r.ErrorCategory.WTF,message:c,thrown:l}),l}}}})}initVideo(e){var t,i,a;return this.config=e,this.domContainer=Fm(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Cm({sources:e.sources,meta:(i=e.meta)!==null&&i!==void 0?i:{},failoverHosts:(a=e.failoverHosts)!==null&&a!==void 0?a:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===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:O.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){r.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const i=t.find(a=>a.quality===e);return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.setState(e),this}setPlaybackRate(e){var t;r.assertNonNullable(this.providerContainer);const i=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return i&&(this.desiredState.playbackRate.setState(e),i.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return(e===void 0||!((t=this.providerContainer)===null||t===void 0)&&t.providerOutput.availableTextTracks$.getValue().find(i=>i.id===e))&&this.desiredState.currentTextTrack.startTransitionTo(e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){r.assertNonNullable(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(r.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===O.None?void 0:t.position;return r.isNonNullable(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}setIntrinsicVideoSize(...e){const t={width:e.reduce((i,{width:a})=>i||a||0,0),height:e.reduce((i,{height:a})=>i||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(r.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(r.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(r.filter(({from:e})=>e===exports.PlaybackState.STOPPED),r.once()).subscribe(()=>{this.initedAt=r.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case exports.PlaybackState.READY:this.events.ready$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case exports.PlaybackState.PAUSED:this.events.paused$.next();break;case exports.PlaybackState.STOPPED:this.events.stopped$.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.events.willStart$.next();break;case exports.PlaybackState.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const o=this.desiredState.seekState.getState();o.state===O.Requested?this.desiredState.seekState.setState({...o,state:O.Applying}):this.events.managedError$.next({id:`WillSeekIn${o.state}`,category:r.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===O.Applying&&(this.desiredState.seekState.setState({state:O.None}),this.events.seeked$.next())})).add(e.current$.pipe(r.map(o=>o.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(r.map(o=>o.destination),r.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(r.map(o=>o.map(({quality:l})=>l).sort((l,d)=>ki(l)?1:ki(d)?-1:Si(d,l)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(o=>{const l={};for(const d of o)d.fps&&(l[d.quality]=d.fps);this.info.availableQualitiesFps$.next(l)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{this.info.currentQuality$.next(o==null?void 0:o.quality),this.info.videoBitrate$.next(o==null?void 0:o.bitrate)})).add(e.providerOutput.hostname$.pipe(r.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(r.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(r.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(r.map(o=>o?{start:o.from,end:o.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(r.combine({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$}).pipe(r.map(({isLive:o,position:l})=>o&&l>-r.ACTIVE_LIVE_VALID_DELAY),r.filterChanged()).subscribe(this.info.atLiveEdge$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(r.map(o=>o.muted),r.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(r.map(o=>o.volume),r.filterChanged()).subscribe(this.info.volume$)).add(Vm({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(r.merge(e.providerOutput.endedEvent$.pipe(r.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(r.mapTo(!1))).pipe(r.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(r.map(o=>({id:o?`No${o}`:"NoProviders",category:r.ErrorCategory.VIDEO_PIPELINE,message:o?`${o} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(r.once(),r.map(o=>o!=null?o:r.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(r.once(),r.map(()=>r.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(r.once(),r.map(()=>r.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 r.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new r.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(r.filter(({to:o})=>o===exports.PlaybackState.PLAYING),r.once()).subscribe(()=>i.next(!1)));let a=0;const n=r.merge(e.providerOutput.isBuffering$,t,i).pipe(r.map(()=>{const o=e.providerOutput.isBuffering$.getValue(),l=t.getValue()||i.getValue();return o&&!l}),r.filterChanged());this.subscription.add(n.subscribe(o=>{o?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add(r.merge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{var l,d;const u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(l=o==null?void 0:o.size)===null||l===void 0?void 0:l.width,height:(d=o==null?void 0:o.size)===null||d===void 0?void 0:d.height},{width:u==null?void 0:u.videoWidth,height:u==null?void 0:u.videoHeight})})),this.subscription.add(r.merge(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const o=e.providerOutput.inPiP$.getValue(),l=e.providerOutput.inFullscreen$.getValue(),d=e.providerOutput.element$.getValue(),u=this.chromecastInitializer.castState$.getValue();let c;u===exports.ChromecastState.CONNECTED?c=exports.Surface.SECOND_SCREEN:d?o?c=exports.Surface.PIP:l?c=exports.Surface.FULLSCREEN:c=exports.Surface.INLINE:c=exports.Surface.NONE,this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(r.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 r.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(r.filterChanged((i,a)=>i.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(r.filter(i=>i.length>0),r.once()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:i})=>i===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=Gt(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(r.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(r.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;r.assertNonNullable(this.providerContainer),r.assertNonNullable(t),Af(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Pf(i)),this.providerContainer.current$.subscribe(({type:i})=>ni("provider",i)),t.duration$.subscribe(i=>ni("duration",i)),t.availableVideoTracks$.pipe(r.filter(i=>!!i.length),r.once()).subscribe(i=>ni("tracks",i)),this.events.fatalError$.subscribe(new Ae("fatalError")),this.events.managedError$.subscribe(new Ae("managedError")),t.position$.subscribe(new Ae("position")),t.currentVideoTrack$.pipe(r.map(i=>i==null?void 0:i.quality)).subscribe(new Ae("quality")),this.info.currentBuffer$.subscribe(new Ae("buffer")),t.isBuffering$.subscribe(new Ae("isBuffering"))].forEach(i=>this.subscription.add(i)),ni("codecs",Pm())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:r.ErrorCategory.DOM,message:String(a)})})};this.subscription.add(r.merge(r.fromEvent(document,"visibilitychange"),r.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const a=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=Boolean(e)&&!(e!=null&&e.released);a&&n?o||i():t()})).add(this.events.willDestruct$.subscribe(t))}}const jm=`@vkontakte/videoplayer-core@${Yr}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return r.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return r.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return r.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return r.ValueSubject}});exports.Player=Um;exports.SDK_VERSION=jm;exports.VERSION=Yr;
6
+ "use strict";var po=Object.create;var pa=Object.defineProperty;var mo=Object.getOwnPropertyDescriptor;var bo=Object.getOwnPropertyNames;var vo=Object.getPrototypeOf,So=Object.prototype.hasOwnProperty;var go=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of bo(e))!So.call(s,a)&&a!==t&&pa(s,a,{get:()=>e[a],enumerable:!(i=mo(e,a))||i.enumerable});return s};var ma=(s,e,t)=>(t=s!=null?po(vo(s)):{},go(e||!s||!s.__esModule?pa(t,"default",{value:s,enumerable:!0}):t,s));var r=require("@vkontakte/videoplayer-shared/es2018.cjs.js"),yo=require("lodash/debounce.js");const Fr="2.0.88";exports.PlaybackState=void 0;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(s){s.MPEG="MPEG",s.DASH="DASH",s.DASH_SEP="DASH_SEP",s.DASH_SEP_VK="DASH_SEP",s.DASH_WEBM="DASH_WEBM",s.DASH_WEBM_AV1="DASH_WEBM_AV1",s.DASH_WEBM_VK="DASH_WEBM",s.DASH_ONDEMAND="DASH_ONDEMAND",s.DASH_ONDEMAND_VK="DASH_ONDEMAND",s.DASH_LIVE="DASH_LIVE",s.DASH_LIVE_CMAF="DASH_LIVE_CMAF",s.DASH_LIVE_WEBM="DASH_LIVE_WEBM",s.HLS="HLS",s.HLS_ONDEMAND="HLS_ONDEMAND",s.HLS_JS="HLS",s.HLS_LIVE="HLS_LIVE",s.HLS_LIVE_CMAF="HLS_LIVE_CMAF",s.WEB_RTC_LIVE="WEB_RTC_LIVE"})(exports.VideoFormat||(exports.VideoFormat={}));var re;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(re||(re={}));exports.ChromecastState=void 0;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var O;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(O||(O={}));exports.Surface=void 0;(function(s){s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip"})(exports.Surface||(exports.Surface={}));var To=s=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class Eo{constructor(e){var t;this.connection$=new r.ValueSubject(void 0),this.castState$=new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new r.Subject,this.realCastState$=new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new r.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const i="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${i}`}),e.isDisabled||!i)return;const a=r.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=Boolean(window.__onGCastApiAvailable);a?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||To("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:r.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 i,a,n;(n=(a=(i=cast.framework.CastContext.getInstance())===null||i===void 0?void 0:i.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0||n.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){r.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();r.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();r.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),i=cast.framework.CastContext.getInstance();this.subscription.add(r.fromEvent(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{var n,o;switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=i.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 r.assertNever(a.sessionState)}})).add(r.merge(r.fromEvent(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(r.tap(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),r.map(a=>a.castState)),r.observableFrom([i.getCastState()])).pipe(r.filterChanged(),r.map($o),r.tap(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{var n;const o=a===exports.ChromecastState.CONNECTED,l=r.isNonNullable(this.connection$.getValue());if(o&&!l){const d=i.getCurrentSession();r.assertNonNullable(d);const u=d.getCastDevice(),c=(n=d.getMediaSession())===null||n===void 0?void 0:n.media.contentId;(r.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(a===exports.ChromecastState.CONNECTED?r.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:a)}))}initializeCastApi(){var e;let t,i,a;try{t=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,a=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:i,autoJoinPolicy:a}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:r.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const $o=s=>{switch(s){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 r.assertNever(s)}};var ba=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},xe=function(s){try{return!!s()}catch(e){return!0}},ko=xe,Pi=!ko(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),Ur=Pi,jr=Function.prototype,ws=jr.call,Po=Ur&&jr.bind.bind(ws,ws),Oe=Ur?Po:function(s){return function(){return ws.apply(s,arguments)}},Hr=Oe,Ao=Hr({}.toString),wo=Hr("".slice),Ai=function(s){return wo(Ao(s),8,-1)},_o=Oe,Ro=xe,Io=Ai,Ui=Object,Do=_o("".split),No=Ro(function(){return!Ui("z").propertyIsEnumerable(0)})?function(s){return Io(s)=="String"?Do(s,""):Ui(s)}:Ui,wi=function(s){return s==null},Co=wi,Lo=TypeError,Fs=function(s){if(Co(s))throw Lo("Can't call method on "+s);return s},xo=No,Oo=Fs,Vt=function(s){return xo(Oo(s))},Bo=function(){},Tt={},Qt=function(s){return s&&s.Math==Math&&s},Ae=Qt(typeof globalThis=="object"&&globalThis)||Qt(typeof window=="object"&&window)||Qt(typeof self=="object"&&self)||Qt(typeof ba=="object"&&ba)||function(){return this}()||Function("return this")(),_s=typeof document=="object"&&document.all,Mo=typeof _s=="undefined"&&_s!==void 0,qr={all:_s,IS_HTMLDDA:Mo},Yr=qr,Vo=Yr.all,he=Yr.IS_HTMLDDA?function(s){return typeof s=="function"||s===Vo}:function(s){return typeof s=="function"},Fo=Ae,Uo=he,va=Fo.WeakMap,jo=Uo(va)&&/native code/.test(String(va)),Sa=he,Gr=qr,Ho=Gr.all,st=Gr.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:Sa(s)||s===Ho}:function(s){return typeof s=="object"?s!==null:Sa(s)},qo=xe,Ge=!qo(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Et={},Yo=Ae,ga=st,Rs=Yo.document,Go=ga(Rs)&&ga(Rs.createElement),zr=function(s){return Go?Rs.createElement(s):{}},zo=Ge,Wo=xe,Qo=zr,Wr=!zo&&!Wo(function(){return Object.defineProperty(Qo("div"),"a",{get:function(){return 7}}).a!=7}),Jo=Ge,Ko=xe,Qr=Jo&&Ko(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Xo=st,Zo=String,el=TypeError,at=function(s){if(Xo(s))return s;throw el(Zo(s)+" is not an object")},tl=Pi,Jt=Function.prototype.call,Be=tl?Jt.bind(Jt):function(){return Jt.apply(Jt,arguments)},Us={},ji=Us,Hi=Ae,il=he,ya=function(s){return il(s)?s:void 0},js=function(s,e){return arguments.length<2?ya(ji[s])||ya(Hi[s]):ji[s]&&ji[s][e]||Hi[s]&&Hi[s][e]},sl=Oe,Hs=sl({}.isPrototypeOf),al=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Jr=Ae,qi=al,Ta=Jr.process,Ea=Jr.Deno,$a=Ta&&Ta.versions||Ea&&Ea.version,ka=$a&&$a.v8,ve,bi;ka&&(ve=ka.split("."),bi=ve[0]>0&&ve[0]<4?1:+(ve[0]+ve[1]));!bi&&qi&&(ve=qi.match(/Edge\/(\d+)/),(!ve||ve[1]>=74)&&(ve=qi.match(/Chrome\/(\d+)/),ve&&(bi=+ve[1])));var rl=bi,Pa=rl,nl=xe,Kr=!!Object.getOwnPropertySymbols&&!nl(function(){var s=Symbol();return!String(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Pa&&Pa<41}),ol=Kr,Xr=ol&&!Symbol.sham&&typeof Symbol.iterator=="symbol",ll=js,ul=he,dl=Hs,cl=Xr,hl=Object,Zr=cl?function(s){return typeof s=="symbol"}:function(s){var e=ll("Symbol");return ul(e)&&dl(e.prototype,hl(s))},fl=String,qs=function(s){try{return fl(s)}catch(e){return"Object"}},pl=he,ml=qs,bl=TypeError,Ys=function(s){if(pl(s))return s;throw bl(ml(s)+" is not a function")},vl=Ys,Sl=wi,_i=function(s,e){var t=s[e];return Sl(t)?void 0:vl(t)},Yi=Be,Gi=he,zi=st,gl=TypeError,yl=function(s,e){var t,i;if(e==="string"&&Gi(t=s.toString)&&!zi(i=Yi(t,s))||Gi(t=s.valueOf)&&!zi(i=Yi(t,s))||e!=="string"&&Gi(t=s.toString)&&!zi(i=Yi(t,s)))return i;throw gl("Can't convert object to primitive value")},vi={},Tl={get exports(){return vi},set exports(s){vi=s}},El=!0,Aa=Ae,$l=Object.defineProperty,kl=function(s,e){try{$l(Aa,s,{value:e,configurable:!0,writable:!0})}catch(t){Aa[s]=e}return e},Pl=Ae,Al=kl,wa="__core-js_shared__",wl=Pl[wa]||Al(wa,{}),en=wl,_a=en;(Tl.exports=function(s,e){return _a[s]||(_a[s]=e!==void 0?e:{})})("versions",[]).push({version:"3.27.2",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.27.2/LICENSE",source:"https://github.com/zloirock/core-js"});var _l=Fs,Rl=Object,Ri=function(s){return Rl(_l(s))},Il=Oe,Dl=Ri,Nl=Il({}.hasOwnProperty),Me=Object.hasOwn||function(e,t){return Nl(Dl(e),t)},Cl=Oe,Ll=0,xl=Math.random(),Ol=Cl(1 .toString),tn=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Ol(++Ll+xl,36)},Bl=Ae,Ml=vi,Ra=Me,Vl=tn,Fl=Kr,Ul=Xr,pt=Bl.Symbol,Wi=Ml("wks"),jl=Ul?pt.for||pt:pt&&pt.withoutSetter||Vl,ge=function(s){return Ra(Wi,s)||(Wi[s]=Fl&&Ra(pt,s)?pt[s]:jl("Symbol."+s)),Wi[s]},Hl=Be,Ia=st,Da=Zr,ql=_i,Yl=yl,Gl=ge,zl=TypeError,Wl=Gl("toPrimitive"),Ql=function(s,e){if(!Ia(s)||Da(s))return s;var t=ql(s,Wl),i;if(t){if(e===void 0&&(e="default"),i=Hl(t,s,e),!Ia(i)||Da(i))return i;throw zl("Can't convert object to primitive value")}return e===void 0&&(e="number"),Yl(s,e)},Jl=Ql,Kl=Zr,Gs=function(s){var e=Jl(s,"string");return Kl(e)?e:e+""},Xl=Ge,Zl=Wr,eu=Qr,Kt=at,Na=Gs,tu=TypeError,Qi=Object.defineProperty,iu=Object.getOwnPropertyDescriptor,Ji="enumerable",Ki="configurable",Xi="writable";Et.f=Xl?eu?function(e,t,i){if(Kt(e),t=Na(t),Kt(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Xi in i&&!i[Xi]){var a=iu(e,t);a&&a[Xi]&&(e[t]=i.value,i={configurable:Ki in i?i[Ki]:a[Ki],enumerable:Ji in i?i[Ji]:a[Ji],writable:!1})}return Qi(e,t,i)}:Qi:function(e,t,i){if(Kt(e),t=Na(t),Kt(i),Zl)try{return Qi(e,t,i)}catch(a){}if("get"in i||"set"in i)throw tu("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Ii=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},su=Ge,au=Et,ru=Ii,Ft=su?function(s,e,t){return au.f(s,e,ru(1,t))}:function(s,e,t){return s[e]=t,s},nu=vi,ou=tn,Ca=nu("keys"),zs=function(s){return Ca[s]||(Ca[s]=ou(s))},Ws={},lu=jo,sn=Ae,uu=st,du=Ft,Zi=Me,es=en,cu=zs,hu=Ws,La="Object already initialized",Is=sn.TypeError,fu=sn.WeakMap,Si,Mt,gi,pu=function(s){return gi(s)?Mt(s):Si(s,{})},mu=function(s){return function(e){var t;if(!uu(e)||(t=Mt(e)).type!==s)throw Is("Incompatible receiver, "+s+" required");return t}};if(lu||es.state){var Ee=es.state||(es.state=new fu);Ee.get=Ee.get,Ee.has=Ee.has,Ee.set=Ee.set,Si=function(s,e){if(Ee.has(s))throw Is(La);return e.facade=s,Ee.set(s,e),e},Mt=function(s){return Ee.get(s)||{}},gi=function(s){return Ee.has(s)}}else{var ut=cu("state");hu[ut]=!0,Si=function(s,e){if(Zi(s,ut))throw Is(La);return e.facade=s,du(s,ut,e),e},Mt=function(s){return Zi(s,ut)?s[ut]:{}},gi=function(s){return Zi(s,ut)}}var bu={set:Si,get:Mt,has:gi,enforce:pu,getterFor:mu},vu=Pi,an=Function.prototype,xa=an.apply,Oa=an.call,Su=typeof Reflect=="object"&&Reflect.apply||(vu?Oa.bind(xa):function(){return Oa.apply(xa,arguments)}),gu=Ai,yu=Oe,rn=function(s){if(gu(s)==="Function")return yu(s)},nn={},on={},ln={}.propertyIsEnumerable,un=Object.getOwnPropertyDescriptor,Tu=un&&!ln.call({1:2},1);on.f=Tu?function(e){var t=un(this,e);return!!t&&t.enumerable}:ln;var Eu=Ge,$u=Be,ku=on,Pu=Ii,Au=Vt,wu=Gs,_u=Me,Ru=Wr,Ba=Object.getOwnPropertyDescriptor;nn.f=Eu?Ba:function(e,t){if(e=Au(e),t=wu(t),Ru)try{return Ba(e,t)}catch(i){}if(_u(e,t))return Pu(!$u(ku.f,e,t),e[t])};var Iu=xe,Du=he,Nu=/#|\.prototype\./,Ut=function(s,e){var t=Lu[Cu(s)];return t==Ou?!0:t==xu?!1:Du(e)?Iu(e):!!e},Cu=Ut.normalize=function(s){return String(s).replace(Nu,".").toLowerCase()},Lu=Ut.data={},xu=Ut.NATIVE="N",Ou=Ut.POLYFILL="P",Bu=Ut,Ma=rn,Mu=Ys,Vu=Pi,Fu=Ma(Ma.bind),dn=function(s,e){return Mu(s),e===void 0?s:Vu?Fu(s,e):function(){return s.apply(e,arguments)}},Xt=Ae,Uu=Su,ju=rn,Hu=he,qu=nn.f,Yu=Bu,dt=Us,Gu=dn,ct=Ft,Va=Me,zu=function(s){var e=function(t,i,a){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,a)}return Uu(s,this,arguments)};return e.prototype=s.prototype,e},Di=function(s,e){var t=s.target,i=s.global,a=s.stat,n=s.proto,o=i?Xt:a?Xt[t]:(Xt[t]||{}).prototype,l=i?dt:dt[t]||ct(dt,t,{})[t],d=l.prototype,u,c,h,f,p,b,S,g,m;for(f in e)u=Yu(i?f:t+(a?".":"#")+f,s.forced),c=!u&&o&&Va(o,f),b=l[f],c&&(s.dontCallGetSet?(m=qu(o,f),S=m&&m.value):S=o[f]),p=c&&S?S:e[f],!(c&&typeof b==typeof p)&&(s.bind&&c?g=Gu(p,Xt):s.wrap&&c?g=zu(p):n&&Hu(p)?g=ju(p):g=p,(s.sham||p&&p.sham||b&&b.sham)&&ct(g,"sham",!0),ct(l,f,g),n&&(h=t+"Prototype",Va(dt,h)||ct(dt,h,{}),ct(dt[h],f,p),s.real&&d&&(u||!d[f])&&ct(d,f,p)))},Ds=Ge,Wu=Me,cn=Function.prototype,Qu=Ds&&Object.getOwnPropertyDescriptor,Qs=Wu(cn,"name"),Ju=Qs&&function(){}.name==="something",Ku=Qs&&(!Ds||Ds&&Qu(cn,"name").configurable),Xu={EXISTS:Qs,PROPER:Ju,CONFIGURABLE:Ku},hn={},Zu=Math.ceil,ed=Math.floor,td=Math.trunc||function(e){var t=+e;return(t>0?ed:Zu)(t)},id=td,Js=function(s){var e=+s;return e!==e||e===0?0:id(e)},sd=Js,ad=Math.max,rd=Math.min,nd=function(s,e){var t=sd(s);return t<0?ad(t+e,0):rd(t,e)},od=Js,ld=Math.min,ud=function(s){return s>0?ld(od(s),9007199254740991):0},dd=ud,Ks=function(s){return dd(s.length)},cd=Vt,hd=nd,fd=Ks,Fa=function(s){return function(e,t,i){var a=cd(e),n=fd(a),o=hd(i,n),l;if(s&&t!=t){for(;n>o;)if(l=a[o++],l!=l)return!0}else for(;n>o;o++)if((s||o in a)&&a[o]===t)return s||o||0;return!s&&-1}},pd={includes:Fa(!0),indexOf:Fa(!1)},md=Oe,ts=Me,bd=Vt,vd=pd.indexOf,Sd=Ws,Ua=md([].push),gd=function(s,e){var t=bd(s),i=0,a=[],n;for(n in t)!ts(Sd,n)&&ts(t,n)&&Ua(a,n);for(;e.length>i;)ts(t,n=e[i++])&&(~vd(a,n)||Ua(a,n));return a},fn=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],yd=gd,Td=fn,Ed=Object.keys||function(e){return yd(e,Td)},$d=Ge,kd=Qr,Pd=Et,Ad=at,wd=Vt,_d=Ed;hn.f=$d&&!kd?Object.defineProperties:function(e,t){Ad(e);for(var i=wd(t),a=_d(t),n=a.length,o=0,l;n>o;)Pd.f(e,l=a[o++],i[l]);return e};var Rd=js,Id=Rd("document","documentElement"),Dd=at,Nd=hn,ja=fn,Cd=Ws,Ld=Id,xd=zr,Od=zs,Ha=">",qa="<",Ns="prototype",Cs="script",pn=Od("IE_PROTO"),is=function(){},mn=function(s){return qa+Cs+Ha+s+qa+"/"+Cs+Ha},Ya=function(s){s.write(mn("")),s.close();var e=s.parentWindow.Object;return s=null,e},Bd=function(){var s=xd("iframe"),e="java"+Cs+":",t;return s.style.display="none",Ld.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(mn("document.F=Object")),t.close(),t.F},Zt,hi=function(){try{Zt=new ActiveXObject("htmlfile")}catch(e){}hi=typeof document!="undefined"?document.domain&&Zt?Ya(Zt):Bd():Ya(Zt);for(var s=ja.length;s--;)delete hi[Ns][ja[s]];return hi()};Cd[pn]=!0;var bn=Object.create||function(e,t){var i;return e!==null?(is[Ns]=Dd(e),i=new is,is[Ns]=null,i[pn]=e):i=hi(),t===void 0?i:Nd.f(i,t)},Md=xe,Vd=!Md(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),Fd=Me,Ud=he,jd=Ri,Hd=zs,qd=Vd,Ga=Hd("IE_PROTO"),Ls=Object,Yd=Ls.prototype,vn=qd?Ls.getPrototypeOf:function(s){var e=jd(s);if(Fd(e,Ga))return e[Ga];var t=e.constructor;return Ud(t)&&e instanceof t?t.prototype:e instanceof Ls?Yd:null},Gd=Ft,Sn=function(s,e,t,i){return i&&i.enumerable?s[e]=t:Gd(s,e,t),s},zd=xe,Wd=he,Qd=st,Jd=bn,za=vn,Kd=Sn,Xd=ge,xs=Xd("iterator"),gn=!1,Ce,ss,as;[].keys&&(as=[].keys(),"next"in as?(ss=za(za(as)),ss!==Object.prototype&&(Ce=ss)):gn=!0);var Zd=!Qd(Ce)||zd(function(){var s={};return Ce[xs].call(s)!==s});Zd?Ce={}:Ce=Jd(Ce);Wd(Ce[xs])||Kd(Ce,xs,function(){return this});var yn={IteratorPrototype:Ce,BUGGY_SAFARI_ITERATORS:gn},ec=ge,tc=ec("toStringTag"),Tn={};Tn[tc]="z";var Xs=String(Tn)==="[object z]",ic=Xs,sc=he,fi=Ai,ac=ge,rc=ac("toStringTag"),nc=Object,oc=fi(function(){return arguments}())=="Arguments",lc=function(s,e){try{return s[e]}catch(t){}},Ni=ic?fi:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=lc(e=nc(s),rc))=="string"?t:oc?fi(e):(i=fi(e))=="Object"&&sc(e.callee)?"Arguments":i},uc=Xs,dc=Ni,cc=uc?{}.toString:function(){return"[object "+dc(this)+"]"},hc=Xs,fc=Et.f,pc=Ft,mc=Me,bc=cc,vc=ge,Wa=vc("toStringTag"),En=function(s,e,t,i){if(s){var a=t?s:s.prototype;mc(a,Wa)||fc(a,Wa,{configurable:!0,value:e}),i&&!hc&&pc(a,"toString",bc)}},Sc=yn.IteratorPrototype,gc=bn,yc=Ii,Tc=En,Ec=Tt,$c=function(){return this},kc=function(s,e,t,i){var a=e+" Iterator";return s.prototype=gc(Sc,{next:yc(+!i,t)}),Tc(s,a,!1,!0),Ec[a]=$c,s},Pc=Di,Ac=Be,$n=Xu,wc=kc,_c=vn,Rc=En,Qa=Sn,Ic=ge,Ja=Tt,kn=yn,Dc=$n.PROPER;$n.CONFIGURABLE;kn.IteratorPrototype;var ei=kn.BUGGY_SAFARI_ITERATORS,rs=Ic("iterator"),Ka="keys",ti="values",Xa="entries",Nc=function(){return this},Cc=function(s,e,t,i,a,n,o){wc(t,e,i);var l=function(m){if(m===a&&f)return f;if(!ei&&m in c)return c[m];switch(m){case Ka:return function(){return new t(this,m)};case ti:return function(){return new t(this,m)};case Xa:return function(){return new t(this,m)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=s.prototype,h=c[rs]||c["@@iterator"]||a&&c[a],f=!ei&&h||l(a),p=e=="Array"&&c.entries||h,b,S,g;if(p&&(b=_c(p.call(new s)),b!==Object.prototype&&b.next&&(Rc(b,d,!0,!0),Ja[d]=Nc)),Dc&&a==ti&&h&&h.name!==ti&&(u=!0,f=function(){return Ac(h,this)}),a)if(S={values:l(ti),keys:n?f:l(Ka),entries:l(Xa)},o)for(g in S)(ei||u||!(g in c))&&Qa(c,g,S[g]);else Pc({target:e,proto:!0,forced:ei||u},S);return o&&c[rs]!==f&&Qa(c,rs,f,{name:a}),Ja[e]=f,S},Lc=function(s,e){return{value:s,done:e}},xc=Vt,Zs=Bo,Za=Tt,Pn=bu,Oc=Et.f,Bc=Cc,ii=Lc,Mc=El,Vc=Ge,An="Array Iterator",Fc=Pn.set,Uc=Pn.getterFor(An);Bc(Array,"Array",function(s,e){Fc(this,{type:An,target:xc(s),index:0,kind:e})},function(){var s=Uc(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,ii(void 0,!0)):t=="keys"?ii(i,!1):t=="values"?ii(e[i],!1):ii([i,e[i]],!1)},"values");var er=Za.Arguments=Za.Array;Zs();Zs();Zs();if(!Mc&&Vc&&er.name!=="values")try{Oc(er,"name",{value:"values"})}catch(s){}var jc=ge,Hc=Tt,qc=jc("iterator"),Yc=Array.prototype,Gc=function(s){return s!==void 0&&(Hc.Array===s||Yc[qc]===s)},zc=Ni,tr=_i,Wc=wi,Qc=Tt,Jc=ge,Kc=Jc("iterator"),wn=function(s){if(!Wc(s))return tr(s,Kc)||tr(s,"@@iterator")||Qc[zc(s)]},Xc=Be,Zc=Ys,eh=at,th=qs,ih=wn,sh=TypeError,ah=function(s,e){var t=arguments.length<2?ih(s):e;if(Zc(t))return eh(Xc(t,s));throw sh(th(s)+" is not iterable")},rh=Be,ir=at,nh=_i,oh=function(s,e,t){var i,a;ir(s);try{if(i=nh(s,"return"),!i){if(e==="throw")throw t;return t}i=rh(i,s)}catch(n){a=!0,i=n}if(e==="throw")throw t;if(a)throw i;return ir(i),t},lh=dn,uh=Be,dh=at,ch=qs,hh=Gc,fh=Ks,sr=Hs,ph=ah,mh=wn,ar=oh,bh=TypeError,pi=function(s,e){this.stopped=s,this.result=e},rr=pi.prototype,vh=function(s,e,t){var i=t&&t.that,a=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),d=lh(e,i),u,c,h,f,p,b,S,g=function(v){return u&&ar(u,"normal",v),new pi(!0,v)},m=function(v){return a?(dh(v),l?d(v[0],v[1],g):d(v[0],v[1])):l?d(v,g):d(v)};if(n)u=s.iterator;else if(o)u=s;else{if(c=mh(s),!c)throw bh(ch(s)+" is not iterable");if(hh(c)){for(h=0,f=fh(s);f>h;h++)if(p=m(s[h]),p&&sr(rr,p))return p;return new pi(!1)}u=ph(s,c)}for(b=n?s.next:u.next;!(S=uh(b,u)).done;){try{p=m(S.value)}catch(v){ar(u,"throw",v)}if(typeof p=="object"&&p&&sr(rr,p))return p}return new pi(!1)},Sh=Gs,gh=Et,yh=Ii,Th=function(s,e,t){var i=Sh(e);i in s?gh.f(s,i,yh(0,t)):s[i]=t},Eh=Di,$h=vh,kh=Th;Eh({target:"Object",stat:!0},{fromEntries:function(e){var t={};return $h(e,function(i,a){kh(t,i,a)},{AS_ENTRIES:!0}),t}});var Ph=Us,Ah=Ph.Object.fromEntries,wh={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},_h=wh,Rh=Ae,Ih=Ni,Dh=Ft,nr=Tt,Nh=ge,or=Nh("toStringTag");for(var ns in _h){var lr=Rh[ns],os=lr&&lr.prototype;os&&Ih(os)!==or&&Dh(os,or,ns),nr[ns]=nr.Array}var Ch=Ah,Lh=Ch,xh=Lh,Oh=xh,jt=Oh,bt;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(bt||(bt={}));var vt=(s,e=0,t=bt.OFFSET_P)=>{switch(t){case bt.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case bt.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}default:r.assertNever(t)}return s},P=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};class Q{constructor(e){this.transitionStarted$=new r.Subject,this.transitionEnded$=new r.Subject,this.transitionUpdated$=new r.Subject,this.forceChanged$=new r.Subject,this.stateChangeStarted$=r.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=r.merge(this.transitionEnded$,this.forceChanged$),this.state=e}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||r.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:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}const Bh=s=>{switch(s){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.DASH_WEBM_AV1:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_CMAF:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return r.assertNever(s)}};var C;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(C||(C={}));const Mh=5,Vh=5,Fh=500,ur=7e3;class Uh{constructor(e){this.subscription=new r.Subscription,this.loadMediaTimeoutSubscription=new r.Subscription,this.videoState=new Q(C.STOPPED),this.syncPlayback=()=>{const i=this.videoState.getState(),a=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: ${i}; videoTransition: ${JSON.stringify(a)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){i!==C.STOPPED&&(this.videoState.startTransitionTo(C.STOPPED),this.stop());return}if(!a){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===O.Requested&&i!==C.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(i){case C.PLAYING:case C.PAUSED:case C.READY:break;case C.STOPPED:this.videoState.startTransitionTo(C.READY),this.prepare();break;default:r.assertNever(i)}break}case exports.PlaybackState.PLAYING:{switch(i){case C.PLAYING:break;case C.PAUSED:this.videoState.startTransitionTo(C.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case C.READY:this.videoState.startTransitionTo(C.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case C.STOPPED:this.videoState.startTransitionTo(C.READY),this.prepare();break;default:r.assertNever(i)}break}case exports.PlaybackState.PAUSED:{switch(i){case C.PLAYING:this.videoState.startTransitionTo(C.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case C.PAUSED:break;case C.READY:this.videoState.startTransitionTo(C.PAUSED),this.videoState.setState(C.PAUSED);break;case C.STOPPED:this.videoState.startTransitionTo(C.READY),this.prepare();break;default:r.assertNever(i)}break}default:r.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(Bh(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new r.Subscription;this.subscription.add(e),this.subscription.add(r.merge(this.videoState.stateChangeStarted$.pipe(r.map(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(r.map(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));const t=(a,n)=>this.subscription.add(a.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const a=new r.Subject;e.add(a.pipe(r.debounce(Fh)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(r.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===O.Applying||Math.abs(l-n)>Mh)&&a.next(l),n=l})),e.add(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);const{remotePlayer:n}=this.params.connection,o=a.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<Vh&&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:r.assertNever(o)}}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});const i=r.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(C.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(C.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:O.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===C.PAUSED||e===C.PLAYING)&&(this.videoState.setState(C.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)===C.PLAYING||e===C.PAUSED)&&(this.videoState.setState(C.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===C.READY&&this.videoState.setState(C.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()!==C.STOPPED&&this.videoState.setState(C.STOPPED)}handleRemoteVolumeChange(e){var t,i;const a=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:a.volume,muted:(i=e.muted)!==null&&i!==void 0?i:a.muted};(n.volume!==a.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const i=this.params.source;let a,n,o;switch(e){case exports.VideoFormat.MPEG:{const c=i[e];r.assertNonNullable(c);const h=r.getHighestQuality(Object.keys(c));r.assertNonNullable(h);const f=c[h];r.assertNonNullable(f),a=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=i[e];r.assertNonNullable(c),a=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:case exports.VideoFormat.DASH_WEBM_AV1:{const c=i[e];r.assertNonNullable(c),a=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=i[e];r.assertNonNullable(c),a=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const c=i[e];r.assertNonNullable(c),a=vt(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:r.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 r.assertNever(e)}const l=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:a,n);l.contentUrl=a,l.streamType=o,l.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:d,subtitle:u}=this.params.meta;return r.isNonNullable(d)&&(l.metadata.title=d),r.isNonNullable(u)&&(l.metadata.subtitle=u),l}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===O.Applying||i.state===O.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((a,n)=>{this.loadMediaTimeoutSubscription.add(r.timeout(ur).subscribe(()=>n(`timeout(${ur})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===O.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},a=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:r.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:a})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}class dr{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;const i=this.listeners[e];for(let a=0,n=i.length;a<n;a++)if(i[a].callback===t){i.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const i=this.listeners[e.type].slice();for(let a=0,n=i.length;a<n;a++){const o=i[a];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 _n extends dr{constructor(){super(),this.listeners||dr.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 Rn=class{constructor(){Object.defineProperty(this,"signal",{value:new _n,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(a){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(a){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Rn.prototype[Symbol.toStringTag]="AbortController",_n.prototype[Symbol.toStringTag]="AbortSignal");function In(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function jh(s){typeof s=="function"&&(s={fetch:s});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=s;if(!In({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||a)&&(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,b)=>{c.addEventListener("abort",()=>b(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,o(d,u)])}return o(d,u)},Request:n}}const Ci=In({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Dn=Ci?jh({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,St=Ci?Dn.fetch:window.fetch;Ci?Dn.Request:window.Request;const it=Ci?Rn:window.AbortController,Nt=s=>s.range?s.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class Ot{constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){var t;const{url:i}=e.request,a=(t=this.dashJsRequestQueue.get(i))!==null&&t!==void 0?t:[];a.push(e),this.dashJsRequestQueue.set(i,a)}async executeNextRequests(){for(const[e,t]of this.dashJsRequestQueue.entries()){const i=this.activeRequests.get(e);if(i){t.length&&this.onBigRequestProgress(i);const a=t[0];if(!a||!a.request.range)continue;const[n,o]=Nt(a.request);if(n>=i.from&&o<=i.to)continue;this.activeRequests.delete(e)}if(t.length){const a=this.sendBigRequest(e,t.map(({request:n})=>n));this.activeRequests.set(e,a)}}}abort(e){var t;if(e){const{request:i}=e,a=((t=this.dashJsRequestQueue.get(i.url))!==null&&t!==void 0?t:[]).includes(e),n=this.activeRequests.get(i.url);a&&n&&n.abortController.abort()}else for(const{abortController:i}of this.activeRequests.values())i.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const i=t.map(Nt),a=i[0][0];let n=i[0][1];for(let f=1;f<i.length&&n<this.params.minDataSize;f++){const p=i[f][1];p-a<=2*this.params.minDataSize&&(n=Math.max(n,p))}a===0?n=Math.max(n,a+this.params.minInitSize):n=Math.max(n,a+this.params.minDataSize);const o=new URL(e,location.href);o.searchParams.append("bytes",`${a}-${n}`);const l=o.toString(),d=new it,u=d.signal,c={url:e,from:a,to:n,loaded:0,data:null,abortController:d};u.addEventListener("abort",()=>this.onBigRequestAbort(c));const h=f=>{var p,b;throw(b=(p=this.params).onError)===null||b===void 0||b.call(p,{id:"BigRequestParsing",category:r.ErrorCategory.PARSER,message:"Error parsing response data",thrown:f}),f};return St(l,{signal:u}).then(f=>{var p,b,S;if(c.response=f,!f.ok||!f.body){this.onBigRequestError(c);return}const[g,m]=f.body.tee();(b=(p=this.params).onDownloadStream)===null||b===void 0||b.call(p,m);const v=g.getReader(),E=parseInt((S=f.headers.get("Content-Length"))!==null&&S!==void 0?S:"",10)||n-a+1;c.data=new ArrayBuffer(E);const y=new Uint8Array(c.data),T=async({done:A,value:L})=>{A?this.onBigRequestProgress(c):L&&(y.set(L,c.loaded),c.loaded+=L.byteLength,this.onBigRequestProgress(c),await(v==null?void 0:v.read().then(T,Ot.suppressStreamErrors).catch(h)))};v==null||v.read().then(T,Ot.suppressStreamErrors).catch(h)},Ot.suppressAbort).catch(f=>this.onBigRequestError(c,f)),c}onBigRequestProgress({url:e,from:t,to:i,loaded:a,data:n,response:o}){var l,d,u,c,h,f,p,b;if(!this.activeRequests.has(e)||!n)return;const S=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const g of S){const{request:m}=g,[v,E]=Nt(m),y=v>=t&&E<=t+a,T=t>=v&&t+a<E,A=n.slice(v-t,Math.min(E-t+1,a));if((y||T)&&(m.requestStartDate=(d=m.requestStartDate)!==null&&d!==void 0?d:new Date,m.firstByteDate=(u=m.firstByteDate)!==null&&u!==void 0?u:new Date,m.bytesLoaded=A.byteLength,m.bytesTotal=i-t),y){m.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((c=this.dashJsRequestQueue.get(e))!==null&&c!==void 0?c:[]).filter(R=>R!==g)),(h=g.success)===null||h===void 0||h.call(g,A,"",e);const L=o?Array.from(o.headers.entries()).map(([R,D])=>`${R}: ${D}`).join(`\r
7
+ `):"";(f=this.dashMetrics)===null||f===void 0||f.addHttpRequest(m,e,(p=o==null?void 0:o.status)!==null&&p!==void 0?p:200,L,[])}else T&&((b=g.progress)===null||b===void 0||b.call(g,{loaded:a,total:i-t,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:t,to:i},a){var n,o,l,d;if((o=(n=this.params).onError)===null||o===void 0||o.call(n,{id:"BigRequest",category:r.ErrorCategory.NETWORK,message:"Download error",thrown:a}),!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]=Nt(c.request);(h>=t&&h<i||f>t&&f<=i)&&((d=c==null?void 0:c.error)===null||d===void 0||d.call(c,c.request,String(a)))}if(this.activeRequests.delete(e),a)throw a}onBigRequestAbort({url:e,from:t,to:i}){var a,n;if(!this.activeRequests.has(e))return;const o=(a=this.dashJsRequestQueue.get(e))!==null&&a!==void 0?a:[];for(const l of o){const[d,u]=Nt(l.request);(d>=t&&d<i||u>t&&u<=i)&&((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 yi{constructor(e,t,i){this.baseLoader=e,this.config=i,this.bigRequest=t,t.setMetrics(i.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(yi.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;yi.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const Hh=(s,e)=>t=>({create:i=>{const a=s(t).create(i);return new yi(a,e,i)}}),qh=(s,e)=>{const t=new Ot(e);return s.extend("SchemeLoaderFactory",function(){const{parent:i}=this,a=i.getLoader;return{getLoader:n=>{const o=a(n);return Hh(o,t)}}},!0),()=>t.destroy()};var Yh=s=>{let e,t=!1,i=!1;s.on("playbackTimeUpdated",({timeToEnd:a})=>{i=a<=3,t&&i&&(e==null||e())}),s.extend("MediaSourceController",function(){const{parent:a}=this,n=a.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&i&&(e==null||e())}}},!0)},Gh=s=>{const e=new r.ValueSubject(1/0),t=new r.Subject,i=new r.ValueSubject(void 0),a=new r.ValueSubject(void 0);let n=NaN,o=!1;const l=()=>{n=Date.now(),o=!1},d=c=>{var h,f,p,b,S;const g=jt(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(E=>E.split(": ")));if("x-playback-duration"in g||"x-playback-duration-millis"in g){const E=parseInt((h=c.getResponseHeader("X-Playback-Duration"))!==null&&h!==void 0?h:"",10),y=parseInt((f=c.getResponseHeader("X-Playback-Duration-Millis"))!==null&&f!==void 0?f:"",10),T=(p=y!=null?y:E*1e3)!==null&&p!==void 0?p:NaN;r.isNonNullable(T)&&!isNaN(T)&&e.next(T)}const m=(b=g["x-delivery-type"])!==null&&b!==void 0?b:exports.HttpConnectionType.HTTP1,v=(S={1:!0,0:!1}[g["x-reused"]])!==null&&S!==void 0?S:void 0;i.next(m),a.next(v)},u=c=>{c.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return s.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,b=f.progress;f.onload=function(...S){return d(this),p(...S)},f.progress=function(...S){return u(this),b(...S)},l()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:a,connectionType$:i}},gt=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},zh=s=>s.extend("RequestModifier",()=>({modifyRequestURL:gt}),!0),Wh=s=>{s.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[a,n]=i.request.range.split("-").map(l=>parseInt(l,10)),o=new URL(i.request.url,location.href);o.searchParams.append("bytes",`${a}-${n}`),i.request.url=o.toString(),i.request.range=void 0}t(i)}}},!0)};const Se=(s,e,t,{equal:i=(o,l)=>o===l,changed$:a,onError:n}={})=>{const o=s.getState(),l=e(),d=r.isNullable(a),u=new r.Subscription;return a&&u.add(a.subscribe(c=>{const h=s.getState();i(c,h)&&s.setState(c)},n)),i(l,o)||(t(o),d&&s.setState(o)),u.add(s.stateChangeStarted$.subscribe(c=>{t(c.to),d&&s.setState(c.to)},n)),u},rt=(s,e,t)=>Se(e,()=>s.loop,i=>{r.isNonNullable(i)&&(s.loop=i)},{onError:t}),Ve=(s,e,t,i)=>Se(e,()=>({muted:s.muted,volume:s.volume}),a=>{r.isNonNullable(a)&&(s.muted=a.muted,s.volume=a.volume)},{equal:(a,n)=>a===n||(a==null?void 0:a.muted)===(n==null?void 0:n.muted)&&(a==null?void 0:a.volume)===(n==null?void 0:n.volume),changed$:t,onError:i}),ze=(s,e,t,i)=>Se(e,()=>s.playbackRate,a=>{r.isNonNullable(a)&&(s.playbackRate=a)},{changed$:t,onError:i}),Qh=s=>["__",s.language,s.label].join("|"),Jh=(s,e)=>{if(s.id===e)return!0;const[t,i,a]=e.split("|");return s.language===i&&s.label===a};class we{constructor(){this.available$=new r.Subject,this.current$=new r.ValueSubject(void 0),this.error$=new r.Subject,this.subscription=new r.Subscription,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const a=n=>{this.error$.next({id:"TextTracksManager",category:r.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Se(t.internalTextTracks,()=>Object.values(this.internalTracks),n=>{r.isNonNullable(n)&&this.setInternal(n)},{equal:(n,o)=>r.isNonNullable(n)&&r.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},d)=>l===o[d].id),changed$:this.available$.pipe(r.map(n=>n.filter(({type:o})=>o==="internal"))),onError:a})),this.subscription.add(Se(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{r.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>r.isNonNullable(n)&&r.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},d)=>l===o[d].id),changed$:this.available$.pipe(r.map(n=>n.filter(({type:o})=>o==="external"))),onError:a})),this.subscription.add(Se(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:a})),this.subscription.add(Se(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){r.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(r.fromEvent(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();this.select(i)})),this.subscription.add(r.merge(r.fromEvent(e,"addtrack"),r.fromEvent(e,"removetrack"),r.observableFrom(["init"])).pipe(r.map(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),r.filterChanged((i,a)=>i.length===a.length&&i.every(({id:n},o)=>n===a[o].id))).subscribe(this.available$)),this.subscription.add(r.merge(r.fromEvent(e,"change"),r.observableFrom(["init"])).pipe(r.map(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),r.map(i=>i&&this.htmlTextTrackToITextTrack(i).id),r.filterChanged()).subscribe(this.current$));const t=i=>{var a,n;return this.applyCueSettings((n=(a=i.target)===null||a===void 0?void 0:a.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(r.fromEvent(e,"addtrack").subscribe(i=>{var a,n;(a=i.track)===null||a===void 0||a.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=i.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(r.fromEvent(e,"removetrack").subscribe(i=>{var a;(a=i.track)===null||a===void 0||a.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const a=i;r.isNonNullable(t.align)&&(a.align=t.align),r.isNonNullable(t.position)&&(a.position=t.position),r.isNonNullable(t.size)&&(a.size=t.size),r.isNonNullable(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){r.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(we.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,a=e.id!==""?e.id:Qh(e),n=this.externalTracks.has(a),o=a.includes("auto");return n?{id:a,type:"external",isAuto:o,language:t,label:i,url:this.externalTracks.get(a).url}:{id:a,type:"internal",isAuto:o,language:t,label:i,url:this.internalTracks.get(a).url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){this.externalTracks.size===0&&(e.filter(({id:t})=>!this.internalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.internalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t)))}select(e){r.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))r.isNonNullable(e)&&Jh(t,e)?t.mode="showing":t.mode="disabled"}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){r.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),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){r.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const ea=s=>{s.removeAttribute("src"),s.load()},Kh=s=>{try{s.pause(),s.playbackRate=0,ea(s),s.remove()}catch(e){console.error(e)}};class Xh{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}}const Os=window.WeakMap?new WeakMap:new Xh,Fe=s=>{let e=s.querySelector("video");const t=Boolean(e);return e?ea(e):(e=document.createElement("video"),s.appendChild(e)),Os.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},Ue=s=>{const e=Os.get(s);Os.delete(s),e?ea(s):Kh(s)};class ta{constructor(){this.pausedTime=0,this.streamOffset=0,this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}}const Nn=s=>{var e;let t=s;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},cr=s=>{const e=Nn(s);return Boolean(e&&e.fullscreenElement&&e.fullscreenElement===s)},Zh=s=>{const e=Nn(s);return Boolean(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)},Bs=3;class ef{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let a=this._source.buffered.start(t);const n=this._source.buffered.end(t);a>e&&a-e<Bs&&(a=e),this._buffer.push({from:a,to:n,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||Bs))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:a,to:n})=>{const o=a>=e&&a<t,l=n>=e&&n<t;o&&l||(o?i(t,n):l?i(a,e):a<e&&n>t?(i(t,n),i(a,e)):i(a,n))})}destroy(){this._buffer=[]}}var Cn=(s,e,t=Bs)=>{let i=0,a=0;for(let n=0;n<s.length;n++){const o=s.start(n),l=s.end(n);if(o<=e&&e<=l){if(i=o,a=l,!t)return{from:i,to:a};for(let d=n-1;d>=0;d--)s.end(d)+t>=i&&(i=s.start(d));for(let d=n+1;d<s.length;d++)s.start(d)-t<=a&&(a=s.end(d))}}return{from:i,to:a}};const tf=1e3,sf=s=>{const e=r.getCurrentBrowser();return e.browser===r.CurrentClientBrowser.Chrome&&e.device===r.CurrentClientDevice.Android?!0:s.webkitAudioDecodedByteCount!==void 0?!!s.webkitAudioDecodedByteCount:s.mozHasAudio!==void 0?s.mozHasAudio:s.audioTracks?!!s.audioTracks.length:!0},je=s=>{const e=y=>r.fromEvent(s,y).pipe(r.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],i=r.merge(...t.map(y=>r.fromEvent(s,y))).pipe(r.map(y=>y.type==="ended"?s.readyState<2:s.readyState<3),r.filterChanged()),a=r.merge(r.fromEvent(s,"progress"),r.fromEvent(s,"timeupdate")).pipe(r.map(()=>Cn(s.buffered,s.currentTime))),o=r.getCurrentBrowser().browser===r.CurrentClientBrowser.Safari?r.combine({play:e("play").pipe(r.once()),playing:e("playing")}).pipe(r.mapTo(void 0)):e("playing"),l=r.fromEvent(s,"playing").pipe(r.debounce(tf),r.map(()=>sf(s))),d=r.fromEvent(s,"volumechange").pipe(r.map(()=>({muted:s.muted,volume:s.volume}))),u=r.fromEvent(s,"ratechange").pipe(r.map(()=>s.playbackRate)),c=r.fromEvent(s,"error").pipe(r.filter(()=>Boolean(s.error||s.played.length)),r.map(()=>{var y;const T=s.error;return{id:T?`MediaError#${T.code}`:"HtmlVideoError",category:r.ErrorCategory.VIDEO_PIPELINE,message:T?T.message:"Error event from HTML video element",thrown:(y=s.error)!==null&&y!==void 0?y:void 0}})),h=r.fromEvent(s,"timeupdate").pipe(r.map(()=>s.currentTime)),f=new r.Subject,p=.3;let b;h.subscribe(y=>{s.loop&&r.isNonNullable(b)&&r.isNonNullable(y)&&b>=s.duration-p&&y<=p&&f.next(b),b=y});const S=r.fromEvent(s,"enterpictureinpicture"),g=r.fromEvent(s,"leavepictureinpicture"),m=new r.ValueSubject(Zh(s));S.subscribe(()=>m.next(!0)),g.subscribe(()=>m.next(!1));const v=new r.ValueSubject(cr(s));return r.fromEvent(s,"fullscreenchange").pipe(r.map(()=>cr(s))).subscribe(v),{playing$:o,pause$:e("pause").pipe(r.filter(()=>!s.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:f,error$:c,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:h,durationChange$:r.fromEvent(s,"durationchange").pipe(r.map(()=>s.duration)),isBuffering$:i,currentBuffer$:a,volumeState$:d,isAudioAvailable$:l,playbackRateState$:u,inPiP$:m,inFullscreen$:v}},ia=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var af=Di,rf=Ri,nf=Ks,of=Js;af({target:"Array",proto:!0},{at:function(e){var t=rf(this),i=nf(t),a=of(e),n=a>=0?a:i+a;return n<0||n>=i?void 0:t[n]}});var lf=js,Ln=lf,uf=Ln,df=uf("Array","at"),cf=df,hf=cf,ff=hf,pf=ff,Re=pf;let sa=!1,De={};const mf=s=>{sa=s},bf=()=>{De={}},vf=s=>{s(De)},si=(s,e)=>{var t;sa&&(De.meta=(t=De.meta)!==null&&t!==void 0?t:{},De.meta[s]=e)};class ke{constructor(e){this.name=e}next(e){var t,i;if(!sa)return;De.series=(t=De.series)!==null&&t!==void 0?t:{};const a=(i=De.series[this.name])!==null&&i!==void 0?i:[];a.push([Date.now(),e]),De.series[this.name]=a}}const Sf=new ke("best_bitrate"),gf=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class yf{constructor(){this.history={}}recordSelection(e){this.history[e.id]=r.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Ht=(s,{container:e,throughput:t,tuning:i,limits:a,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:d,history:u})=>{var c,h,f,p;const b=i.usePixelRatio&&(c=window.devicePixelRatio)!==null&&c!==void 0?c:1,S=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*b*i.containerSizeFactor,height:e.height*b*i.containerSizeFactor},g=S&&r.videoSizeToQuality(S),m=i.considerPlaybackRate&&r.isNonNullable(l)?l:1,v=s.filter(I=>!r.isInvariantQuality(I.quality)).sort((I,_)=>r.isHigher(I.quality,_.quality)?-1:1),E=(h=Re(v,-1))===null||h===void 0?void 0:h.quality,y=(f=Re(v,0))===null||f===void 0?void 0:f.quality,T=r.isNullable(a)||r.isNonNullable(a.min)&&r.isNonNullable(a.max)&&r.isLower(a.max,a.min)||r.isNonNullable(a.min)&&y&&r.isHigher(a.min,y)||r.isNonNullable(a.max)&&E&&r.isLower(a.max,E),A=m*gf(o!=null?o:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),R=v.filter(I=>{const _=g?r.isLower(I.quality,g):!0,j=r.isNonNullable(t)&&isFinite(t)&&r.isNonNullable(I.bitrate)?t-n>=I.bitrate*A:!0,W=i.lazyQualitySwitch&&r.isNonNullable(i.minBufferToSwitchUp)&&d&&!r.isInvariantQuality(d.quality)&&(o!=null?o:0)<i.minBufferToSwitchUp&&r.isHigher(I.quality,d.quality),te=T||(r.isNullable(a.max)||r.isLowerOrEqual(I.quality,a.max))&&(r.isNullable(a.min)||r.isHigherOrEqual(I.quality,a.min));return _&&j&&!W&&te})[0];R&&R.bitrate&&Sf.next(R.bitrate);const D=(p=R!=null?R:v[Math.ceil((v.length-1)/2)])!==null&&p!==void 0?p:s[0],M=D&&u&&u.history[D.id]&&r.now()-u.history[D.id]<=i.trackCooldown&&(!u.last||D.id!==u.last.id);if(D!=null&&D.id&&u&&!M&&u.recordSelection(D),M&&(u!=null&&u.last)){const I=u.last;return u==null||u.recordSwitch(I),I}return u==null||u.recordSwitch(D),D};var oe=s=>new URL(s).hostname;const Tf=300,Ti=(s,e=Tf)=>new r.Observable(t=>{const{width:i,height:a}=s.getBoundingClientRect();if(t.next({width:i,height:a}),!window.ResizeObserver)return;const n=new ResizeObserver(yo(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),r.isNonNullable(d)&&r.isNonNullable(u)&&t.next({width:d,height:u})},e));return n.observe(s),()=>n.disconnect()}),Ef=5e3,Ct={};var B;(function(s){s.DOWNLOADING_LIB="downloading_lib",s.STOPPED="stopped",s.STREAM_INITIALIZED="stream_initialized",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(B||(B={}));const ee=(s,e)=>new r.Observable(t=>{const i=a=>t.next(a);return s.on(e,i),()=>s.off(e,i)});class hr{constructor(e){this.subscription=new r.Subscription,this.videoState=new Q(B.DOWNLOADING_LIB),this.textTracksManager=new we,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new r.ValueSubject(void 0),this.maxSeekBackTime$=new r.ValueSubject(1/0),this.availableFrom$=new r.ValueSubject(void 0),this.elementSize$=new r.ValueSubject(void 0),this.liveOffset=new ta,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState(),o=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===B.DOWNLOADING_LIB||t===B.STREAM_INITIALIZED))switch((a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&n.state===O.Requested&&t!==B.STOPPED&&i!==exports.PlaybackState.STOPPED&&(o?this.seek(n.position-this.liveOffset.getTotalPausedTime()):this.seek(n.position)),i){case exports.PlaybackState.STOPPED:{switch(t){case B.STOPPED:break;case B.PLAYING:case B.PAUSED:case B.READY:this.stop();break;default:r.assertNever(t)}break}case exports.PlaybackState.READY:{switch(t){case B.STOPPED:this.prepare();break;case B.PLAYING:case B.PAUSED:case B.READY:break;default:r.assertNever(t)}break}case exports.PlaybackState.PLAYING:{switch(t){case B.PLAYING:break;case B.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 B.READY:this.play();break;case B.STOPPED:this.prepare();break;default:r.assertNever(t)}break}case exports.PlaybackState.PAUSED:{switch(t){case B.PLAYING:this.pause(),this.liveOffset.pause();break;case B.PAUSED:break;case B.READY:this.videoState.setState(B.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case B.STOPPED:this.prepare();break;default:r.assertNever(t)}break}default:r.assertNever(i)}},this.video=Fe(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=a=>{var n;e||this.params.output.error$.next({id:a==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:r.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${(n=a==null?void 0:a.toString)===null||n===void 0?void 0:n.call(a)}`,thrown:a}),e=!0},i=window.setTimeout(()=>t("timeout"),Ef);import("dashjs/dist/dash.mediaplayer.min.js").then(a=>{e||(Ct.MediaPlayer=a.MediaPlayer,Ct.Debug=a.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){r.assertNonNullable(Ct.MediaPlayer,"dashjs not loaded"),r.assertNonNullable(Ct.Debug,"dashjs not loaded"),this.player=Ct.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?ia(t.frameRate+""):void 0),!0)),(this.params.format===exports.VideoFormat.DASH_WEBM||this.params.format===exports.VideoFormat.DASH_WEBM_AV1)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=qh(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&&Wh(this.player),Yh(this.player),this.params.tuning.requestQuick&&zh(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(B.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=m=>{e.error$.next({id:"DashIFProvider",category:r.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:m})},a=(m,v)=>this.subscription.add(m.subscribe(v,i));a(Ti(this.video),this.elementSize$),a(ee(this.player,"error").pipe(r.map(m=>{const v=typeof m.error=="object"?m.error.code:m.error,E=typeof m.error=="object"?m.error.message:void 0;return{id:`DashJS#${v}`,message:E}})),e.error$),a(ee(this.player,"playbackError").pipe(r.map(m=>({id:"DashJSPlayback",message:m.error}))),e.error$);const n=ee(this.player,"qualityChangeRendered").pipe(r.filter(({mediaType:m})=>m==="video"),r.map(({newQuality:m})=>{var v;return(v=this.videoTracks.find(({bitrateInfo:E})=>E.qualityIndex===m))===null||v===void 0?void 0:v.track}));n.pipe(r.filter(r.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(r.filter(({to:m})=>m===B.STREAM_INITIALIZED),r.once()).subscribe(()=>{this.subscription.add(Se(t.videoTrack,()=>{var m,v;const E=this.player.getQualityFor("video");return(v=(m=this.videoTracks.find(({bitrateInfo:y})=>y.qualityIndex===E))===null||m===void 0?void 0:m.track)===null||v===void 0?void 0:v.id},m=>{var v;if(r.isNullable(m))return;const E=(v=this.videoTracks.find(({track:y})=>y.id===m))===null||v===void 0?void 0:v.bitrateInfo;E&&this.player.setQualityFor("video",E.qualityIndex)},{changed$:n.pipe(r.map(m=>m==null?void 0:m.id)),onError:i}))},i)),this.subscription.add(Se(t.autoVideoTrackSwitching,()=>{var m,v,E;return(E=(v=(m=this.player.getSettings().streaming)===null||m===void 0?void 0:m.abr)===null||v===void 0?void 0:v.autoSwitchBitrate)===null||E===void 0?void 0:E.video},m=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:m}}}}),{onError:i})),a(ee(this.player,"bufferStateChanged").pipe(r.filter(({mediaType:m})=>m==="video"),r.map(({state:m})=>m==="bufferStalled")),e.isBuffering$),a(ee(this.player,"fragmentLoadingStarted"),({mediaType:m,request:{url:v}})=>{var E,y;const T=this.player.getDashMetrics(),A=T.getLatestFragmentRequestHeaderValueByID(m,"X-Reused"),L=(E=T.getLatestFragmentRequestHeaderValueByID(m,"X-Delivery-Type"))!==null&&E!==void 0?E:exports.HttpConnectionType.HTTP1,R=(y={1:!0,0:!1}[A])!==null&&y!==void 0?y:void 0;this.params.output.httpConnectionType$.next(L),this.params.output.httpConnectionReused$.next(R),e.hostname$.next(oe(v))}),a(ee(this.player,"streamInitialized"),({streamInfo:{duration:m,manifestInfo:{isDynamic:v,availableFrom:E}}})=>{this.isLive$.next(v),this.availableFrom$.next(E.getTime()),v||e.duration$.next(m),this.videoTracks=[];const y=this.player.getQualityFor("video");let T;for(const A of this.player.getBitrateInfoListFor("video")){const L=A.qualityIndex.toString(10),R=r.videoSizeToQuality(A),D=A.bitrate/1e3,M={width:A.width,height:A.height},I=this.frameRatesByFrameHeight[A.height];if(R){const _={id:L,quality:R,bitrate:D,size:M,fps:I};this.videoTracks.push({track:_,bitrateInfo:A}),A.qualityIndex===y&&(T=_)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:A})=>A)),T&&e.currentVideoTrack$.next(T),this.videoState.setState(B.STREAM_INITIALIZED),this.videoState.startTransitionTo(B.READY)}),a(ee(this.player,"fragmentLoadingCompleted"),({request:m})=>{if(!m.requestEndDate||!m.firstByteDate||!m.bytesLoaded)return;const v=m.requestEndDate.getTime()-m.firstByteDate.getTime(),E=m.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(E,v)}),a(r.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(),v=Ht(this.videoTracks.map(({track:y})=>y),{container:this.elementSize$.getValue(),throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),E=this.videoTracks.find(({track:y})=>y===v);E!=null&&E.bitrateInfo&&this.player.setQualityFor("video",E==null?void 0:E.bitrateInfo.qualityIndex,!1)}),a(r.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(r.filter(r.isNonNullable))}).pipe(r.filter(({isLive:m})=>m),r.map(({maxSeekBackTime:m})=>-m/1e3)),this.params.output.duration$);const o=ee(this.player,"playbackTimeUpdated").pipe(r.map(({time:m})=>m!=null?m:0));a(r.combine({availableFrom:this.availableFrom$.pipe(r.filter(r.isNonNullable)),currentTime:o}),({availableFrom:m,currentTime:v})=>this.params.output.liveTime$.next(m+v*1e3)),a(o.pipe(r.filter(()=>this.isLive$.getValue()===!1)),e.position$),a(ee(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),a(ee(this.player,"playbackEnded"),e.endedEvent$),a(ee(this.player,"playbackProgress").pipe(r.map(()=>Cn(this.video.buffered,this.video.currentTime))),e.currentBuffer$),a(ee(this.player,"playbackPlaying"),()=>{this.videoState.setState(B.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)}),a(ee(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(B.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),a(ee(this.player,"playbackPaused"),()=>{this.videoState.setState(B.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)}),a(ee(this.player,"canPlay"),()=>{var m;((m=this.videoState.getTransition())===null||m===void 0?void 0:m.to)===B.READY&&this.videoState.setState(B.READY)}),a(this.isLive$,e.isLive$),a(Ti(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const l=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));a(l,this.syncPlayback);const{playbackDuration$:d,ping$:u,connectionType$:c,connectionReused$:h}=Gh(this.player);a(c,this.params.output.httpConnectionType$),a(h,this.params.output.httpConnectionReused$),a(d,this.maxSeekBackTime$),a(u.pipe(r.once()),e.firstBytesEvent$),a(ee(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&a(r.combine({isLive:this.isLive$,isShort:e.duration$.pipe(r.map(m=>m<60))}),({isLive:m,isShort:v})=>{const E=!m&&v;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:E}}})}),a(o.pipe(r.filter(m=>m>this.params.tuning.insufficientBufferRuleMargin),r.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(ee(this.player,"manifestLoaded").pipe(r.once()).subscribe(()=>{this.subscription.add(ee(this.player,"playbackPlaying").pipe(r.once(),r.mapTo(void 0)).subscribe(e.firstFrameEvent$,i))},i)),a(ee(this.player,"manifestLoaded"),m=>{var v,E,y,T,A,L,R;if(!((E=(v=m.data)===null||v===void 0?void 0:v.Period)===null||E===void 0)&&E.AdaptationSet){const D=[];for(const M of(T=(y=m.data)===null||y===void 0?void 0:y.Period)===null||T===void 0?void 0:T.AdaptationSet)if(M.contentType==="text"){const I=(A=M.Representation)===null||A===void 0?void 0:A.id,_=new URL((L=M.Representation)===null||L===void 0?void 0:L.BaseURL,(R=m.data)===null||R===void 0?void 0:R.baseUri).toString(),j="internal",W=M.lang;D.push({id:I,url:_,type:j,language:W})}t.internalTextTracks.startTransitionTo(D)}}),this.subscription.add(rt(this.video,t.isLooped,i));const{volumeState$:f,looped$:p,playbackRateState$:b,inPiP$:S,inFullscreen$:g}=je(this.video);this.subscription.add(Ve(this.video,t.volume,f,i)),this.subscription.add(f.subscribe(e.volume$,i)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(ze(this.video,t.playbackRate,b,i)),this.subscription.add(S.subscribe(e.inPiP$)),this.subscription.add(g.subscribe(e.inFullscreen$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(B.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(B.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const a=vt(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,bt.PLAYBACK_SHIFT);this.player.attachSource(a)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(B.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(B.PAUSED),this.video.pause()}destroy(){var e,t;this.subscription.unsubscribe(),this.textTracksManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(i){}Ue(this.video),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var qt=s=>{switch(s){case"mobile":return r.VideoQuality.Q_144P;case"lowest":return r.VideoQuality.Q_240P;case"low":return r.VideoQuality.Q_360P;case"sd":case"medium":return r.VideoQuality.Q_480P;case"hd":case"high":return r.VideoQuality.Q_720P;case"fullhd":case"full":return r.VideoQuality.Q_1080P;case"quadhd":case"quad":return r.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return r.VideoQuality.Q_2160P}};const fr=s=>{if(s instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(s.message))throw s;return!(s instanceof DOMException&&(s.code===20||s.name==="AbortError"))};var We=async s=>{const e=s.muted;try{await s.play()}catch(t){if(!fr(t))return!1;if(e)return console.warn(t),!1;s.muted=!0;try{await s.play()}catch(i){return fr(i)&&(s.muted=!1,console.warn(i)),!1}}return!0};function ne(){return r.now()}function xn(s){return ne()-s}function pr(s){const e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,a=o=>i.test(o);return{resolve:(o,l,d=!1)=>{a(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 $f(s,e,t){const i=(...a)=>{t.apply(null,a),s.removeEventListener(e,i)};s.addEventListener(e,i)}function mi(s,e,t,i){const a=window.XMLHttpRequest;let n,o,l,d=!1,u=0,c,h,f=!1,p="arraybuffer",b=7e3,S=2e3,g=()=>{if(d)return;r.assertNonNullable(c);const _=xn(c);let j;if(_<S){j=S-_,setTimeout(g,j);return}S*=2,S>b&&(S=b),o&&o.abort(),o=new a,A()};const m=_=>(n=_,I),v=_=>(h=_,I),E=()=>(p="json",I),y=()=>{if(!d){if(--u>=0){g(),i&&i();return}d=!0,h&&h(),t&&t()}},T=_=>(f=_,I),A=()=>{c=ne(),o=new a,o.open("get",s);let _=0,j,W=0;const te=()=>(r.assertNonNullable(c),Math.max(c,Math.max(j||0,W||0)));if(n&&o.addEventListener("progress",k=>{const N=ne();n.updateChunk&&k.loaded>_&&(n.updateChunk(te(),k.loaded-_),_=k.loaded,j=N)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>y())),o.addEventListener("load",()=>{if(d)return;r.assertNonNullable(o);const k=o.status;if(k>=200&&k<300){if(o.response.byteLength&&n){const N=o.response.byteLength-_;N&&n.updateChunk&&n.updateChunk(te(),N)}h&&h(),o&&e(o.response)}else y()}),o.addEventListener("error",()=>{y()}),f){const k=()=>{r.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(W=ne(),o.removeEventListener("readystatechange",k))};o.addEventListener("readystatechange",k)}return o.responseType=p,o.send(),I},I={withBitrateReporting:m,withParallel:T,withJSONResponse:E,withRetryCount:_=>(u=_,I),withRetryInterval:(_,j)=>(r.isNonNullable(_)&&(S=_),r.isNonNullable(j)&&(b=j),I),withTimeout:_=>(l=_,I),withFinally:v,send:A,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return I}const kf=100,Pf=2e3,Af=500;let wf=class{constructor(e){this.intervals=[],this.currentRate=0,this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,i){return{start:e,end:t,bytes:i}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-Af;if(t-e>Pf){let i=0,a=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)i+=n.end-n.start,a+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,l=n.end-n.start;i+=o;const d=n.bytes*o/l;a+=d,n.start=t,n.bytes-=d}}}if(a>0&&i>0){const n=a*8/(i/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(a)}/${Math.round(i)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>kf&&(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 _f{constructor(e,t,i,a,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=i,this.MAX_PARALLEL_REQUESTS=a,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 i=ne(),a=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=ne()-i,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=mi(t,n,()=>a("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=ne()}_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=ne();if(Object.keys(this.activeRequests).length>=e)return!1;const i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,i,a){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=i,o._retryCB=a,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}`),i(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=i,n._retryCB=a,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 ai=1e4,ri=3,Rf=300,If=2e3,Df=6e4,Nf=10,Cf=1,Lf=500;class xf{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 wf(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=pr(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=pr(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var i;Boolean(e.error)&&!this.destroyed&&(t(`Video element error: ${(i=e.error)===null||i===void 0?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,i=t.buffered.length;let a;i!==0&&(a=t.buffered.start(i-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){const{videoElement:t}=this.params;let i,a,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)?(!a||n.bitrate>a.bitrate)&&(a=n):(!i||i.bitrate>n.bitrate)&&(i=n));return a||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||r.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:i,videoElement:a,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{$f(a,"progress",()=>{a.buffered.length?(a.currentTime=a.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 _f(ri,ai,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,playerCallback:a}=this.params;let n=!1,o=null,l=null,d=null,u=null,c=!1;const h=()=>{const y=n&&(!c||c===this.rep);return y||t("Not running!"),y},f=(y,T,A)=>{d&&d.abort(),d=mi(this.urlResolver.resolve(y,!1),T,A,()=>this._retryCallback()).withTimeout(ai).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ri).withFinally(()=>{d=null}).send()},p=(y,T,A)=>{r.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),T,A,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},b=y=>{const T=i.playbackRate;i.playbackRate!==y&&(t(`Playback rate switch: ${T}=>${y}`),i.playbackRate=y)},S=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)b(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){b(1);return}const A=ne()-1e4;let L=0;for(let D=0;D<this.bufferStates.length;D++){const M=this.bufferStates[D];y=Math.min(y,M.buf),M.ts<A&&L++}this.bufferStates.splice(0,L),t(`update playback rate; minBuffer=${y} drop=${L} jitter=${this.sourceJitter}`);let R=y-Cf;this.sourceJitter>=0?R-=this.sourceJitter/2:this.sourceJitter-=1,R>3?b(1.15):R>1?b(1.1):R>.3?b(1.05):b(1)}},m=y=>{let T;const A=()=>T&&T.start?T.start.length:0,L=k=>T.start[k]/1e3,R=k=>T.dur[k]/1e3,D=k=>T.fragIndex+k,M=(k,N)=>({chunkIdx:D(k),startTS:L(k),dur:R(k),discontinuity:N}),I=()=>{let k=0;if(T&&T.dur){let N=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,G=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,X=N;this.sourceJitter>1&&(X+=this.sourceJitter-1);let ie=T.dur.length-1;for(;ie>=0&&(X-=T.dur[ie],!(X<=0));--ie);k=Math.min(ie,T.dur.length-1-G),k=Math.max(k,0)}return M(k,!0)},_=k=>{const N=A();if(!(N<=0)){if(r.isNonNullable(k)){for(let G=0;G<N;G++)if(L(G)>k)return M(G)}return I()}},j=k=>{const N=A(),G=k?k.chunkIdx+1:0,X=G-T.fragIndex;if(!(N<=0)){if(!k||X<0||X-N>Nf)return t(`Resync: offset=${X} bChunks=${N} chunk=`+JSON.stringify(k)),I();if(!(X>=N))return M(G-T.fragIndex,!1)}},W=(k,N,G)=>{u&&u.abort(),u=mi(this.urlResolver.resolve(k,!0,this.lowLatency),N,G,()=>this._retryCallback()).withTimeout(ai).withRetryCount(ri).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(k,N)=>{W(y,G=>{if(!h())return;T=G;const X=Boolean(T.lowLatency);X!==this.lowLatency&&S(X);let ie=0;for(let le=0;le<T.dur.length;++le)ie+=T.dur[le];ie>0&&(r.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ie/T.dur.length)),a({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,k(_(N))},()=>this._handleNetworkError())},nextChunk:j}},v=()=>{n=!1,l&&l.abort(),d&&d.abort(),u&&u.abort(),r.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:y=>{const{videoElement:T,logger:A}=this.params;let L=m(e.jidxUrl),R,D,M,I,_=0,j,W,te;const k=()=>{j&&(clearTimeout(j),j=void 0);const F=Math.max(Lf,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),se=_+F,fe=ne(),pe=Math.min(1e4,se-fe);_=fe;const _e=()=>{u||h()&&L.seek(()=>{h()&&(_=ne(),N(),k())})};pe>0?j=window.setTimeout(()=>{this.paused?k():_e()},pe):_e()},N=()=>{let F;for(;F=L.nextChunk(I);)I=F,ye(F);const se=L.nextChunk(M);if(se){if(M&&se.discontinuity){A("Detected discontinuity; restarting playback"),this.paused?k():(v(),this._initPlayerWith(e));return}le(se)}else k()},G=(F,se)=>{if(!h()||!this.sourceBuffer)return;let fe,pe,_e;const Qe=qe=>{window.setTimeout(()=>{h()&&G(F,se)},qe)};if(this.sourceBuffer.updating)A("Source buffer is updating; delaying appendBuffer"),Qe(100);else{const qe=ne(),nt=T.currentTime;!this.paused&&T.buffered.length>1&&W===nt&&qe-te>500&&(A("Stall suspected; trying to fix"),this._fixupStall()),W!==nt&&(W=nt,te=qe);const Te=this._getBufferSizeSec();if(Te>30)A(`Buffered ${Te} seconds; delaying appendBuffer`),Qe(2e3);else try{this.sourceBuffer.appendBuffer(F),this.videoPlayStarted?(this.bufferStates.push({ts:qe,buf:Te}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),se&&se()}catch($t){if($t.name==="QuotaExceededError")A("QuotaExceededError; delaying appendBuffer"),_e=this.sourceBuffer.buffered.length,_e!==0&&(fe=this.sourceBuffer.buffered.start(0),pe=nt,pe-fe>4&&this.sourceBuffer.remove(fe,pe-3)),Qe(1e3);else throw $t}}},X=()=>{D&&R&&(A([`Appending chunk, sz=${D.byteLength}:`,JSON.stringify(M)]),G(D,function(){D=null,N()}))},ie=F=>e.fragUrlTemplate.replace("%%id%%",F.chunkIdx),le=F=>{h()&&p(ie(F),(se,fe)=>{if(h()){if(fe/=1e3,D=se,M=F,o=F.startTS,fe){const pe=Math.min(10,F.dur/fe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*pe:pe}X()}},()=>this._handleNetworkError())},ye=F=>{h()&&(r.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ie(F),!1)))},He=F=>{h()&&(e.cachedHeader=F,G(F,()=>{R=!0,X()}))};n=!0,L.seek(F=>{if(h()){if(_=ne(),!F){k();return}I=F,!r.isNullable(y)||F.startTS>y?le(F):(M=F,N())}},y),e.cachedHeader?He(e.cachedHeader):f(e.headerUrl,He,()=>this._handleNetworkError())},stop:v,getTimestampSec:()=>o},c}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),r.isNonNullable(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,r.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return r.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=h=>{if(!this.autoQuality)return;let f,p,b;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(p=this._getBufferSizeSec(),b=h/this.bitrate,p>10&&b>.8||p>15&&b>.5||p>20&&b>.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 b=ne();if(this.chunkRateEstimator.addInterval(f,b,p)){const g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:b-f,speed:g}),!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&&xn(o)<3e4)return;i(h)}d=this.autoQuality};return{updateChunk:(h,f)=>{const p=n.updateChunk(h,f);return p&&u(),p},notifySwitch:h=>{const f=ne();h<l&&(o=f),l=h}}}_fetchManifest(e,t,i){this.manifestRequest=mi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(ai).withRetryCount(ri).withRetryInterval(Rf,If).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;We(t).then(i=>{i||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:a}=this.params,n=o=>{const l=[];return o!=null&&o.length?(o.forEach((d,u)=>{d.video&&a.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}`),i({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},Df))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var x;(function(s){s.STOPPED="stopped",s.MANIFEST_READY="manifest_ready",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(x||(x={}));const Of=[x.PAUSED,x.PLAYING,x.READY],Bf=[x.PAUSED,x.PLAYING,x.READY];class Mf{constructor(e){this.subscription=new r.Subscription,this.videoState=new Q(x.STOPPED),this.representations$=new r.ValueSubject([]),this.textTracksManager=new we,this.maxSeekBackTime$=new r.ValueSubject(1/0),this.zeroTime$=new r.ValueSubject(void 0),this.liveOffset=new ta,this._dashCb=a=>{var n,o,l,d;switch(a.name){case"buffering":{const u=a.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${a.type}`,category:r.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=a.manifest,c=[];for(const h of u){const f=(n=h.name)!==null&&n!==void 0?n:h.index.toString(10),p=(o=qt(h.name))!==null&&o!==void 0?o:r.videoSizeToQuality(h.video),b=h.bitrate/1e3,S={...h.video};if(!p)continue;const g={id:f,quality:p,bitrate:b,size:S};c.push({track:g,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)===x.MANIFEST_READY&&this.videoState.setState(x.MANIFEST_READY);break}case"qualitySwitch":{const u=a.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),r.isNonNullable(c)&&this.params.output.currentVideoTrack$.next(c);break}case"bandwidth":{const{size:u,duration:c}=a;this.params.dependencies.throughputEstimator.addRawSpeed(u,c);break}case"index":{this.maxSeekBackTime$.next(a.shiftDuration),this.zeroTime$.next(a.zeroTime);break}}},this.syncPlayback=()=>{var a;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!==x.STOPPED&&(this.videoState.startTransitionTo(x.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(x.STOPPED));return}if(!o){if(Bf.includes(n)){const c=(a=this.params.desiredState.videoTrack.getTransition())===null||a===void 0?void 0:a.to;r.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===O.Requested&&Of.includes(n)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(n){case x.STOPPED:this.videoState.startTransitionTo(x.MANIFEST_READY),this.dash.attachSource(vt(this.params.source.url));return;case x.MANIFEST_READY:this.videoState.startTransitionTo(x.READY),this.prepare();break;case x.READY:if(l===exports.PlaybackState.PAUSED)this.videoState.setState(x.PAUSED);else if(l===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(x.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(x.PAUSED)})}return;case x.PLAYING:l===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(x.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case x.PAUSED:l===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(x.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(x.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return r.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=a=>{e.output.error$.next({id:"DashLiveProvider",category:r.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:a})};r.merge(this.videoState.stateChangeStarted$.pipe(r.map(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(a)}`})}),this.video=Fe(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(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const i=je(this.video);this.subscription.add(i.canplay$.subscribe(()=>{var a;((a=this.videoState.getTransition())===null||a===void 0?void 0:a.to)===x.READY&&this.videoState.setState(x.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(x.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===O.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(x.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(r.filterChanged(),r.map(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(r.combine({zeroTime:this.zeroTime$.pipe(r.filter(r.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:a,position:n})=>this.params.output.liveTime$.next(a+n*1e3),t)).add(rt(this.video,this.params.desiredState.isLooped,t)).add(Ve(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(ze(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:a}})=>{const n=a&&r.videoQualityToHeight(a);this.dash.setMaxAutoQuality(n)})).add(this.videoState.stateChangeEnded$.subscribe(a=>{var n;switch(a.to){case x.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case x.MANIFEST_READY:case x.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 x.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case x.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return r.assertNever(a.to)}},t)).add(r.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ue(this.video)}createLiveDashPlayer(){const e=new xf({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,i,a,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=(a=(i=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||i===void 0?void 0:i.to)!==null&&a!==void 0?a:this.params.desiredState.autoVideoTrackSwitching.getState(),c=!u&&r.isNonNullable(d)?d:(n=Ht(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;r.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 i=(t=this.representations$.getValue().find(({track:a})=>a.id===e))===null||t===void 0?void 0:t.representation;r.assertNonNullable(i,`No such representation ${e}`),this.dash.switchByName(i.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),a=t===exports.PlaybackState.PAUSED&&i===x.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(vt(this.params.source.url,o)),a&&this.dash.pause(),this.liveOffset.resetTo(o,a)}}var On=s=>{var e,t;const i=s.get("X-Delivery-Type"),a=s.get("X-Reused"),n=i===null?exports.HttpConnectionType.HTTP1:(e=i)!==null&&e!==void 0?e:void 0,o=a===null?void 0:(t={1:!0,0:!1}[a])!==null&&t!==void 0?t:void 0;return{type:n,reused:o}},tt=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){const a=s.start(i)*1e3,n=s.end(i)*1e3;a<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const Vf=s=>{const e=document.createElement("a");return e.href=s,e.origin},Ff=s=>{const e=document.createElement("a");return e.href=s,e.host};class Bn{constructor(e,t=[],i,a,n,o){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=i,this._progressCb=a,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,i,a,n,o,l,d,u;if(r.assertNonNullable(this._xhr),((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(i=this._errorCb)===null||i===void 0||i.call(this,`Http${(a=this._xhr)===null||a===void 0?void 0:a.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=jt(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 i;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(i=this._errorCb)===null||i===void 0||i.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let a;this._failoverIndex>=this._failoverHosts.length?(a=this._url,this._failoverIndex=0):(a=this._url.replace(Ff(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",a,!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 Ei{constructor(e){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t==null||t()}catch(i){if(i.name==="QuotaExceededError"){this._isFull=!0;const a=this._sourceBuffer.buffered;let n=0;for(let o=0,l=a.length;o<l;o++)n+=a.end(o)-a.start(o);n&&(this._maxBufferDuration=Math.round(n))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",i),i}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,i,a,n,o,l){this.abort(()=>{let d=0;const u=Date.now();let c=0,h=0,f=0;const p=S=>{a(Ei._str2ua(S.substr(d))),d=S.length};let b=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(b=gt(b)),this._lastXhr=new Bn(b,e.failoverHosts,S=>{this._lastXhr=void 0,p(S);const g=Date.now()-u;this._params.onBandwidthChange({size:S.length,duration:g,speed:8*S.length/(g/1e3)}),this._onDashCallback("loading",{size:S.length,done:!0}),n==null||n()},S=>{if(S.length-d>l&&p(S),h===0){h=Date.now();return}f=S.length-c;const g=Date.now()-h;f>=100*1024&&g>=1e3&&(this._params.onBandwidthChange({size:f,duration:g,speed:8*f/(g/1e3)}),f=0,c=S.length,h=Date.now()),this._onDashCallback("loading",{size:S.length,done:!1})},o,(S,g,m)=>this._params.onError(S,g,m))})}abort(e){var t;(t=this._lastXhr)===null||t===void 0||t.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e==null||e()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(i){throw this._params.onError("SourceBuffer","Source Buffer update error",i),i}};return this._sourceBuffer.addEventListener("updateend",t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener("updateend",e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=Ei._concatUint8(this._appendPromiseUint8Array,e):(this._appendPromiseUint8Array=e,this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,()=>{this._appendPromiseUint8Array=void 0,t&&this._sbUpdatingWatch(t)})}))}endOfStream(){this._mediaSource.readyState==="open"&&this._sbUpdatingWatch(()=>this._mediaSource.endOfStream())}static _concatUint8(e,t){const i=new Uint8Array(e.byteLength+t.byteLength);return i.set(e,0),i.set(t,e.byteLength),i}static _str2ua(e){const t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}remove(e,t){this._sbUpdatingWatch(()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(e,t),this._maxBufferDuration=Number.POSITIVE_INFINITY})}destroy(){var e;(e=this._lastXhr)===null||e===void 0||e.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._mediaSource.readyState==="open"&&this._sourceBuffer.abort()}}class Uf{constructor(e){var t;this._representations=[],this._appendVector={},this._cachingPaused=!1,this._duration=0,this.STREAM_END_THRESHOLD=1,this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=(t=e.onDashCallback)!==null&&t!==void 0?t:()=>{},this._config=e.config}_parseDurationFromISO8601(e){const t=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/,i=(l,d)=>{const u=l?parseFloat(l.replace(",",".")):NaN;return(isNaN(u)?0:u)*d},a=t.exec(e),n=(a==null?void 0:a[1])==="-"?-1:1,o={years:i(a==null?void 0:a[2],n),months:i(a==null?void 0:a[3],n),weeks:i(a==null?void 0:a[4],n),days:i(a==null?void 0:a[5],n),hours:i(a==null?void 0:a[6],n),minutes:i(a==null?void 0:a[7],n),seconds:i(a==null?void 0:a[8],n)};return o.hours*3600+o.minutes*60+o.seconds}getRepresentations(){return this._representations}attachSource(e,t){let i=e;this._config.REQUEST_QUIC&&(i=gt(i)),new Bn(i,t,a=>{this.attachManifest(a,t,Vf(i))},void 0,a=>{this._params.onResponseHeaders(a)},(a,n,o)=>this._params.onError(a,n,o))}attachManifest(e,t,i){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,b,S,g,m,v,E,y,T,A,L,R,D,M,I,_;const j=u.getElementsByTagName("SegmentBase")[0],W=j&&o(j,"indexRange").split("-"),te=j&&j.getElementsByTagName("Initialization")[0],k=te&&o(te,"range").split("-");if(!k||!W){const ye=u.parentElement;if((ye==null?void 0:ye.getAttribute("contentType"))==="text"){const He=(c=u.getAttribute("id"))!==null&&c!==void 0?c:void 0,F=(i?i+"/":"")+((b=(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||b===void 0?void 0:b.data),se=(S=ye.getAttribute("lang"))!==null&&S!==void 0?S:void 0;F&&d.push({id:He,url:F,language:se})}return}const N=.1,G=Number((g=u.attributes.getNamedItem("bandwidth"))===null||g===void 0?void 0:g.value),X=(i?i+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ie;const le=(v=(m=u.attributes.getNamedItem("frameRate"))===null||m===void 0?void 0:m.value)!==null&&v!==void 0?v:void 0;ie=le?ia(le):void 0,l.push({width:Number((E=u.attributes.getNamedItem("width"))===null||E===void 0?void 0:E.value),height:Number((y=u.attributes.getNamedItem("height"))===null||y===void 0?void 0:y.value),bandwidth:G,baseURL:X,failoverHosts:t,indexFrom:Number(W[0]),indexTo:Number(W[1]),initFrom:Number(k[0]),initTo:Number(k[1]),codecs:(A=(T=u.attributes.getNamedItem("codecs"))===null||T===void 0?void 0:T.value)!==null&&A!==void 0?A:void 0,mimeType:(R=(L=u.attributes.getNamedItem("mimeType"))===null||L===void 0?void 0:L.value)!==null&&R!==void 0?R:void 0,fps:ie,bufferSize:N*G/8,bufferLength:N,name:(M=(D=u.attributes.getNamedItem("okQuality"))===null||D===void 0?void 0:D.value)!==null&&M!==void 0?M:void 0,id:(_=(I=u.attributes.getNamedItem("id"))===null||I===void 0?void 0:I.value)!==null&&_!==void 0?_: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");h&&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({representations:this._representations,textRepresentations:d})}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const i=Date.now();this._stream.load(e,e.initFrom,e.indexTo,a=>{let n=e.initTo-e.initFrom+1;if(!a.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(a.buffer,0,n);const o=new DataView(a.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),b=d+o.getUint32(n+4,!1);n+=12,e.refs.push({fromTime:d/l,toTime:b/l,fromOffset:u,toOffset:p-1}),u=p,d=b}const h=e.refs[e.refs.length-1];h.toTime-h.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,a=>{this._params.onResponseHeaders(a),this._params.onIdxRequestPing(Date.now()-i)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const i=new t;let a,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!==a&&(a=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 b=this._buffer.getNextWithGap(p);b&&(this._video.currentTime=b.from)}catch(b){throw this._params.onError("GapSyncError",`Seek Error ${String(b)}`,b),b}},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=i.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Ei({mediaSource:i,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),i.duration||(i.duration=this._duration),this._loopTimeout||l(),i.removeEventListener("sourceopen",d),i.removeEventListener("webkitsourceopen",d)};i.addEventListener("sourceopen",d,!1),i.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),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,i=!1,a=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const n=this._findRef(t);if(n){if(i){this._isLastRef(n)&&t>=n.toTime&&(t=n.fromTime);const o=this._findRef(this._video.currentTime),l=Math.abs(this._video.currentTime-t),d=a||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 i=this._buffer.getByTime(this._video.currentTime),a=this._findRef(this._video.currentTime);if(!i||!a){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(a.toTime<i.to+n){const o=this._findRef(a.toTime);o&&o.toTime<i.to+n?(this._buffer.smartRemove(a.fromTime-n,o.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(a.fromTime-n,a.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,a.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||r.isNullable(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return;if(Array.isArray(i)&&i.length===0){this._params.onError("emptyrefs","Empty refs");return}let a;for(let n=0;n<i.length;n++){const o=i[n];if(o.fromTime<=e&&o.toTime>e)return o;o.fromTime>e&&(!a||o.fromTime<a.fromTime)&&(a=o)}if(!a){const n=i[i.length-1];if(e>n.toTime)return n}return a}_isLastRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return!1;const a=i[i.length-1];return e.fromTime===a.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const i=this._video.buffered.start(t),a=this._video.buffered.end(t);if(e>i&&e<a)return Math.round(a*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var V;(function(s){s.STOPPED="stopped",s.MANIFEST_LOADED="manifest-loaded",s.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",s.METADATA_LOADED="metadata-loaded",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(V||(V={}));const jf=[V.PAUSED,V.PLAYING];class Hf{constructor(e){this.videoState=new Q(V.STOPPED),this.subscription=new r.Subscription,this.representations$=new r.ValueSubject([]),this.currentRepresentation$=new r.ValueSubject(void 0),this.textTracksManager=new we,this.elementSize$=new r.ValueSubject(void 0),this.dashLiteEvents={idxRequestPing$:new r.Subject,responseHeaders$:new r.Subject,manifestReady$:new r.Subject,representationPlay$:new r.Subject,error$:new r.Subject},this.handleManifestReady=({representations:t,textRepresentations:i})=>{var a,n,o;const l=[];for(const d of t){const u=(n=(a=d.name)!==null&&a!==void 0?a:d.id)!==null&&n!==void 0?n:d.height.toString(10),c=(o=d.name&&qt(d.name))!==null&&o!==void 0?o:r.videoSizeToQuality(d),h=d.bandwidth/1e3,f={width:d.width,height:d.height},p=d.fps;if(!c)continue;const b={id:u,quality:c,bitrate:h,size:f,fps:p};l.push({track:b,representation:d})}if(this.representations$.next(l),this.params.output.availableVideoTracks$.next(l.map(({track:d})=>d)),(i==null?void 0:i.length)>0){const d=[];for(const u of i){const c=u.id||`${u.language}_${Date.now()}`;d.push({id:c,type:"internal",url:u.url||"",language:u.language,isAuto:u.isAuto})}this.params.desiredState.internalTextTracks.startTransitionTo(d)}this.videoState.setState(V.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var i;const a=(i=this.representations$.getValue().find(({representation:n})=>n===t))===null||i===void 0?void 0:i.track;a&&(this.params.output.currentVideoTrack$.next(a),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(a.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return r.assertNonNullable(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${a}; seekState: ${JSON.stringify(o)};`}),a===exports.PlaybackState.STOPPED){t!==V.STOPPED&&(this.videoState.startTransitionTo(V.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(V.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!i)switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&o.state===O.Requested&&jf.includes(t)&&this.seek(o.position,o.forcePrecise),t){case V.STOPPED:this.videoState.startTransitionTo(V.MANIFEST_LOADED),this.prepare();return;case V.MANIFEST_LOADED:this.videoState.startTransitionTo(V.INITIAL_REPRESENTATION_SELECTED);return;case V.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(V.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case V.METADATA_LOADED:this.videoState.startTransitionTo(V.READY),this.dash.updateRefsForCurrentTime();return;case V.READY:a===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):a===exports.PlaybackState.PAUSED?(this.videoState.setState(V.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):a===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(V.PLAYING),this.playIfAllowed());return;case V.PLAYING:a===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(V.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case V.PAUSED:a===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(V.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),r.merge(this.videoState.stateChangeStarted$.pipe(r.map(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=Fe(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new ef(this.video),this.dash=new Uf({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:({representations:t,textRepresentations:i})=>this.dashLiteEvents.manifestReady$.next({representations:t,textRepresentations:i}),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,i,a)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:i,thrown:a,category:r.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,i=l=>{e.error$.next({id:"DashProvider",category:r.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:l})},a=()=>{const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:l},n=je(this.video),o=(l,d)=>this.subscription.add(l.subscribe(d,i));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$),o(n.isAudioAvailable$,e.isAudioAvailable$),o(n.inPiP$,e.inPiP$),o(n.inFullscreen$,e.inFullscreen$),this.subscription.add(n.seeking$.subscribe(()=>{r.isNullable(this.params.desiredState.seekState.getState().state!==O.Applying)&&(this.videoState.getState()===V.PLAYING||this.videoState.getState()===V.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(rt(this.video,t.isLooped,i)),this.subscription.add(Ve(this.video,t.volume,n.volumeState$,i)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ze(this.video,t.playbackRate,n.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),o(Ti(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===V.READY&&this.videoState.setState(V.READY)},i)).add(n.pause$.subscribe(()=>{this.videoState.setState(V.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(V.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},i)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(V.METADATA_LOADED)},i)).add(n.currentBuffer$.subscribe(l=>{this.buffer.fill(),e.currentBuffer$.next(l)},i)).add(this.dashLiteEvents.error$.pipe(r.map(({id:l,message:d,thrown:u})=>({id:`DashLite_${l}`,category:r.ErrorCategory.WTF,message:d,thrown:u}))).subscribe(this.params.output.error$)).add(r.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$,r.fromEvent(this.video,"progress")).pipe(r.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(),b=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),S=this.elementSize$.getValue(),g=a();f&&this.params.desiredState.autoVideoTrackSwitching.setState(f.to);let m;if(!g&&r.isNonNullable(p))m=p;else{const v=tt(this.video.buffered,this.video.currentTime*1e3),E=g?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,y=Math.min(v/E,1);m=(d=Ht(h.map(({track:T})=>T),{container:S,throughput:b,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:y,playbackRate:this.video.playbackRate,current:(l=h.find(({representation:T})=>T===c))===null||l===void 0?void 0:l.track}))===null||d===void 0?void 0:d.id}return r.isNonNullable(m)?(u=h.find(({track:v})=>v.id===m))===null||u===void 0?void 0:u.representation:void 0}),r.filterChanged()).subscribe(this.currentRepresentation$,i)).add(r.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(r.filter(l=>l.to===V.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(r.filter(r.isNonNullable))}).pipe(r.once()).subscribe(()=>this.videoState.setState(V.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(r.filter(r.isNonNullable),r.filterChanged((l,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&a()?l.height<=d.height:l===d)).subscribe(l=>{const d=tt(this.video.buffered,this.video.currentTime*1e3),u=Math.min(d/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||u<=.5||!a())&&(this.dash.setQualityByRepresentation(l,!0),this.params.output.hostname$.next(oe(l.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(l=>{const{type:d,reused:u}=On(l);this.params.output.httpConnectionType$.next(d),this.params.output.httpConnectionReused$.next(u)})).add(this.dashLiteEvents.idxRequestPing$.pipe(r.once(),r.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,i)).add(this.dashLiteEvents.representationPlay$.pipe(r.filter(r.isNonNullable)).subscribe(this.handleRepresentationPlay,i)).add(r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ue(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return r.assertNever(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){We(this.video).then(e=>{e||(this.videoState.setState(V.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}}var ae;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(ae||(ae={}));var $i;(function(s){s.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",s.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})($i||($i={}));var ce;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(ce||(ce={}));var H;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(H||(H={}));var yt;(function(s){s.MP4="mp4",s.WEBM="webm"})(yt||(yt={}));var Ms=(s,e)=>{for(let t=0;t<s.length;t++)if(s.start(t)*1e3<=e&&s.end(t)*1e3>e)return!0;return!1};const qf=(s,e={})=>{const i=e.timeout||1,a=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-a-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},Yf=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",mr=Yf?qf:window.requestIdleCallback;var ls,us;let Mn=!1;try{Mn=r.getCurrentBrowser().browser===r.CurrentClientBrowser.Safari&&parseInt((us=(ls=navigator.userAgent.match(/Version\/(\d+)/))===null||ls===void 0?void 0:ls[1])!==null&&us!==void 0?us:"",10)<16}catch(s){console.error(s)}class Gf{constructor(e){this.bufferFull$=new r.Subject,this.error$=new r.Subject,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const i=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!i),this.currentTask=null}this.queue.length&&this.pull()}catch(i){this.error$.next({id:"BufferTaskQueueUnknown",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const a={operation:"append",data:e,signal:t,callback:i};this.queue.push(a),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(a=>{const n={operation:"remove",from:e,to:t,signal:i,callback:a};this.queue.unshift(n),this.pull()})}async abort(e){return new Promise(t=>{let i;Mn&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:a}of this.queue)a(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:i}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&i==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${i}`,category:r.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:r.assertNever(t)}}}var br=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};const Vn=new TextDecoder("ascii"),Fn=s=>{let e=0,t=s.getUint32(e);e+=4;const i=new DataView(s.buffer,s.byteOffset+e,4),a=Vn.decode(i);e+=4,t===0?t=1/0:t===1&&(e+=8,t=1/0);const n=Math.min(t,s.byteLength)-e,o=new DataView(s.buffer,s.byteOffset+e,n);return{id:a,size:t,contents:o}},zf=s=>Vn.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",Wf=(s,e,t)=>{const i=Fn(s),a=[];let n=0;const o=()=>{const S=i.contents.getUint32(n);return n+=4,S};if((o()&4278190080)!==0)throw new SyntaxError("Unsupported sidx version");o();const u=o(),c=o(),h=o(),f=o()&4294967295;let p=c/u*1e3,b=(t?t.to+1:s.byteOffset+s.byteLength)+h;for(let S=0;S<f;S++){const g=o(),m=g>>>31,v=g<<1>>>1,E=o();if(o(),m!==0)throw new Error("Unsupported multilevel sidx");const y=E/u*1e3;a.push({status:H.NONE,time:{from:p,to:p+y},byte:{from:b,to:b+v-1}}),p+=y,b+=v}return a},Qf=s=>{let e=0,t=!1,i=!1;for(;e<=s.byteLength&&!t;){const a=new DataView(s.buffer,s.byteOffset+e);try{const n=Fn(a);if(i||(i=n.id==="mdat"),e+n.size<=s.byteLength)e+=n.size;else break}catch(n){t=!0}}return e>0&&e<=s.byteLength&&i?new DataView(s.buffer,s.byteOffset,e):null},Jf={validateData:zf,parseInit:()=>null,getIndexRange:()=>{},parseSegments:Wf,parseFeedableSegmentChunk:Qf};var $;(function(s){s[s.EBML=440786851]="EBML",s[s.EBMLVersion=17030]="EBMLVersion",s[s.EBMLReadVersion=17143]="EBMLReadVersion",s[s.EBMLMaxIDLength=17138]="EBMLMaxIDLength",s[s.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",s[s.DocType=17026]="DocType",s[s.DocTypeVersion=17031]="DocTypeVersion",s[s.DocTypeReadVersion=17029]="DocTypeReadVersion",s[s.Void=236]="Void",s[s.Segment=408125543]="Segment",s[s.SeekHead=290298740]="SeekHead",s[s.Seek=19899]="Seek",s[s.SeekID=21419]="SeekID",s[s.SeekPosition=21420]="SeekPosition",s[s.Info=357149030]="Info",s[s.TimestampScale=2807729]="TimestampScale",s[s.Duration=17545]="Duration",s[s.Tracks=374648427]="Tracks",s[s.Chapters=272869232]="Chapters",s[s.Cluster=524531317]="Cluster",s[s.Timestamp=231]="Timestamp",s[s.SilentTracks=22612]="SilentTracks",s[s.SilentTrackNumber=22743]="SilentTrackNumber",s[s.Position=167]="Position",s[s.PrevSize=171]="PrevSize",s[s.SimpleBlock=163]="SimpleBlock",s[s.BlockGroup=160]="BlockGroup",s[s.EncryptedBlock=175]="EncryptedBlock",s[s.Attachments=423732329]="Attachments",s[s.Tags=307544935]="Tags",s[s.Cues=475249515]="Cues",s[s.CuePoint=187]="CuePoint",s[s.CueTime=179]="CueTime",s[s.CueTrackPositions=183]="CueTrackPositions",s[s.CueTrack=247]="CueTrack",s[s.CueClusterPosition=241]="CueClusterPosition",s[s.CueRelativePosition=240]="CueRelativePosition",s[s.CueDuration=178]="CueDuration",s[s.CueBlockNumber=21368]="CueBlockNumber",s[s.CueCodecState=234]="CueCodecState",s[s.CueReference=219]="CueReference",s[s.CueRefTime=150]="CueRefTime"})($||($={}));var w;(function(s){s.SignedInteger="int",s.UnsignedInteger="uint",s.Float="float",s.String="string",s.UTF8="utf8",s.Date="date",s.Master="master",s.Binary="binary"})(w||(w={}));const vr={[$.EBML]:{type:w.Master},[$.EBMLVersion]:{type:w.UnsignedInteger},[$.EBMLReadVersion]:{type:w.UnsignedInteger},[$.EBMLMaxIDLength]:{type:w.UnsignedInteger},[$.EBMLMaxSizeLength]:{type:w.UnsignedInteger},[$.DocType]:{type:w.String},[$.DocTypeVersion]:{type:w.UnsignedInteger},[$.DocTypeReadVersion]:{type:w.UnsignedInteger},[$.Void]:{type:w.Binary},[$.Segment]:{type:w.Master},[$.SeekHead]:{type:w.Master},[$.Seek]:{type:w.Master},[$.SeekID]:{type:w.Binary},[$.SeekPosition]:{type:w.UnsignedInteger},[$.Info]:{type:w.Master},[$.TimestampScale]:{type:w.UnsignedInteger},[$.Duration]:{type:w.Float},[$.Tracks]:{type:w.Master},[$.Chapters]:{type:w.Master},[$.Cluster]:{type:w.Master},[$.Timestamp]:{type:w.UnsignedInteger},[$.SilentTracks]:{type:w.Master},[$.SilentTrackNumber]:{type:w.UnsignedInteger},[$.Position]:{type:w.UnsignedInteger},[$.PrevSize]:{type:w.UnsignedInteger},[$.SimpleBlock]:{type:w.Binary},[$.BlockGroup]:{type:w.Master},[$.EncryptedBlock]:{type:w.Binary},[$.Attachments]:{type:w.Master},[$.Tags]:{type:w.Master},[$.Cues]:{type:w.Master},[$.CuePoint]:{type:w.Master},[$.CueTime]:{type:w.UnsignedInteger},[$.CueTrackPositions]:{type:w.Master},[$.CueTrack]:{type:w.UnsignedInteger},[$.CueClusterPosition]:{type:w.UnsignedInteger},[$.CueRelativePosition]:{type:w.UnsignedInteger},[$.CueDuration]:{type:w.UnsignedInteger},[$.CueBlockNumber]:{type:w.UnsignedInteger},[$.CueCodecState]:{type:w.UnsignedInteger},[$.CueReference]:{type:w.Master},[$.CueRefTime]:{type:w.UnsignedInteger}},Un=s=>{const e=s.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=ki(s,t),a=i in vr,n=a?vr[i].type:w.Binary,o=s.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(s.buffer,s.byteOffset+t+1,l-1),u=o&255>>l,c=ki(d),h=u*2**((l-1)*8)+c,f=t+l;let p;return f+h>s.byteLength?p=new DataView(s.buffer,s.byteOffset+f):p=new DataView(s.buffer,s.byteOffset+f,h),{tag:a?i:"0x"+i.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:p,valueSize:h}},ki=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{const t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ne=(s,e)=>{switch(e){case w.SignedInteger:return s.getInt8(0);case w.UnsignedInteger:return ki(s);case w.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case w.String:return new TextDecoder("ascii").decode(s);case w.UTF8:return new TextDecoder("utf-8").decode(s);case w.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case w.Master:return s;case w.Binary:return s;default:r.assertNever(e)}},Yt=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),a=Un(i);if(!e(a))return;a.type===w.Master&&Yt(a.value,e),t=a.value.byteOffset-s.byteOffset+a.valueSize}},Kf=s=>{if(s.getUint32(0)!==$.EBML)return!1;let e,t,i;const a=Un(s);return Yt(a.value,({tag:n,type:o,value:l})=>(n===$.EBMLReadVersion?e=Ne(l,o):n===$.DocType?t=Ne(l,o):n===$.DocTypeReadVersion&&(i=Ne(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},jn=[$.Info,$.SeekHead,$.Tracks,$.Chapters,$.Cluster,$.Cues,$.Attachments,$.Tags],Xf=[$.Timestamp,$.SilentTracks,$.SilentTrackNumber,$.Position,$.PrevSize,$.SimpleBlock,$.BlockGroup,$.EncryptedBlock],Zf=s=>{let e,t,i,a,n=!1,o=!1,l=!1,d,u;return Yt(s,({tag:c,type:h,value:f,valueSize:p})=>{if(c===$.SeekID){const b=Ne(f,h);u=ki(b)}else c!==$.SeekPosition&&(u=void 0);return c===$.Segment?(e=f.byteOffset,t=f.byteOffset+p):c===$.Info?n=!0:c===$.SeekHead?o=!0:c===$.TimestampScale?i=Ne(f,h):c===$.Duration?a=Ne(f,h):c===$.SeekPosition&&u===$.Cues?d=Ne(f,h):n&&o&&jn.includes(c)&&(l=!0),!l}),r.assertNonNullable(e,"Failed to parse webm Segment start"),r.assertNonNullable(t,"Failed to parse webm Segment end"),r.assertNonNullable(a,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(a/1e9*i*1e3),cuesSeekPosition:d}},ep=s=>{if(r.isNullable(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},tp=(s,e)=>{let t=!1,i=!1;const a=l=>r.isNonNullable(l.time)&&r.isNonNullable(l.position),n=[];let o;return Yt(s,({tag:l,type:d,value:u})=>{switch(l){case $.Cues:t=!0;break;case $.CuePoint:o&&a(o)&&n.push(o),o={};break;case $.CueTime:o&&(o.time=Ne(u,d));break;case $.CueTrackPositions:break;case $.CueClusterPosition:o&&(o.position=Ne(u,d));break;default:t&&jn.includes(l)&&(i=!0)}return!(t&&i)}),o&&a(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}}})},ip=s=>{let e=0,t=!1;try{Yt(s,i=>i.tag===$.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Xf.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[$.SimpleBlock,$.BlockGroup,$.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},sp={validateData:Kf,parseInit:Zf,getIndexRange:ep,parseSegments:tp,parseFeedableSegmentChunk:ip};class Sr{constructor(e,t,i,a,{fetcher:n,tuning:o,getCurrentPosition:l,compatibilityMode:d=!1}){switch(this.onLastSegment$=new r.ValueSubject(!1),this.fullyBuffered$=new r.ValueSubject(!1),this.playingRepresentation$=new r.ValueSubject(void 0),this.error$=new r.Subject,this.gaps=[],this.subscription=new r.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new it,this.destroyAbortController=new it,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=r.abortable(this.destroyAbortController.signal,async function*(u){const c=this.representations.get(u);r.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 Gf(this.sourceBuffer),this.subscription.add(r.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},b=>this.error$.next({id:"SegmentEjection",category:r.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:b}))),this.subscription.add(r.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:r.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(b=>{if(!this.sourceBuffer)return;const S=Math.min(this.bufferLimit,br(this.sourceBuffer.buffered)*.8);this.bufferLimit=S,this.pruneBuffer(this.getCurrentPosition(),b)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(b=>this.error$.next(b))),yield this.loadInit(c,"high",!0);const h=this.initData.get(c.id),f=this.segments.get(c.id);if(r.assertNonNullable(h,"No init buffer for starting representation"),r.assertNonNullable(f,"No segments for starting representation"),!(h instanceof ArrayBuffer))return;let p=0;for(const b of f)b.time.from-p>0&&this.gaps.push({representation:c.id,from:p,to:b.time.from}),p=b.time.to;r.isNonNullable(c.duration)&&c.duration-p>0&&this.gaps.push({representation:c.id,from:p,to:c.duration}),yield this.sourceBufferTaskQueue.append(h,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId)}.bind(this)),this.switchTo=r.abortable(this.destroyAbortController.signal,async function*(u){if(u===this.downloadingRepresentationId||u===this.switchingToRepresentationId)return;this.switchingToRepresentationId=u;const c=this.representations.get(u);r.assertNonNullable(c,`No such representation ${u}`);let h=this.initData.get(u);if(r.isNullable(h)?yield this.loadInit(c,"high",!1):h instanceof Promise&&(yield h),h=this.initData.get(u),!h||!(h instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=u,this.abort(),yield this.sourceBufferTaskQueue.append(h,this.downloadAbortController.signal);const f=this.getCurrentPosition();r.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=i,i){case yt.MP4:this.containerParser=Jf;break;case yt.WEBM:this.containerParser=sp;break;default:r.assertNever(i)}this.initData=new Map(a.map(u=>[u.id,null])),this.segments=new Map,this.representations=new Map(a.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 it,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(r.isNullable(e)||r.isNullable(this.downloadingRepresentationId)||r.isNullable(this.playingRepresentationId)||r.isNullable(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(r.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const a=i.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=tt(this.sourceBuffer.buffered,e),h=a?a.time.to+100:-1/0;a&&c>=a.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&br(this.sourceBuffer.buffered)>=this.bufferLimit){const u=tt(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(i,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(l.includes(a))u="high";else{const c=Re(l,0);c&&c.time.from-a.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status===H.FED&&!l.length&&tt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=Re(i,-1);d&&d.status===H.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(a===d))}findSegmentStartTime(e){var t,i,a;const n=(i=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&i!==void 0?i: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(a=l==null?void 0:l.time.from)!==null&&a!==void 0?a:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){const a=e.findIndex(({status:h,time:{from:f,to:p}},b)=>{const S=f<=i&&p>=i,g=f>i||S||b===0&&i===0,m=Math.min(this.forwardBufferTarget,this.bufferLimit),v=this.preloadOnly&&f<=i+m||p<=i+m;return(h===H.NONE||h===H.PARTIALLY_EJECTED&&g&&v&&this.sourceBuffer&&!Ms(this.sourceBuffer.buffered,i))&&g&&v});if(a===-1)return[];if(t!==ce.BYTE_RANGE)return e.slice(a,a+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=a;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}async loadSegments(e,t,i="auto"){if(!e.length)return;let a,n,o=e;const{type:l}=t.segmentReference;switch(l){case ce.BYTE_RANGE:{a=t.segmentReference.url,n={from:Re(e,0).byte.from,to:Re(e,-1).byte.to};break}case ce.TEMPLATE:{const u=Re(e,0);a=new URL(u.url,t.segmentReference.baseUrl).toString(),o=[u];break}default:r.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&&(await r.abortable(d,async function*(){const u=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield 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(a,{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:r.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}},signal:d,priority:i}).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 i=!1;const a=this.getCurrentPosition();this.sourceBuffer&&r.isNonNullable(a)&&(i=tt((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,a)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,i||this.error$.next({id:"SegmentDownload",category:r.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,i,a,n){if(!this.activeSegments.size)return;const o=()=>{this.abort()},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 b of(f=this.segments.get(p.id))!==null&&f!==void 0?f:[])b.status===H.FED&&b.time.from===h.segment.time.from&&b.time.to===h.segment.time.to&&(b.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===ce.BYTE_RANGE,b=p?f.byte.to-f.byte.from+1:c;if(h.representationId!==t||!(!p||f.byte.from>=i&&f.byte.to<i+e.byteLength))continue;if(n.aborted){o();continue}const g=p?f.byte.from-i:0,m=p?f.byte.to-i:e.byteLength,v=g<a,E=m<=a;if(f.status===H.DOWNLOADING&&v&&E){f.status=H.DOWNLOADED,this.activeSegments.delete(h);const y=new DataView(e.buffer,e.byteOffset+g,b);this.sourceBufferTaskQueue.append(y,n).then(T=>T&&!n.aborted?l(h):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&v&&(h.loadedBytes=Math.min(b,a-g),h.loadedBytes>h.feedingBytes)){const y=new DataView(e.buffer,e.byteOffset+g+h.feedingBytes,h.loadedBytes-h.feedingBytes),T=h.loadedBytes===b?y:this.containerParser.parseFeedableSegmentChunk(y);T!=null&&T.byteLength&&(f.status=H.PARTIALLY_FED,h.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,n).then(A=>{if(n.aborted)o();else if(A)h.fedBytes+=T.byteLength,h.fedBytes===b&&l(h);else{if(h.feedingBytes<b)return;o()}}))}}}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[a,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=mr(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const a=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!i&&this.failedDownloads>0?r.abortable(this.destroyAbortController.signal,async function*(){const l=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,l))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,a)).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),i&&this.error$.next({id:"LoadInits",category:r.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o}async pruneBuffer(e,t,i=!1){if(!this.sourceBuffer||!this.playingRepresentationId||r.isNullable(e)||this.sourceBuffer.updating)return!1;let a=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;a+=h};for(const u of this.segments.values())for(const c of u){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;c.status===H.FED&&d(c)}if(l=isFinite(n)&&isFinite(o),!l){a=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)||a>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&&i){a=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 i of t){let a={representation:e,from:i.time.from,to:i.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<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&l>=i.time.to){a=void 0;break}l>i.time.from&&l<i.time.to&&(a.from=l),o<i.time.to&&o>i.time.from&&(a.to=o)}}a&&a.to-a.from>=1&&!this.gaps.some(n=>a&&n.from===a.from&&n.to===a.to)&&this.gaps.push(a)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=mr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:r.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(r.isNullable(this.sourceBuffer)||r.isNullable(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const a=Math.round(this.sourceBuffer.buffered.start(i)*1e3),n=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:a,to:n})}const t=1;for(const i of this.segments.values())for(const a of i){const{status:n}=a;if(n!==H.FED&&n!==H.PARTIALLY_EJECTED)continue;const o=Math.floor(a.time.from),l=Math.ceil(a.time.to),d=e.some(c=>c.from-t<=o&&c.to+t>=l),u=e.filter(c=>o>=c.from-t&&o<=c.to+t||l>=c.from-t&&l<=c.to+t);d||(u.length===1?a.status=H.PARTIALLY_EJECTED:a.status=H.NONE)}}}var mt;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(mt||(mt={}));class ap{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new r.ValueSubject(void 0),this.lastConnectionReused$=new r.ValueSubject(void 0),this.lastRequestFirstBytes$=new r.ValueSubject(void 0),this.abortAllController=new it,this.subscription=new r.Subscription,this.fetchManifest=r.abortable(this.abortAllController.signal,async function*(a){let n=a;this.requestQuic&&(n=gt(n));const o=yield St(n,{signal:this.abortAllController.signal}).catch(Lt);return o?(this.onHeadersReceived(o.headers),o.text()):null}.bind(this)),this.fetch=r.abortable(this.abortAllController.signal,async function*(a,{rangeMethod:n=this.compatibilityMode?mt.HEADER:mt.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0}={}){var h,f,p,b;let S=a;const g=new Headers;if(o)switch(n){case mt.HEADER:{g.append("Range",`bytes=${o.from}-${o.to}`);break}case mt.PARAM:{const k=new URL(S,location.href);k.searchParams.append("bytes",`${o.from}-${o.to}`),S=k.toString();break}default:r.assertNever(n)}this.requestQuic&&(S=gt(S));let m=this.abortAllController.signal;if(u){const k=new it;if(this.subscription.add(r.merge(r.fromEvent(this.abortAllController.signal,"abort"),r.fromEvent(u,"abort")).subscribe(()=>{try{k.abort()}catch(N){Lt(N)}})),this.abortAllController.signal.aborted||u.aborted)try{k.abort()}catch(N){Lt(N)}m=k.signal}const v=r.now(),E=yield St(S,{priority:d,headers:g,signal:m}).catch(Lt),y=r.now();if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(y-v),!E)return null;if(!E.ok||!E.body)return Promise.reject(new Error(`Fetch error ${E.status}: ${E.statusText}`));this.onHeadersReceived(E.headers);const T=parseInt((f=E.headers.get("Content-Length"))!==null&&f!==void 0?f:"",10)||o&&o.to-o.from+1||NaN;if(!T){const k=yield E.arrayBuffer();return(p=this.throughputEstimator)===null||p===void 0||p.addRawSpeed(k.byteLength,r.now()-y),l==null||l(new DataView(k),k.byteLength),k}if(!l&&!c)return E.arrayBuffer();const[A,L]=E.body.tee(),R=A.getReader();c&&((b=this.throughputEstimator)===null||b===void 0||b.trackStream(L));let D=0;const M=new ArrayBuffer(T),I=new Uint8Array(M),_=new DataView(M);let j=!1;const W=k=>{j=!0,Lt(k)},te=r.abortable(m,async function*({done:k,value:N}){D===0&&this.lastRequestFirstBytes$.next(r.now()-v),!m.aborted&&!k&&N&&(I.set(N,D),D+=N.byteLength,l==null||l(_,D),yield R==null?void 0:R.read().then(te,W))}.bind(this));return yield R==null?void 0:R.read().then(te,W),j?null:M}.bind(this)),this.fetchByteRangeRepresentation=r.abortable(this.abortAllController.signal,async function*(a,n,o){var l;if(a.type!==ce.BYTE_RANGE)return null;const{from:d,to:u}=a.initRange;let c=d,h=u,f=!1,p,b;a.indexRange&&(p=a.indexRange.from,b=a.indexRange.to,f=u+1===p,f&&(c=Math.min(p,d),h=Math.max(b,u))),c=Math.min(c,0);const S=yield this.fetch(a.url,{range:{from:c,to:h},priority:o,measureThroughput:!1});if(!S)return null;const g=new DataView(S,d-c,u-c+1);if(!n.validateData(g))throw new Error("Invalid media file");const m=n.parseInit(g),v=(l=a.indexRange)!==null&&l!==void 0?l:n.getIndexRange(m);if(!v)throw new ReferenceError("No way to load representation index");let E;if(f)E=new DataView(S,v.from-c,v.to-v.from+1);else{const T=yield this.fetch(a.url,{range:v,priority:o,measureThroughput:!1});if(!T)return null;E=new DataView(T)}const y=n.parseSegments(E,m,v);return{dataView:new DataView(S),segments:y}}.bind(this)),this.fetchTemplateRepresentation=r.abortable(this.abortAllController.signal,async function*(a,n){if(a.type!==ce.TEMPLATE)return null;const o=new URL(a.initUrl,a.baseUrl).toString(),l=yield this.fetch(o,{priority:n,measureThroughput:!1});return l?{segments:a.segments.map(u=>({...u,status:H.NONE,size:void 0})),dataView:new DataView(l)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=On(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var a,n;const{type:o}=e;switch(o){case ce.BYTE_RANGE:return(a=await this.fetchByteRangeRepresentation(e,t,i))!==null&&a!==void 0?a:null;case ce.TEMPLATE:return(n=await this.fetchTemplateRepresentation(e,i))!==null&&n!==void 0?n:null;default:r.assertNever(o)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Lt=s=>{if(!(s instanceof DOMException)||!(s.name==="AbortError"||s.code===20))throw s};var rp=st,np=Ai,op=ge,lp=op("match"),up=function(s){var e;return rp(s)&&((e=s[lp])!==void 0?!!e:np(s)=="RegExp")},dp=Ni,cp=String,hp=function(s){if(dp(s)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return cp(s)},fp=at,pp=function(){var s=fp(this),e="";return s.hasIndices&&(e+="d"),s.global&&(e+="g"),s.ignoreCase&&(e+="i"),s.multiline&&(e+="m"),s.dotAll&&(e+="s"),s.unicode&&(e+="u"),s.unicodeSets&&(e+="v"),s.sticky&&(e+="y"),e},mp=Be,bp=Me,vp=Hs,Sp=pp,gr=RegExp.prototype,gp=function(s){var e=s.flags;return e===void 0&&!("flags"in gr)&&!bp(s,"flags")&&vp(gr,s)?mp(Sp,s):e},aa=Oe,yp=Ri,Tp=Math.floor,ds=aa("".charAt),Ep=aa("".replace),cs=aa("".slice),$p=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,kp=/\$([$&'`]|\d{1,2})/g,Pp=function(s,e,t,i,a,n){var o=t+s.length,l=i.length,d=kp;return a!==void 0&&(a=yp(a),d=$p),Ep(n,d,function(u,c){var h;switch(ds(c,0)){case"$":return"$";case"&":return s;case"`":return cs(e,0,t);case"'":return cs(e,o);case"<":h=a[cs(c,1,-1)];break;default:var f=+c;if(f===0)return u;if(f>l){var p=Tp(f/10);return p===0?u:p<=l?i[p-1]===void 0?ds(c,1):i[p-1]+ds(c,1):u}h=i[f-1]}return h===void 0?"":h})},Ap=Di,wp=Be,ra=Oe,yr=Fs,_p=he,Rp=wi,Ip=up,ht=hp,Dp=_i,Np=gp,Cp=Pp,Lp=ge,xp=Lp("replace"),Op=TypeError,Hn=ra("".indexOf),Bp=ra("".replace),Tr=ra("".slice),Mp=Math.max,Er=function(s,e,t){return t>s.length?-1:e===""?t:Hn(s,e,t)};Ap({target:"String",proto:!0},{replaceAll:function(e,t){var i=yr(this),a,n,o,l,d,u,c,h,f,p=0,b=0,S="";if(!Rp(e)){if(a=Ip(e),a&&(n=ht(yr(Np(e))),!~Hn(n,"g")))throw Op("`.replaceAll` does not allow non-global regexes");if(o=Dp(e,xp),o)return wp(o,e,i,t);if(a)return Bp(ht(i),e,t)}for(l=ht(i),d=ht(e),u=_p(t),u||(t=ht(t)),c=d.length,h=Mp(1,c),p=Er(l,d,0);p!==-1;)f=u?ht(t(d,p,l)):Cp(d,l,p,[],void 0,t),S+=Tr(l,b,p)+f,b=p+c,p=Er(l,d,p+h);return b<l.length&&(S+=Tr(l,b)),S}});var Vp=Ln,Fp=Vp("String","replaceAll"),Up=Fp,jp=Up,Hp=jp,qp=Hp,$r=qp;const kr=s=>{if(!s.startsWith("P"))return;const e=(o,l)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*l},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),a=(i==null?void 0:i[1])==="-"?-1:1,n={days:e(i==null?void 0:i[5],a),hours:e(i==null?void 0:i[6],a),minutes:e(i==null?void 0:i[7],a),seconds:e(i==null?void 0:i[8],a)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},hs=(s,e)=>{let t=s;t=$r(t,"$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[a,n]of Object.entries(i)){const o=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=$r(t,o,(l,d)=>r.isNullable(n)?l:r.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},Yp=(s,e)=>{var t,i,a,n,o,l,d,u,c,h,f,p,b,S,g,m,v,E,y,T,A,L,R,D,M,I,_,j,W,te,k,N,G,X,ie,le,ye,He,F,se;const pe=new DOMParser().parseFromString(s,"application/xml"),_e={video:[],audio:[],text:[]},Qe=pe.children[0],qe=Qe.getElementsByTagName("Period")[0],nt=qe.children;let Te;const $t=Qe.getAttribute("mediaPresentationDuration"),na=qe.getAttribute("duration");if($t)Te=kr($t);else if(na){const me=kr(na);r.isNonNullable(me)&&(Te=me)}let Jn=0;const xi=(i=(t=Qe.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],Kn=xi.includes($i.WEBM_AS_IN_FFMPEG)||xi.includes($i.WEBM_AS_IN_SPEC)?yt.WEBM:yt.MP4;for(const me of nt){const Gt=me.getAttribute("mimeType"),Xn=me.getAttribute("codecs"),oa=(a=me.getAttribute("contentType"))!==null&&a!==void 0?a:Gt==null?void 0:Gt.split("/")[0],Zn=(o=(n=me.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],la=me.querySelectorAll("Representation"),eo=me.querySelector("SegmentTemplate");if(oa===ae.TEXT){for(const Z of la){const Je=Z.getAttribute("id")||"",zt=me.getAttribute("lang"),ot=(u=(d=(l=Z.querySelector("BaseURL"))===null||l===void 0?void 0:l.textContent)===null||d===void 0?void 0:d.trim())!==null&&u!==void 0?u:"",Oi=new URL(ot,e).toString();_e[ae.TEXT].push({id:Je,lang:zt,kind:ae.TEXT,url:Oi})}continue}for(const Z of la){const Je=(c=Z.getAttribute("mimeType"))!==null&&c!==void 0?c:Gt,zt=(f=(h=Z.getAttribute("codecs"))!==null&&h!==void 0?h:Xn)!==null&&f!==void 0?f:"",ot=(b=(p=Z.getAttribute("contentType"))!==null&&p!==void 0?p:Je==null?void 0:Je.split("/")[0])!==null&&b!==void 0?b:oa,Oi=(g=(S=me.getAttribute("profiles"))===null||S===void 0?void 0:S.split(","))!==null&&g!==void 0?g:[],to=parseInt((m=Z.getAttribute("width"))!==null&&m!==void 0?m:"",10),ua=parseInt((v=Z.getAttribute("height"))!==null&&v!==void 0?v:"",10),da=parseInt((E=Z.getAttribute("bandwidth"))!==null&&E!==void 0?E:"",10)/1e3,ca=(y=Z.getAttribute("frameRate"))!==null&&y!==void 0?y:"",io=(T=Z.getAttribute("quality"))!==null&&T!==void 0?T:void 0,so=ca?ia(ca):void 0,ao=(A=Z.getAttribute("id"))!==null&&A!==void 0?A:(Jn++).toString(10),ro=ot==="video"?`${ua}p`:ot==="audio"?`${da}Kbps`:zt,no=`${ao}@${ro}`,oo=(D=(R=(L=Z.querySelector("BaseURL"))===null||L===void 0?void 0:L.textContent)===null||R===void 0?void 0:R.trim())!==null&&D!==void 0?D:"",ha=new URL(oo,e).toString(),lo=[...xi,...Zn,...Oi];let Bi;const uo=Z.querySelector("SegmentBase"),Ke=(M=Z.querySelector("SegmentTemplate"))!==null&&M!==void 0?M:eo;if(uo){const kt=(_=(I=Z.querySelector("SegmentBase Initialization"))===null||I===void 0?void 0:I.getAttribute("range"))!==null&&_!==void 0?_:"",[Pt,Vi]=kt.split("-").map(Xe=>parseInt(Xe,10)),At={from:Pt,to:Vi},wt=(j=Z.querySelector("SegmentBase"))===null||j===void 0?void 0:j.getAttribute("indexRange"),[Fi,Wt]=wt?wt.split("-").map(Xe=>parseInt(Xe,10)):[],_t=wt?{from:Fi,to:Wt}:void 0;Bi={type:ce.BYTE_RANGE,url:ha,initRange:At,indexRange:_t}}else if(Ke){const kt={representationId:(W=Z.getAttribute("id"))!==null&&W!==void 0?W:void 0,bandwidth:(te=Z.getAttribute("bandwidth"))!==null&&te!==void 0?te:void 0},Pt=parseInt((k=Ke.getAttribute("timescale"))!==null&&k!==void 0?k:"",10),Vi=(N=Ke.getAttribute("initialization"))!==null&&N!==void 0?N:"",At=Ke.getAttribute("media"),wt=(X=parseInt((G=Ke.getAttribute("startNumber"))!==null&&G!==void 0?G:"",10))!==null&&X!==void 0?X:1,Fi=hs(Vi,kt);if(!At)throw new ReferenceError("No media attribute in SegmentTemplate");const Wt=(ie=Ke.querySelectorAll("SegmentTimeline S"))!==null&&ie!==void 0?ie:[],_t=[];if(Wt.length){let Xe=wt,Ze=0;for(const Rt of Wt){const lt=parseInt((le=Rt.getAttribute("d"))!==null&&le!==void 0?le:"",10)*1e3,It=parseInt((ye=Rt.getAttribute("r"))!==null&&ye!==void 0?ye:"",10)||0,Dt=(F=parseInt((He=Rt.getAttribute("t"))!==null&&He!==void 0?He:"",10))!==null&&F!==void 0?F:void 0;for(let fa=0;fa<It+1;fa++){const co=hs(At,{...kt,segmentNumber:Xe.toString(10),segmentTime:Dt.toString(10)}),ho=Dt?Dt/Pt:Ze;Ze+=lt/Pt;const fo=Ze;Xe++,_t.push({time:{from:ho,to:fo},url:co})}}}else if(r.isNonNullable(Te)){const Ze=parseInt((se=Ke.getAttribute("duration"))!==null&&se!==void 0?se:"",10)/Pt*1e3,Rt=Math.ceil(Te/Ze);let lt=0;for(let It=1;It<Rt;It++){const Dt=hs(At,{...kt,segmentNumber:It.toString(10),segmentTime:lt.toString(10)});_t.push({time:{from:lt,to:lt+Ze},url:Dt}),lt+=Ze}}Bi={type:ce.TEMPLATE,baseUrl:ha,initUrl:Fi,segments:_t}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ot||!Je)continue;const Mi={video:ae.VIDEO,audio:ae.AUDIO,text:ae.TEXT}[ot];Mi&&_e[Mi].push({id:no,kind:Mi,segmentReference:Bi,profiles:lo,duration:Te,bitrate:da,mime:Je,codecs:zt,width:to,height:ua,fps:so,quality:io})}}return{duration:Te,container:Kn,representations:_e}},Gp=["timeupdate","progress","play","seeked","stalled","waiting"];var de;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(de||(de={}));let zp=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new r.Subscription,this.state$=new Q(de.NONE),this.currentVideoRepresentation$=new r.ValueSubject(void 0),this.error$=new r.Subject,this.lastConnectionType$=new r.ValueSubject(void 0),this.lastConnectionReused$=new r.ValueSubject(void 0),this.lastRequestFirstBytes$=new r.ValueSubject(void 0),this.forceEnded$=new r.Subject,this.gapWatchdogStarted=!1,this.destroyController=new it,this.initManifest=r.abortable(this.destroyController.signal,async function*(t,i){this.element=t,this.state$.startTransitionTo(de.MANIFEST_READY);const a=yield this.fetcher.fetchManifest(i).catch(l=>this.error$.next({id:"LoadManifest",category:r.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:l}));if(!a)return;let n;try{n=Yp(a!=null?a:"",i)}catch(l){this.error$.next({id:"ManifestParsing",category:r.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:l})}if(!n)return;const o=({kind:l,mime:d,codecs:u})=>{var c,h,f;return Boolean(((c=t.canPlayType)===null||c===void 0?void 0:c.call(t,d))&&((f=(h=window.MediaSource)===null||h===void 0?void 0:h.isTypeSupported)===null||f===void 0?void 0:f.call(h,`${d}; codecs="${u}"`))||l===ae.TEXT)};this.manifest={...n,representations:jt(Object.entries(n.representations).map(([l,d])=>[l,d.filter(o)]))},this.manifest.representations.video.length?this.state$.setState(de.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:r.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this)),this.initRepresentations=r.abortable(this.destroyController.signal,async function*(t,i){r.assertNonNullable(this.manifest),r.assertNonNullable(this.element),this.state$.startTransitionTo(de.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const a={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0};this.videoBufferManager=new Sr(ae.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,a),this.bufferManagers=[this.videoBufferManager],r.isNonNullable(i)&&(this.audioBufferManager=new Sr(ae.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,a),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=r.merge(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(r.map(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),o=r.merge(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(r.map(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.subscription.add(r.merge(this.forceEnded$,r.combine({allBuffersFull:n,someBufferEnded:o}).pipe(r.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:r.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.subscription.add(r.merge(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.source.readyState!=="open"&&(yield new Promise(l=>{var d;return(d=this.source)===null||d===void 0?void 0:d.addEventListener("sourceopen",l)})),r.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&r.isNonNullable(i)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)]):yield this.videoBufferManager.startWith(t),this.state$.setState(de.REPRESENTATIOS_READY)}.bind(this)),this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;const a=this.element.currentTime*1e3;this.videoBufferManager.maintain(a),(t=this.audioBufferManager)===null||t===void 0||t.maintain(a),(this.videoBufferManager.gaps.length||!((i=this.audioBufferManager)===null||i===void 0)&&i.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=r.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),n=>{this.error$.next({id:"GapWatchdog",category:r.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new ap({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initBuffer(){r.assertNonNullable(this.element),this.state$.setState(de.RUNNING),this.subscription.add(r.merge(...Gp.map(e=>r.fromEvent(this.element,e)),r.fromEvent(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:r.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(r.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(r.fromEvent(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Ms(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){const i={[ae.VIDEO]:this.videoBufferManager,[ae.AUDIO]:this.audioBufferManager,[ae.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)}seek(e,t){var i,a,n,o,l;r.assertNonNullable(this.element),r.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((i=this.videoBufferManager.findSegmentStartTime(e))!==null&&i!==void 0?i:e,(n=(a=this.audioBufferManager)===null||a===void 0?void 0:a.findSegmentStartTime(e))!==null&&n!==void 0?n:e),Ms(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(de.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)===null||e===void 0?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3,t=[];for(const i of this.bufferManagers)for(const a of i.gaps)i.playingRepresentation$.getValue()===a.representation&&a.from<=e&&a.to>e&&(this.element.duration*1e3-a.to<this.tuning.endGapTolerance?t.push(1/0):t.push(a.to));if(t.length){const i=Math.max(...t);i===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=i/1e3}}};var J;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(J||(J={}));const Wp=({id:s,width:e,height:t,bitrate:i,fps:a,quality:n})=>{var o;const l=(o=n?qt(n):void 0)!==null&&o!==void 0?o:r.videoSizeToQuality({width:e,height:t});return l&&{id:s,quality:l,bitrate:i,size:{width:e,height:t},fps:a}},Qp=({id:s,bitrate:e})=>({id:s,bitrate:e}),Jp=({id:s,lang:e,url:t,isAuto:i})=>({id:s,url:t,isAuto:i,type:"internal",language:e}),Kp=(s,e,t)=>{var i;const a=e.indexOf(t);return(i=Re(s,Math.round(s.length*a/e.length)))!==null&&i!==void 0?i:Re(s,-1)};class Xp{constructor(e){this.subscription=new r.Subscription,this.videoState=new Q(J.STOPPED),this.elementSize$=new r.ValueSubject(void 0),this.textTracksManager=new we,this.videoTracks=[],this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new yf,this.textTracks=[],this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(n.state===O.Requested&&(a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&t!==J.STOPPED&&i!==exports.PlaybackState.STOPPED&&this.seek(n.position,n.forcePrecise),i===exports.PlaybackState.STOPPED){t!==J.STOPPED&&(this.videoState.startTransitionTo(J.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(J.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(t){case J.STOPPED:this.videoState.startTransitionTo(J.READY),this.prepare();return;case J.READY:i===exports.PlaybackState.PAUSED?(this.videoState.setState(J.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===exports.PlaybackState.READY&&P(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case J.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(J.PAUSED),this.video.pause()):(a==null?void 0:a.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case J.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(t)}}},this.params=e,this.video=Fe(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new zp({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=je(this.video),a=u=>{e.error$.next({id:"DashVKProvider",category:r.ErrorCategory.WTF,message:"DashVKProvider internal logic error",thrown:u})},n=(u,c)=>this.subscription.add(u.subscribe(c,a));n(i.timeUpdate$,e.position$),n(i.durationChange$,e.duration$),n(i.ended$,e.endedEvent$),n(i.looped$,e.loopedEvent$),n(i.error$,e.error$),n(i.isBuffering$,e.isBuffering$),n(i.currentBuffer$,e.currentBuffer$),n(i.playing$,e.firstFrameEvent$),n(i.canplay$,e.canplay$),n(i.isAudioAvailable$,e.isAudioAvailable$),n(i.inPiP$,e.inPiP$),n(i.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.lastRequestFirstBytes$.pipe(r.filter(r.isNonNullable),r.once()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(rt(this.video,t.isLooped,a)),this.subscription.add(Ve(this.video,t.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(ze(this.video,t.playbackRate,i.playbackRateState$,a)),n(Ti(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(J.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},a)).add(i.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},a)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===J.PLAYING&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var c;if(u===de.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();r.assertNonNullable(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((g,m)=>m.bitrate-g.bitrate),p=Array.from(h.video).sort((g,m)=>m.bitrate-g.bitrate),b=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const g of f){const m=Qp(g);m&&this.audioTracks.push({track:m,representation:g})}for(const g of p){const m=Wp(g);if(m){this.videoTracks.push({track:m,representation:g});const v=!this.params.tuning.isAudioDisabled&&Kp(f,p,g);v&&this.audioRepresentations.set(g.id,v)}}for(const g of b){const m=Jp(g);m&&this.textTracks.push({track:m,representation:g})}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:g})=>g)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:g})=>g)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:g})=>g));const S=this.selectVideoRepresentation();r.assertNonNullable(S),this.player.initRepresentations(S.id,(c=this.audioRepresentations.get(S.id))===null||c===void 0?void 0:c.id)}else u===de.REPRESENTATIOS_READY&&(this.videoState.setState(J.READY),this.player.initBuffer())},a));const o=u=>e.error$.next({id:"RepresentationSwitch",category:r.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(r.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,r.fromEvent(this.video,"progress")).subscribe(()=>{const u=this.player.state$.getState(),c=this.player.state$.getTransition();if(u!==de.RUNNING||c||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const h=this.selectVideoRepresentation();if(h){this.player.switchRepresentation(ae.VIDEO,h.id).catch(o);const f=this.audioRepresentations.get(h.id);f&&this.player.switchRepresentation(ae.AUDIO,f.id).catch(o)}},a)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(r.filterChanged(),r.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$,a)),this.textTracksManager.connect(this.video,t,e);const l=t.playbackState.stateChangeStarted$.pipe(r.map(({to:u})=>u===exports.PlaybackState.READY),r.filterChanged());this.subscription.add(r.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(r.merge(l,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,a))}selectVideoRepresentation(){var e,t,i,a,n,o;const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.videoTrack.getState(),u=(e=this.videoTracks.find(({track:{id:m}})=>m===d))===null||e===void 0?void 0:e.track,c=this.params.output.currentVideoTrack$.getValue(),h=tt(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),b=Math.max(u&&!l&&(i=(t=this.audioRepresentations.get(u.id))===null||t===void 0?void 0:t.bitrate)!==null&&i!==void 0?i:0,c&&(n=(a=this.audioRepresentations.get(c.id))===null||a===void 0?void 0:a.bitrate)!==null&&n!==void 0?n:0),S=Ht(this.videoTracks.map(({track:m})=>m),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:b,forwardBufferHealth:p,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),g=l?S!=null?S:u:u!=null?u:S;return g&&((o=this.videoTracks.find(({track:m})=>m===g))===null||o===void 0?void 0:o.representation)}async prepare(){this.player.initManifest(this.video,this.params.source.url)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Ue(this.video)}playIfAllowed(){We(this.video).then(e=>{e||(this.videoState.setState(J.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}}const Zp=5e3,$e={};var U;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(U||(U={}));const xt=(s,e)=>new r.Observable(t=>{const i=(a,n)=>t.next(n);return s.on(e,i),()=>s.off(e,i)});class em{constructor(e){this.subscription=new r.Subscription,this.videoState=new Q(U.INITIALIZING),this.textTracksManager=new we,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(t!==U.INITIALIZING)switch((a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&n.state===O.Requested&&this.seek(n.position),i){case exports.PlaybackState.STOPPED:switch(t){case U.STOPPED:break;case U.READY:case U.PLAYING:case U.PAUSED:this.stop();break;default:r.assertNever(t)}break;case exports.PlaybackState.READY:switch(t){case U.STOPPED:this.prepare();break;case U.READY:case U.PLAYING:case U.PAUSED:break;default:r.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case U.PLAYING:break;case U.STOPPED:this.prepare();break;case U.READY:case U.PAUSED:this.playIfAllowed();break;default:r.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case U.PAUSED:break;case U.STOPPED:this.prepare();break;case U.READY:this.videoState.setState(U.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case U.PLAYING:this.pause();break;default:r.assertNever(t)}break;default:r.assertNever(i)}},this.video=Fe(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)===null||e===void 0||e.detachMedia(),(t=this.hls)===null||t===void 0||t.destroy(),this.params.output.element$.next(void 0),Ue(this.video)}loadHlsJs(){let e=!1;const t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:r.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},i=window.setTimeout(()=>t("timeout"),Zp);import("hls.js").then(a=>{e||($e.Hls=a.default,$e.Events=a.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){r.assertNonNullable($e.Hls,"hls.js not loaded"),this.hls=new $e.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(U.STOPPED)}subscribe(){r.assertNonNullable($e.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=u=>{t.error$.next({id:"HlsJsProvider",category:r.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=je(this.video),n=(u,c)=>this.subscription.add(u.subscribe(c,i));n(a.timeUpdate$,t.position$),n(a.durationChange$,t.duration$),n(a.ended$,t.endedEvent$),n(a.looped$,t.loopedEvent$),n(a.error$,t.error$),n(a.isBuffering$,t.isBuffering$),n(a.currentBuffer$,t.currentBuffer$),n(a.loadStart$,t.firstBytesEvent$),n(a.playing$,t.firstFrameEvent$),n(a.canplay$,t.canplay$),n(a.seeked$,t.seekedEvent$),n(a.isAudioAvailable$,t.isAudioAvailable$),n(a.inPiP$,t.inPiP$),n(a.inFullscreen$,t.inFullscreen$),this.subscription.add(rt(this.video,e.isLooped,i)),this.subscription.add(Ve(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ze(this.video,e.playbackRate,a.playbackRateState$,i)),this.subscription.add(xt(this.hls,$e.Events.ERROR).subscribe(u=>{var c;u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:r.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(a.playing$.subscribe(()=>{this.videoState.setState(U.PLAYING),P(e.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(U.PAUSED),P(e.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===U.READY&&this.videoState.setState(U.READY),this.videoState.getState()===U.PLAYING&&this.playIfAllowed()},i)),n(xt(this.hls,$e.Events.MANIFEST_PARSED).pipe(r.map(({levels:u})=>u.reduce((c,h)=>{var f,p;const b=h.name||h.height.toString(10),{width:S,height:g}=h,m=(p=qt((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&p!==void 0?p:r.videoSizeToQuality({width:S,height:g});if(!m)return c;const v=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,E={id:b.toString(),quality:m,bitrate:h.bitrate/1e3,size:{width:S,height:g},fps:v};return this.trackLevels.set(b,{track:E,level:h}),c.push(E),c},[]))),t.availableVideoTracks$),n(xt(this.hls,$e.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){const c=[];for(const h of u.subtitleTracks){const f=h.name,p=h.attrs.URI||"",b=h.lang,S="internal";c.push({id:f,url:p,language:b,type:S})}e.internalTextTracks.startTransitionTo(c)}}),n(xt(this.hls,$e.Events.LEVEL_LOADING).pipe(r.map(({url:u})=>oe(u))),t.hostname$),this.subscription.add(Se(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:i}));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=xt(this.hls,$e.Events.LEVEL_SWITCHED).pipe(r.map(({level:u})=>o(this.hls.levels[u])));l.pipe(r.filter(r.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Se(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(r.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,b=this.hls.levels[p];!b||h.bitrate>b.bitrate?this.hls.nextLevel=f:(this.hls.loadLevel=f,this.hls.loadLevel=f)},{changed$:l.pipe(r.map(u=>u==null?void 0:u.id)),onError:i})),n(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=r.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(U.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(U.PLAYING),await We(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState(U.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(U.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(U.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const Pr="X-Playback-Duration";var Ar=async s=>{const e=await St(s,{method:"HEAD"});return e.headers.has(Pr)?parseInt(e.headers.get(Pr),10):void 0};const tm=s=>{let e=null;if(s.QUALITY&&(e=qt(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(a=>parseInt(a,10));e=r.videoSizeToQuality({width:t,height:i})}return e!=null?e:null},qn=async(s,e=s)=>{var t;const n=(await(await St(s)).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=jt(u[1].split(",").map(m=>m.split("="))),h=(t=c.QUALITY)!==null&&t!==void 0?t:`stream-${c.BANDWIDTH}`,f=tm(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 b=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0;let S;if(c.RESOLUTION){const[m,v]=c.RESOLUTION.split("x").map(E=>parseInt(E,10));m&&v&&(S={width:m,height:v})}const g=new URL(n[++l],e).toString();f&&o.push({id:h,quality:f,url:g,bandwidth:p,size:S,fps:b})}return o};var q;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(q||(q={}));class im{constructor(e){var t;this.subscription=new r.Subscription,this.videoState=new Q(q.STOPPED),this.textTracksManager=new we,this.manifests$=new r.ValueSubject([]),this.liveOffset=new ta,this.manifestStartTime$=new r.ValueSubject(void 0),this.syncPlayback=()=>{const a=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){a!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(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(a===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===O.None&&this.params.desiredState.seekState.setState({state:O.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&c.state===O.Requested){this.videoState.startTransitionTo(q.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(a){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 r.assertNever(a)}},this.params=e,this.video=Fe(e.container),this.params.output.element$.next(this.video);const i={id:"master",quality:r.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([i]),qn(vt(this.params.source.url),this.params.source.url).then(a=>{this.manifests$.next([i,...a])},a=>this.params.output.error$.next({id:"ExtractHlsQualities",category:r.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:a})),this.params.output.isLive$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),this.maxSeekBackTime$=new r.ValueSubject((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:a}=this.params.desiredState,n=i.getState(),o=a.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:a.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d)return;const u=n?"master":l;return n&&!o&&a.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"HlsLiveProvider",category:r.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:l})},a=je(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,i));n(a.ended$,e.endedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.isAudioAvailable$,e.isAudioAvailable$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Ve(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(q.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(q.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.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()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(r.filterChanged(),r.map(l=>-l/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(a.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&&r.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(oe(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===q.CHANGING_MANIFEST&&this.videoState.setState(d.to),l&&l.state===O.Requested&&this.seek(l.position)},i)),this.subscription.add(a.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)},i)),this.subscription.add(r.combine({startTime:this.manifestStartTime$.pipe(r.filter(r.isNonNullable)),currentTime:a.timeUpdate$}).subscribe(({startTime:l,currentTime:d})=>this.params.output.liveTime$.next(l+d*1e3),i)),this.subscription.add(this.manifests$.pipe(r.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$,i));const o=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ue(this.video)}prepare(){const e=this.selectManifest();if(r.isNullable(e))return;const t=vt(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),Ar(t).then(i=>{var a;if(!r.isNullable(i))this.maxSeekBackTime$.next(i);else{const n=(a=this.params.source.maxSeekBackTime)!==null&&a!==void 0?a:this.maxSeekBackTime$.getValue();if(r.isNullable(n)||!isFinite(n))try{St(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();Ar(u).then(c=>{r.isNullable(c)||this.maxSeekBackTime$.next(c)})}})}catch(o){}}})}playIfAllowed(){We(this.video).then(e=>{e||(this.videoState.setState(q.PAUSED),this.liveOffset.pause(),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}var z;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(z||(z={}));class sm{constructor(e){this.subscription=new r.Subscription,this.videoState=new Q(z.STOPPED),this.textTracksManager=new we,this.manifests$=new r.ValueSubject([]),this.syncPlayback=()=>{const i=this.videoState.getState(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a===exports.PlaybackState.STOPPED){i!==z.STOPPED&&(this.videoState.startTransitionTo(z.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(z.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.seekState.getState();if(i===z.STOPPED){this.videoState.startTransitionTo(z.READY),this.prepare();return}if(o||l){const c=this.videoState.getState();this.videoState.setState(z.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),u.state===O.None&&this.params.desiredState.seekState.setState({state:O.Requested,position:h*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&u.state===O.Requested&&this.seek(u.position),i){case z.READY:a===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):a===exports.PlaybackState.PAUSED?(this.videoState.setState(z.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):a===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed());return;case z.PLAYING:a===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(z.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case z.PAUSED:a===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case z.CHANGING_MANIFEST:break;default:return r.assertNever(i)}},this.params=e,this.video=Fe(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:r.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([t]),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),qn(this.params.source.url).then(i=>{this.manifests$.next([t,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:r.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:a}=this.params.desiredState,n=i.getState(),o=a.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:a.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d)return;const u=n?"master":l;return n&&!o&&a.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"HlsProvider",category:r.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:l})},a=je(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.seeked$,e.seekedEvent$),n(a.isAudioAvailable$,e.isAudioAvailable$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(rt(this.video,t.isLooped,i)),this.subscription.add(Ve(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(z.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.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()},i).add(a.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&&r.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(oe(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===z.CHANGING_MANIFEST&&this.videoState.setState(d.to),l.state===O.Requested&&this.seek(l.position)},i))),this.subscription.add(this.manifests$.pipe(r.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$,i));const o=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ue(this.video)}prepare(){const e=this.selectManifest();r.isNullable(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){We(this.video).then(e=>{e||(this.videoState.setState(z.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var K;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(K||(K={}));class am{constructor(e){this.subscription=new r.Subscription,this.videoState=new Q(K.STOPPED),this.trackUrls={},this.textTracksManager=new we,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition();if(i===exports.PlaybackState.STOPPED){t!==K.STOPPED&&(this.videoState.startTransitionTo(K.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(K.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===K.STOPPED){this.videoState.startTransitionTo(K.READY),this.prepare();return}if(o){const{currentTime:d}=this.video;this.prepare(),l.state===O.None&&this.params.desiredState.seekState.setState({state:O.Requested,position:d*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&l.state===O.Requested&&this.seek(l.position),t){case K.READY:i===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(K.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed());return;case K.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(K.PAUSED),this.video.pause()):(a==null?void 0:a.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case K.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(t)}},this.params=e,this.video=Fe(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach(([t,i],a)=>{const n=a.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"MpegProvider",category:r.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:l})},a=je(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,i));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.seeked$,e.seekedEvent$),n(a.isAudioAvailable$,e.isAudioAvailable$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(rt(this.video,t.isLooped,i)),this.subscription.add(Ve(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(ze(this.video,t.playbackRate,a.playbackRateState$,i)),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(K.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(K.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===K.READY&&this.videoState.setState(K.READY);const d=this.params.desiredState.videoTrack.getTransition();d&&r.isNonNullable(d.to)&&(this.params.desiredState.videoTrack.setState(d.to),this.params.output.currentVideoTrack$.next(this.trackUrls[d.to].track)),this.videoState.getState()===K.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const o=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Ue(this.video)}prepare(){var e,t;const i=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState();r.assertNonNullable(i,"MpegProvider: track is not selected");let{url:a}=this.trackUrls[i];r.assertNonNullable(a,`MpegProvider: No url for ${i}`),this.params.tuning.requestQuick&&(a=gt(a)),this.video.setAttribute("src",a),this.video.load(),this.params.output.hostname$.next(oe(a))}playIfAllowed(){We(this.video).then(e=>{e||(this.videoState.setState(K.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}const wr=["stun:videostun.mycdn.me:80"],rm=1e3,nm=3,fs=()=>null;class om{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=fs,this.externalStopCallback=fs,this.externalErrorCallback=fs,this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:wr}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:r.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),rm)}normalizeOptions(e={}){const t={stunServerList:wr,maxRetryNumber:nm,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var Y;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Y||(Y={}));class lm{constructor(e){this.videoState=new Q(Y.STOPPED),this.maxSeekBackTime$=new r.ValueSubject(0),this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition();if(i===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:i===exports.PlaybackState.PAUSED?(this.videoState.setState(Y.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed());return;case Y.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Y.PAUSED),this.video.pause()):(a==null?void 0:a.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Y.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(t)}},this.subscription=new r.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Fe(e.container),this.liveStreamClient=new om(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Ue(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"WebRTCLiveProvider",category:r.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};r.merge(this.videoState.stateChangeStarted$.pipe(r.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:l})=>{this.log({message:`[videoState change] ${l}: ${JSON.stringify(o)}`})});const a=je(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,i));n(a.timeUpdate$,e.liveTime$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(a.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===Y.READY&&this.videoState.setState(Y.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED)},i)).add(a.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING)},i)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ve(this.video,t.volume,a.volumeState$,i)).add(a.volumeState$.subscribe(e.volume$,i)).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 r.assertNever(o.to)}},i)).add(r.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(oe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:r.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:r.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){We(this.video).then(e=>{e||(this.videoState.setState(Y.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class _r{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 ps,ms,bs,vs,Ss,gs,ni,ys,oi,Ts,li,Es,ui,$s,di,ks,ci,Ps;const Yn=r.getCurrentBrowser().device===r.CurrentClientDevice.Android,Ye=document.createElement("video"),um='video/mp4; codecs="avc1.42000a,mp4a.40.2"',dm='video/mp4; codecs="hev1.1.6.L93.B0"',Gn='video/webm; codecs="vp09.00.10.08"',zn='video/webm; codecs="av01.0.00M.08"',cm='audio/mp4; codecs="mp4a.40.2"',hm='audio/webm; codecs="opus"',be={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&((ms=(ps=window.SourceBuffer)===null||ps===void 0?void 0:ps.prototype)===null||ms===void 0?void 0:ms.appendBuffer)),hls:Boolean(((bs=Ye.canPlayType)===null||bs===void 0?void 0:bs.call(Ye,"application/x-mpegurl"))||((vs=Ye.canPlayType)===null||vs===void 0?void 0:vs.call(Ye,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection),ws:Boolean(window.WebSocket)},ue={mp4:Boolean((Ss=Ye.canPlayType)===null||Ss===void 0?void 0:Ss.call(Ye,"video/mp4")),webm:Boolean((gs=Ye.canPlayType)===null||gs===void 0?void 0:gs.call(Ye,"video/webm")),cmaf:!0},Pe={h264:Boolean((ys=(ni=window.MediaSource)===null||ni===void 0?void 0:ni.isTypeSupported)===null||ys===void 0?void 0:ys.call(ni,um)),h265:Boolean((Ts=(oi=window.MediaSource)===null||oi===void 0?void 0:oi.isTypeSupported)===null||Ts===void 0?void 0:Ts.call(oi,dm)),vp9:Boolean((Es=(li=window.MediaSource)===null||li===void 0?void 0:li.isTypeSupported)===null||Es===void 0?void 0:Es.call(li,Gn)),av1:Boolean(($s=(ui=window.MediaSource)===null||ui===void 0?void 0:ui.isTypeSupported)===null||$s===void 0?void 0:$s.call(ui,zn)),aac:Boolean((ks=(di=window.MediaSource)===null||di===void 0?void 0:di.isTypeSupported)===null||ks===void 0?void 0:ks.call(di,cm)),opus:Boolean((Ps=(ci=window.MediaSource)===null||ci===void 0?void 0:ci.isTypeSupported)===null||Ps===void 0?void 0:Ps.call(ci,hm))},ft=(Pe.h264||Pe.h265)&&Pe.aac;var Ie;(function(s){s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient"})(Ie||(Ie={}));let et;const fm=async()=>{if(!window.navigator.mediaCapabilities)return;const s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:zn}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:Gn}})]);et={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}};try{fm()}catch(s){console.error(s)}const Li=be.hls&&ue.mp4,pm=()=>Object.keys(Pe).filter(s=>Pe[s]),mm=(s,e=!1)=>s.filter(t=>{switch(t){case exports.VideoFormat.DASH:return be.mse&&ue.mp4&&ft;case exports.VideoFormat.DASH_SEP:return be.mse&&ue.mp4&&ft;case exports.VideoFormat.DASH_WEBM:return be.mse&&ue.webm&&Pe.vp9&&Pe.opus;case exports.VideoFormat.DASH_WEBM_AV1:return be.mse&&ue.webm&&Pe.av1&&Pe.opus;case exports.VideoFormat.DASH_LIVE:return be.mse&&ue.mp4&&ft;case exports.VideoFormat.DASH_LIVE_CMAF:return be.mse&&ue.mp4&&ft&&ue.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return be.mse&&ue.mp4&&ft;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.HLS_ONDEMAND:return Li||e&&be.mse&&ue.mp4&&ft;case exports.VideoFormat.MPEG:return ue.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return be.webrtc&&be.ws&&Pe.h264&&(ue.mp4||ue.webm);default:return r.assertNever(t)}}),As=s=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(s){case Ie.VP9:return[e,t];case Ie.AV1:return[t,e];case Ie.NONE:return[];case Ie.SMOOTH:return et?et[t].smooth?[t,e]:et[e].smooth?[e,t]:[t,e]:[e,t];case Ie.POWER_EFFICIENT:return et?et[t].powerEfficient?[t,e]:et[e].powerEfficient?[e,t]:[t,e]:[e,t];default:r.assertNever(s)}return[e,t]},bm=(s=Ie.VP9)=>Yn?[exports.VideoFormat.MPEG,...As(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND]:Li?[...As(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[...As(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG],vm=()=>Yn?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF]:Li?[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF]:[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],Rr=s=>s?[exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_WEBM_AV1,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var Sm=s=>new r.Observable(e=>{const t=new r.Subscription,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(r.map(({from:u,to:c})=>`${u}-${c}`)),a=s.desiredPlaybackState$.stateChangeEnded$,n=s.providerChanged$.pipe(r.map(({type:u})=>u!==void 0)),o=new r.Subject;let l=0,d="unknown";return t.add(i.subscribe(u=>{l&&window.clearTimeout(l),d=u,l=window.setTimeout(()=>o.next(u),s.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(l),d="unknown",l=0})),t.add(n.subscribe(u=>{l&&(window.clearTimeout(l),l=0,u&&(l=window.setTimeout(()=>o.next(d),s.maxTransitionInterval)))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const Ir={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},gm={cacheDuration:12e4},ym={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Tm={maxPausedTime:3e4},Dr={maxPausedTime:3e4};class Em{constructor(e){this.current$=new r.ValueSubject({type:void 0}),this.providerError$=new r.Subject,this.noAvailableProvidersError$=new r.Subject,this.providerOutput={position$:new r.ValueSubject(0),duration$:new r.ValueSubject(1/0),volume$:new r.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new r.ValueSubject(void 0),availableVideoTracks$:new r.ValueSubject([]),availableAudioTracks$:new r.ValueSubject([]),isAudioAvailable$:new r.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new r.ValueSubject(!1),currentBuffer$:new r.ValueSubject(void 0),isBuffering$:new r.ValueSubject(!0),error$:new r.Subject,willSeekEvent$:new r.Subject,seekedEvent$:new r.Subject,loopedEvent$:new r.Subject,endedEvent$:new r.Subject,firstBytesEvent$:new r.Subject,firstFrameEvent$:new r.Subject,canplay$:new r.Subject,isLive$:new r.ValueSubject(void 0),liveTime$:new r.ValueSubject(void 0),availableTextTracks$:new r.ValueSubject([]),currentTextTrack$:new r.ValueSubject(void 0),hostname$:new r.ValueSubject(void 0),httpConnectionType$:new r.ValueSubject(void 0),httpConnectionReused$:new r.ValueSubject(void 0),inPiP$:new r.ValueSubject(!1),inFullscreen$:new r.ValueSubject(!1),element$:new r.ValueSubject(void 0),availableSources$:new r.ValueSubject(void 0)},this.subscription=new r.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=mm([...vm(),...bm(this.params.tuning.webmCodec)],this.params.tuning.useHlsJs).filter(l=>r.isNonNullable(e.sources[l])),{forceFormat:i,formatsToAvoid:a}=this.params.tuning;let n=[];i?n=[i]:a.length?n=[...t.filter(l=>!a.includes(l)),...t.filter(l=>a.includes(l))]:n=t,this.screenFormatsIterator=new _r(n);const o=[...Rr(!0),...Rr(!1)];this.chromecastFormatsIterator=new _r(o.filter(l=>r.isNonNullable(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(r.isNullable(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:r.ErrorCategory.WTF,message:"Failed to create provider",thrown:a})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),a=i.state!==O.None;this.params.desiredState.seekState.setState({state:O.Requested,position:a?i.position:t,forcePrecise:a?i.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 re.SCREEN:return this.createScreenProvider(t);case re.CHROMECAST:return this.createChromecastProvider(t);default:return r.assertNever(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:a}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Hf({...o,source:l,config:gm})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.DASH_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),this.params.tuning.useDashJs?new hr({...o,source:l,format:e,config:Dr}):new Xp({...o,source:l})}case exports.VideoFormat.DASH_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new hr({...o,source:l,format:e,config:Dr})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),Li||!this.params.tuning.useHlsJs?new sm({...o,source:l}):new em({...o,source:l})}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new im({...o,source:l,config:Tm})}case exports.VideoFormat.MPEG:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new am({...o,source:l})}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Mf({...o,source:l,config:ym})}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new lm({container:i,source:l,desiredState:a,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 r.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:a,meta:n}=this.params,o=this.providerOutput,l=this.params.dependencies.chromecastInitializer.connection$.getValue();return r.assertNonNullable(l),new Uh({connection:l,meta:n,container:i,source:t,format:e,desiredState:a,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?re.CHROMECAST:re.SCREEN}chooseFormat(e){switch(e){case re.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case re.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return r.assertNever(e)}}skipFormat(e){switch(e){case re.SCREEN:return this.screenFormatsIterator.next();case re.CHROMECAST:return this.chromecastFormatsIterator.next();default:return r.assertNever(e)}}handleNoFormatsError(e){switch(e){case re.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case re.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return r.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=a=>{const n=new URL(a);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{...e,url:i(e.url)}}return jt(Object.entries(e).map(([a,n])=>[a,i(n)]))}initProviderErrorHandling(){const e=new r.Subscription;let t=!1,i=0;return e.add(r.merge(this.providerOutput.error$,Sm({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:Ir.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(r.map(a=>({id:`ProviderHangup:${a}`,category:r.ErrorCategory.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const a=this.params.desiredState.playbackState.transitionEnded$.pipe(r.filter(({to:n})=>n===exports.PlaybackState.PLAYING),r.once()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{const n=this.current$.getValue().destination;if(n===re.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(re.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const o=a.category===r.ErrorCategory.NETWORK,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<Ir.providerErrorLimit;l&&(o&&t||!d)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(i++,this.reinitProvider()):this.switchToNextProvider(n!=null?n:re.SCREEN)}})),e}}const Vs=(s,e,t)=>t*e+(1-t)*s,Wn=(s,e)=>s.reduce((t,i)=>t+i,0)/e,$m=(s,e,t,i)=>{let a=0,n=t;const o=Wn(s,e),l=e<i?e:i;for(let d=0;d<l;d++)s[n]>o?a++:a--,n=(s.length+n-1)%s.length;return Math.abs(a)===l};class Qn{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new r.ValueSubject(e.initial),this.debounced$=new r.ValueSubject(e.initial);const i=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ke(`raw_${i}`),this.smoothedSeries$=new ke(`smoothed_${i}`),this.reportedSeries$=new ke(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let l=0;l<this.pastMeasures.length;l++)this.pastMeasures[l]!==void 0&&(t+=(this.pastMeasures[l]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const a=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*a,o=this.smoothed-this.params.deviationFactor*a;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>n||this.smoothed<o)&&(r.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))}}class km extends Qn{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Vs(this.slow,e,this.params.emaAlphaSlow),this.fast=Vs(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Pm extends Qn{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Wn(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Vs(this.emaSmoothed,e,this.params.emaAlpha);const i=$m(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class Nr{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new km({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Pm({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}}const Am=5e3,Cr="one_video_throughput",Lr="one_video_rtt",Le=window.navigator.connection,xr=()=>{const s=Le==null?void 0:Le.downlink;if(r.isNonNullable(s)&&s!==10)return s*1e3},Or=()=>{const s=Le==null?void 0:Le.rtt;if(r.isNonNullable(s)&&s!==3e3)return s},Br=(s,e,t)=>{const i=t*8,a=i/s;return i/(a+e)};class Bt{constructor(e){var t,i;this.subscription=new r.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const a=Bt.load(Cr)||(e.useBrowserEstimation?xr():void 0)||Am,n=(i=(t=Bt.load(Lr))!==null&&t!==void 0?t:e.useBrowserEstimation?Or():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new r.ValueSubject(a),this.rtt$=new r.ValueSubject(n),this.rttAdjustedThroughput$=new r.ValueSubject(Br(a,n,e.rttPenaltyRequestSize)),this.throughput=Nr.getSmoothedValue(a,-1,e),this.rtt=Nr.getSmoothedValue(n,1,e),e.useBrowserEstimation){const o=()=>{const d=xr();d&&this.throughput.next(d);const u=Or();r.isNonNullable(u)&&this.rtt.next(u)};Le&&"onchange"in Le&&this.subscription.add(r.fromEvent(Le,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{r.safeStorage.set(Cr,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{r.safeStorage.set(Lr,o.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(r.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(r.map(({throughput:o,rtt:l})=>Br(o,l,e.rttPenaltyRequestSize)),r.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,i=r.now();const a=new r.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(r.fromEvent(e,"progress").pipe(r.once()).subscribe(n=>{t=n.loaded,i=r.now()}));break;case 1:case 0:a.add(r.fromEvent(e,"loadstart").subscribe(()=>{t=0,i=r.now()}));break}a.add(r.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,l=r.now(),d=o-t,u=l-i;this.addRawSpeed(d,u,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let i=0;const a=r.now();let n=0,o=r.now();const l=u=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${u}`).catch(()=>{})},d=async({done:u,value:c})=>{u?(this.addRawSpeed(i,r.now()-a,1),this.concurrentDownloads.delete(e)):c&&(i+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&r.now()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,r.now()-o,this.concurrentDownloads.size),n=0,o=r.now()),await(t==null?void 0:t.read().then(d,l)))};this.concurrentDownloads.add(e),t==null||t.read().then(d,l)}addRawSpeed(e,t,i=1){if(Bt.sanityCheck(e,t)){const a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||e<10*1024||t<=20)}static load(e){var t;const i=r.safeStorage.get(e);if(r.isNonNullable(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const Mr={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,webmCodec:Ie.VP9,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useHlsJs:!0,isAudioDisabled:!1,webrtc:{connectionRetryMaxNumber:3}},wm=s=>{const e={};for(const t of Object.keys(Mr)){const i=Mr[t],a=s[t];Array.isArray(i)&&Array.isArray(a)?t==="configName"?e[t]=[...a,...i]:e[t]=a:typeof i=="object"&&typeof a=="object"?e[t]={...i,...a}:e[t]=a!=null?a:i}return e};var Vr=({seekState:s,position$:e})=>r.merge(s.stateChangeEnded$.pipe(r.map(({to:t})=>{var i;return t.state===O.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),r.filter(r.isNonNullable)),e.pipe(r.filter(()=>s.getState().state===O.None))),_m=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return r.assertNonNullable(e,`Wrong container or containerId {${s.container}}`),e};class Rm{constructor(e={configName:[]}){if(this.subscription=new r.Subscription,this.logger=new r.Logger,this.isPlaybackStarted=!1,this.desiredState={playbackState:new Q(exports.PlaybackState.STOPPED),seekState:new Q({state:O.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([]),internalTextTracks:new Q([]),currentTextTrack:new Q(void 0),textTrackCuesSettings:new Q({})},this.info={playbackState$:new r.ValueSubject(exports.PlaybackState.STOPPED),position$:new r.ValueSubject(0),duration$:new r.ValueSubject(1/0),muted$:new r.ValueSubject(!1),volume$:new r.ValueSubject(1),availableQualities$:new r.ValueSubject([]),availableQualitiesFps$:new r.ValueSubject({}),availableAudioTracks$:new r.ValueSubject([]),isAudioAvailable$:new r.ValueSubject(!0),currentQuality$:new r.ValueSubject(void 0),isAutoQualityEnabled$:new r.ValueSubject(!0),autoQualityLimitingAvailable$:new r.ValueSubject(!1),autoQualityLimits$:new r.ValueSubject({}),currentPlaybackRate$:new r.ValueSubject(1),currentBuffer$:new r.ValueSubject({start:0,end:0}),isBuffering$:new r.ValueSubject(!0),isStalled$:new r.ValueSubject(!1),isEnded$:new r.ValueSubject(!1),isLooped$:new r.ValueSubject(!1),isLive$:new r.ValueSubject(void 0),atLiveEdge$:new r.ValueSubject(void 0),liveTime$:new r.ValueSubject(void 0),currentFormat$:new r.ValueSubject(void 0),availableTextTracks$:new r.ValueSubject([]),currentTextTrack$:new r.ValueSubject(void 0),throughputEstimation$:new r.ValueSubject(void 0),rttEstimation$:new r.ValueSubject(void 0),videoBitrate$:new r.ValueSubject(void 0),hostname$:new r.ValueSubject(void 0),httpConnectionType$:new r.ValueSubject(void 0),httpConnectionReused$:new r.ValueSubject(void 0),surface$:new r.ValueSubject(exports.Surface.NONE),chromecastState$:new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new r.ValueSubject(void 0),intrinsicVideoSize$:new r.ValueSubject(void 0),availableSources$:new r.ValueSubject(void 0)},this.events={inited$:new r.Subject,ready$:new r.Subject,started$:new r.Subject,playing$:new r.Subject,paused$:new r.Subject,stopped$:new r.Subject,willStart$:new r.Subject,willResume$:new r.Subject,willPause$:new r.Subject,willStop$:new r.Subject,willDestruct$:new r.Subject,watchCoverageRecord$:new r.Subject,watchCoverageLive$:new r.Subject,managedError$:new r.Subject,fatalError$:new r.Subject,ended$:new r.Subject,looped$:new r.Subject,seeked$:new r.Subject,willSeek$:new r.Subject,firstBytes$:new r.Subject,firstFrame$:new r.Subject,canplay$:new r.Subject,log$:new r.Subject},this.experimental={element$:new r.ValueSubject(void 0),tuningConfigName$:new r.ValueSubject([]),enableDebugTelemetry$:new r.ValueSubject(!1),dumpTelemetry:vf},this.initLogs(),this.tuning=wm(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Eo({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Bt(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,a)=>{const n=Reflect.get(t,i,a);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 b=typeof p;return["number","string","boolean"].includes(b)?p:p===null?null:`<${b}>`})),u=`Player.${String(i)}`,c=`Exception calling ${u} (${d.join(", ")})`;throw this.events.fatalError$.next({id:u,category:r.ErrorCategory.WTF,message:c,thrown:l}),l}}}})}initVideo(e){var t,i,a;return this.config=e,this.domContainer=_m(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Em({sources:e.sources,meta:(i=e.meta)!==null&&i!==void 0?i:{},failoverHosts:(a=e.failoverHosts)!==null&&a!==void 0?a:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===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:O.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){r.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const i=t.find(a=>a.quality===e);return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.setState(e),this}setPlaybackRate(e){var t;r.assertNonNullable(this.providerContainer);const i=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return i&&(this.desiredState.playbackRate.setState(e),i.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return(e===void 0||!((t=this.providerContainer)===null||t===void 0)&&t.providerOutput.availableTextTracks$.getValue().find(i=>i.id===e))&&this.desiredState.currentTextTrack.startTransitionTo(e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){r.assertNonNullable(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(r.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===O.None?void 0:t.position;return r.isNonNullable(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}setIntrinsicVideoSize(...e){const t={width:e.reduce((i,{width:a})=>i||a||0,0),height:e.reduce((i,{height:a})=>i||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(r.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(r.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(r.filter(({from:e})=>e===exports.PlaybackState.STOPPED),r.once()).subscribe(()=>{this.initedAt=r.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case exports.PlaybackState.READY:this.events.ready$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case exports.PlaybackState.PAUSED:this.events.paused$.next();break;case exports.PlaybackState.STOPPED:this.events.stopped$.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.events.willStart$.next();break;case exports.PlaybackState.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const o=this.desiredState.seekState.getState();o.state===O.Requested?this.desiredState.seekState.setState({...o,state:O.Applying}):this.events.managedError$.next({id:`WillSeekIn${o.state}`,category:r.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===O.Applying&&(this.desiredState.seekState.setState({state:O.None}),this.events.seeked$.next())})).add(e.current$.pipe(r.map(o=>o.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(r.map(o=>o.destination),r.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(r.map(o=>o.map(({quality:l})=>l).sort((l,d)=>r.isInvariantQuality(l)?1:r.isInvariantQuality(d)?-1:r.isHigher(d,l)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(o=>{const l={};for(const d of o)d.fps&&(l[d.quality]=d.fps);this.info.availableQualitiesFps$.next(l)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{this.info.currentQuality$.next(o==null?void 0:o.quality),this.info.videoBitrate$.next(o==null?void 0:o.bitrate)})).add(e.providerOutput.hostname$.pipe(r.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(r.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(r.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(r.map(o=>o?{start:o.from,end:o.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(r.combine({isLive:e.providerOutput.isLive$,position:Vr({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(r.map(({isLive:o,position:l})=>o&&l>-r.ACTIVE_LIVE_VALID_DELAY),r.filterChanged()).subscribe(this.info.atLiveEdge$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(r.map(o=>o.muted),r.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(r.map(o=>o.volume),r.filterChanged()).subscribe(this.info.volume$)).add(Vr({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(r.merge(e.providerOutput.endedEvent$.pipe(r.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(r.mapTo(!1))).pipe(r.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(r.map(o=>({id:o?`No${o}`:"NoProviders",category:r.ErrorCategory.VIDEO_PIPELINE,message:o?`${o} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(r.once(),r.map(o=>o!=null?o:r.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(r.once(),r.map(()=>r.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(r.once(),r.map(()=>r.now()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new r.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new r.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(r.filter(({to:o})=>o===exports.PlaybackState.PLAYING),r.once()).subscribe(()=>i.next(!1)));let a=0;const n=r.merge(e.providerOutput.isBuffering$,t,i).pipe(r.map(()=>{const o=e.providerOutput.isBuffering$.getValue(),l=t.getValue()||i.getValue();return o&&!l}),r.filterChanged());this.subscription.add(n.subscribe(o=>{o?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add(r.merge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{var l,d;const u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(l=o==null?void 0:o.size)===null||l===void 0?void 0:l.width,height:(d=o==null?void 0:o.size)===null||d===void 0?void 0:d.height},{width:u==null?void 0:u.videoWidth,height:u==null?void 0:u.videoHeight})})),this.subscription.add(r.merge(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const o=e.providerOutput.inPiP$.getValue(),l=e.providerOutput.inFullscreen$.getValue(),d=e.providerOutput.element$.getValue(),u=this.chromecastInitializer.castState$.getValue();let c;u===exports.ChromecastState.CONNECTED?c=exports.Surface.SECOND_SCREEN:d?o?c=exports.Surface.PIP:l?c=exports.Surface.FULLSCREEN:c=exports.Surface.INLINE:c=exports.Surface.NONE,this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(r.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 r.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(r.filterChanged((i,a)=>i.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(r.filter(i=>i.length>0),r.once()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:i})=>i===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=Ht(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(r.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(r.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;r.assertNonNullable(this.providerContainer),r.assertNonNullable(t),bf(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>mf(i)),this.providerContainer.current$.subscribe(({type:i})=>si("provider",i)),t.duration$.subscribe(i=>si("duration",i)),t.availableVideoTracks$.pipe(r.filter(i=>!!i.length),r.once()).subscribe(i=>si("tracks",i)),this.events.fatalError$.subscribe(new ke("fatalError")),this.events.managedError$.subscribe(new ke("managedError")),t.position$.subscribe(new ke("position")),t.currentVideoTrack$.pipe(r.map(i=>i==null?void 0:i.quality)).subscribe(new ke("quality")),this.info.currentBuffer$.subscribe(new ke("buffer")),t.isBuffering$.subscribe(new ke("isBuffering"))].forEach(i=>this.subscription.add(i)),si("codecs",pm())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:r.ErrorCategory.DOM,message:String(a)})})};this.subscription.add(r.merge(r.fromEvent(document,"visibilitychange"),r.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const a=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=Boolean(e)&&!(e!=null&&e.released);a&&n?o||i():t()})).add(this.events.willDestruct$.subscribe(t))}}const Im=`@vkontakte/videoplayer-core@${Fr}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return r.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return r.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return r.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return r.ValueSubject}});Object.defineProperty(exports,"VideoQuality",{enumerable:!0,get:function(){return r.VideoQuality}});exports.Player=Rm;exports.SDK_VERSION=Im;exports.VERSION=Fr;