@vkontakte/videoplayer-core 2.0.80 → 2.0.81

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es2015.cjs.js CHANGED
@@ -1,8 +1,8 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.80
3
- * Fri, 24 Mar 2023 13:06:32 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-80/doc/
2
+ * @vkontakte/videoplayer-core v2.0.81
3
+ * Tue, 28 Mar 2023 08:39:32 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-81/doc/
5
5
  */
6
- "use strict";var au=Object.create;var va=Object.defineProperty;var nu=Object.getOwnPropertyDescriptor;var ou=Object.getOwnPropertyNames;var lu=Object.getPrototypeOf,uu=Object.prototype.hasOwnProperty;var du=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ou(e))!uu.call(i,s)&&s!==t&&va(i,s,{get:()=>e[s],enumerable:!(r=nu(e,s))||r.enumerable});return i};var Sa=(i,e,t)=>(t=i!=null?au(lu(i)):{},du(e||!i||!i.__esModule?va(t,"default",{value:i,enumerable:!0}):t,i));var a=require("@vkontakte/videoplayer-shared/es2015.cjs.js"),cu=require("lodash/debounce.js");const hu="2.0.80",fu="@vkontakte/videoplayer-core";exports.PlaybackState=void 0;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(i){i.MPEG="MPEG",i.DASH="DASH",i.DASH_SEP="DASH_SEP",i.DASH_SEP_VK="DASH_SEP",i.DASH_WEBM="DASH_WEBM",i.DASH_WEBM_VK="DASH_WEBM",i.DASH_ONDEMAND="DASH_ONDEMAND",i.DASH_ONDEMAND_VK="DASH_ONDEMAND",i.DASH_LIVE="DASH_LIVE",i.DASH_LIVE_WEBM="DASH_LIVE_WEBM",i.HLS="HLS",i.HLS_ONDEMAND="HLS_ONDEMAND",i.HLS_JS="HLS",i.HLS_LIVE="HLS_LIVE",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(exports.VideoFormat||(exports.VideoFormat={}));var he;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(he||(he={}));exports.ChromecastState=void 0;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var C;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(C||(C={}));var pu=i=>new Promise((e,t)=>{const r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});class mu{constructor(e){var t;this.connection$=new a.ValueSubject(void 0),this.castState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new a.Subject,this.realCastState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const r="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${r}`}),e.isDisabled||!r)return;const s=a.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=Boolean(window.__onGCastApiAvailable);s?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||pu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:a.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,s,n;(n=(s=(r=cast.framework.CastContext.getInstance())===null||r===void 0?void 0:r.getCurrentSession())===null||s===void 0?void 0:s.getMediaSession())===null||n===void 0||n.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){a.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();a.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();a.isNullable(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(a.fromEvent(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(s=>{var n,o;switch(s.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=r.getCurrentSession())===null||n===void 0?void 0:n.getMediaSession())===null||o===void 0?void 0:o.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return a.assertNever(s.sessionState)}})).add(a.merge(a.fromEvent(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(a.tap(s=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(s)}`})}),a.map(s=>s.castState)),a.observableFrom([r.getCastState()])).pipe(a.filterChanged(),a.map(vu),a.tap(s=>{this.log({message:`realCastState$: ${s}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(s=>{var n;const o=s===exports.ChromecastState.CONNECTED,l=a.isNonNullable(this.connection$.getValue());if(o&&!l){const d=r.getCurrentSession();a.assertNonNullable(d);const u=d.getCastDevice(),c=(n=d.getMediaSession())===null||n===void 0?void 0:n.media.contentId;(a.isNullable(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:d,castDevice:u}))}else!o&&l&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(s===exports.ChromecastState.CONNECTED?a.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:s)}))}initializeCastApi(){var e;let t,r,s;try{t=cast.framework.CastContext.getInstance(),r=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,s=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:r,autoJoinPolicy:s}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:a.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const vu=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return exports.ChromecastState.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return exports.ChromecastState.AVAILABLE;case cast.framework.CastState.CONNECTING:return exports.ChromecastState.CONNECTING;case cast.framework.CastState.CONNECTED:return exports.ChromecastState.CONNECTED;default:return a.assertNever(i)}};var ba=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},ye=function(i){try{return!!i()}catch(e){return!0}},Su=ye,er=!Su(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),so=er,ao=Function.prototype,hs=ao.call,bu=so&&ao.bind.bind(hs,hs),Ce=so?bu:function(i){return function(){return hs.apply(i,arguments)}},no=Ce,gu=no({}.toString),yu=no("".slice),tr=function(i){return yu(gu(i),8,-1)},Tu=Ce,Eu=ye,$u=tr,Sr=Object,ku=Tu("".split),Pu=Eu(function(){return!Sr("z").propertyIsEnumerable(0)})?function(i){return $u(i)=="String"?ku(i,""):Sr(i)}:Sr,ir=function(i){return i==null},Au=ir,wu=TypeError,oo=function(i){if(Au(i))throw wu("Can't call method on "+i);return i},_u=Pu,Ru=oo,si=function(i){return _u(Ru(i))},Iu=function(){},Ct={},vi=function(i){return i&&i.Math==Math&&i},le=vi(typeof globalThis=="object"&&globalThis)||vi(typeof window=="object"&&window)||vi(typeof self=="object"&&self)||vi(typeof ba=="object"&&ba)||function(){return this}()||Function("return this")(),fs=typeof document=="object"&&document.all,Nu=typeof fs=="undefined"&&fs!==void 0,lo={all:fs,IS_HTMLDDA:Nu},uo=lo,Cu=uo.all,se=uo.IS_HTMLDDA?function(i){return typeof i=="function"||i===Cu}:function(i){return typeof i=="function"},Du=le,Ou=se,ga=Du.WeakMap,Lu=Ou(ga)&&/native code/.test(String(ga)),ya=se,co=lo,xu=co.all,Ke=co.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:ya(i)||i===xu}:function(i){return typeof i=="object"?i!==null:ya(i)},Bu=ye,Ue=!Bu(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),ct={},Mu=le,Ta=Ke,ps=Mu.document,Vu=Ta(ps)&&Ta(ps.createElement),Ls=function(i){return Vu?ps.createElement(i):{}},Fu=Ue,Uu=ye,ju=Ls,ho=!Fu&&!Uu(function(){return Object.defineProperty(ju("div"),"a",{get:function(){return 7}}).a!=7}),Hu=Ue,Gu=ye,fo=Hu&&Gu(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Yu=Ke,qu=String,zu=TypeError,Xe=function(i){if(Yu(i))return i;throw zu(qu(i)+" is not an object")},Wu=er,Si=Function.prototype.call,ke=Wu?Si.bind(Si):function(){return Si.apply(Si,arguments)},xs={},br=xs,gr=le,Qu=se,Ea=function(i){return Qu(i)?i:void 0},ht=function(i,e){return arguments.length<2?Ea(br[i])||Ea(gr[i]):br[i]&&br[i][e]||gr[i]&&gr[i][e]},Ju=Ce,Bs=Ju({}.isPrototypeOf),rr=typeof navigator!="undefined"&&String(navigator.userAgent)||"",po=le,yr=rr,$a=po.process,ka=po.Deno,Pa=$a&&$a.versions||ka&&ka.version,Aa=Pa&&Pa.v8,Te,Hi;Aa&&(Te=Aa.split("."),Hi=Te[0]>0&&Te[0]<4?1:+(Te[0]+Te[1]));!Hi&&yr&&(Te=yr.match(/Edge\/(\d+)/),(!Te||Te[1]>=74)&&(Te=yr.match(/Chrome\/(\d+)/),Te&&(Hi=+Te[1])));var mo=Hi,wa=mo,Ku=ye,vo=!!Object.getOwnPropertySymbols&&!Ku(function(){var i=Symbol();return!String(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&wa&&wa<41}),Xu=vo,So=Xu&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Zu=ht,ed=se,td=Bs,id=So,rd=Object,bo=id?function(i){return typeof i=="symbol"}:function(i){var e=Zu("Symbol");return ed(e)&&td(e.prototype,rd(i))},sd=String,sr=function(i){try{return sd(i)}catch(e){return"Object"}},ad=se,nd=sr,od=TypeError,ft=function(i){if(ad(i))return i;throw od(nd(i)+" is not a function")},ld=ft,ud=ir,Ms=function(i,e){var t=i[e];return ud(t)?void 0:ld(t)},Tr=ke,Er=se,$r=Ke,dd=TypeError,cd=function(i,e){var t,r;if(e==="string"&&Er(t=i.toString)&&!$r(r=Tr(t,i))||Er(t=i.valueOf)&&!$r(r=Tr(t,i))||e!=="string"&&Er(t=i.toString)&&!$r(r=Tr(t,i)))return r;throw dd("Can't convert object to primitive value")},Gi={},hd={get exports(){return Gi},set exports(i){Gi=i}},go=!0,_a=le,fd=Object.defineProperty,pd=function(i,e){try{fd(_a,i,{value:e,configurable:!0,writable:!0})}catch(t){_a[i]=e}return e},md=le,vd=pd,Ra="__core-js_shared__",Sd=md[Ra]||vd(Ra,{}),Vs=Sd,Ia=Vs;(hd.exports=function(i,e){return Ia[i]||(Ia[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.27.2",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.27.2/LICENSE",source:"https://github.com/zloirock/core-js"});var bd=oo,gd=Object,Fs=function(i){return gd(bd(i))},yd=Ce,Td=Fs,Ed=yd({}.hasOwnProperty),je=Object.hasOwn||function(e,t){return Ed(Td(e),t)},$d=Ce,kd=0,Pd=Math.random(),Ad=$d(1 .toString),yo=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Ad(++kd+Pd,36)},wd=le,_d=Gi,Na=je,Rd=yo,Id=vo,Nd=So,Et=wd.Symbol,kr=_d("wks"),Cd=Nd?Et.for||Et:Et&&Et.withoutSetter||Rd,pe=function(i){return Na(kr,i)||(kr[i]=Id&&Na(Et,i)?Et[i]:Cd("Symbol."+i)),kr[i]},Dd=ke,Ca=Ke,Da=bo,Od=Ms,Ld=cd,xd=pe,Bd=TypeError,Md=xd("toPrimitive"),Vd=function(i,e){if(!Ca(i)||Da(i))return i;var t=Od(i,Md),r;if(t){if(e===void 0&&(e="default"),r=Dd(t,i,e),!Ca(r)||Da(r))return r;throw Bd("Can't convert object to primitive value")}return e===void 0&&(e="number"),Ld(i,e)},Fd=Vd,Ud=bo,Us=function(i){var e=Fd(i,"string");return Ud(e)?e:e+""},jd=Ue,Hd=ho,Gd=fo,bi=Xe,Oa=Us,Yd=TypeError,Pr=Object.defineProperty,qd=Object.getOwnPropertyDescriptor,Ar="enumerable",wr="configurable",_r="writable";ct.f=jd?Gd?function(e,t,r){if(bi(e),t=Oa(t),bi(r),typeof e=="function"&&t==="prototype"&&"value"in r&&_r in r&&!r[_r]){var s=qd(e,t);s&&s[_r]&&(e[t]=r.value,r={configurable:wr in r?r[wr]:s[wr],enumerable:Ar in r?r[Ar]:s[Ar],writable:!1})}return Pr(e,t,r)}:Pr:function(e,t,r){if(bi(e),t=Oa(t),bi(r),Hd)try{return Pr(e,t,r)}catch(s){}if("get"in r||"set"in r)throw Yd("Accessors not supported");return"value"in r&&(e[t]=r.value),e};var ar=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},zd=Ue,Wd=ct,Qd=ar,ai=zd?function(i,e,t){return Wd.f(i,e,Qd(1,t))}:function(i,e,t){return i[e]=t,i},Jd=Gi,Kd=yo,La=Jd("keys"),js=function(i){return La[i]||(La[i]=Kd(i))},Hs={},Xd=Lu,To=le,Zd=Ke,ec=ai,Rr=je,Ir=Vs,tc=js,ic=Hs,xa="Object already initialized",ms=To.TypeError,rc=To.WeakMap,Yi,ii,qi,sc=function(i){return qi(i)?ii(i):Yi(i,{})},ac=function(i){return function(e){var t;if(!Zd(e)||(t=ii(e)).type!==i)throw ms("Incompatible receiver, "+i+" required");return t}};if(Xd||Ir.state){var _e=Ir.state||(Ir.state=new rc);_e.get=_e.get,_e.has=_e.has,_e.set=_e.set,Yi=function(i,e){if(_e.has(i))throw ms(xa);return e.facade=i,_e.set(i,e),e},ii=function(i){return _e.get(i)||{}},qi=function(i){return _e.has(i)}}else{var bt=tc("state");ic[bt]=!0,Yi=function(i,e){if(Rr(i,bt))throw ms(xa);return e.facade=i,ec(i,bt,e),e},ii=function(i){return Rr(i,bt)?i[bt]:{}},qi=function(i){return Rr(i,bt)}}var Eo={set:Yi,get:ii,has:qi,enforce:sc,getterFor:ac},nc=er,$o=Function.prototype,Ba=$o.apply,Ma=$o.call,ko=typeof Reflect=="object"&&Reflect.apply||(nc?Ma.bind(Ba):function(){return Ma.apply(Ba,arguments)}),oc=tr,lc=Ce,Po=function(i){if(oc(i)==="Function")return lc(i)},Gs={},Ao={},wo={}.propertyIsEnumerable,_o=Object.getOwnPropertyDescriptor,uc=_o&&!wo.call({1:2},1);Ao.f=uc?function(e){var t=_o(this,e);return!!t&&t.enumerable}:wo;var dc=Ue,cc=ke,hc=Ao,fc=ar,pc=si,mc=Us,vc=je,Sc=ho,Va=Object.getOwnPropertyDescriptor;Gs.f=dc?Va:function(e,t){if(e=pc(e),t=mc(t),Sc)try{return Va(e,t)}catch(r){}if(vc(e,t))return fc(!cc(hc.f,e,t),e[t])};var bc=ye,gc=se,yc=/#|\.prototype\./,ni=function(i,e){var t=Ec[Tc(i)];return t==kc?!0:t==$c?!1:gc(e)?bc(e):!!e},Tc=ni.normalize=function(i){return String(i).replace(yc,".").toLowerCase()},Ec=ni.data={},$c=ni.NATIVE="N",kc=ni.POLYFILL="P",Ro=ni,Fa=Po,Pc=ft,Ac=er,wc=Fa(Fa.bind),nr=function(i,e){return Pc(i),e===void 0?i:Ac?wc(i,e):function(){return i.apply(e,arguments)}},gi=le,_c=ko,Rc=Po,Ic=se,Nc=Gs.f,Cc=Ro,gt=xs,Dc=nr,yt=ai,Ua=je,Oc=function(i){var e=function(t,r,s){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,r)}return new i(t,r,s)}return _c(i,this,arguments)};return e.prototype=i.prototype,e},De=function(i,e){var t=i.target,r=i.global,s=i.stat,n=i.proto,o=r?gi:s?gi[t]:(gi[t]||{}).prototype,l=r?gt:gt[t]||yt(gt,t,{})[t],d=l.prototype,u,c,h,f,p,v,m,S,b;for(f in e)u=Cc(r?f:t+(s?".":"#")+f,i.forced),c=!u&&o&&Ua(o,f),v=l[f],c&&(i.dontCallGetSet?(b=Nc(o,f),m=b&&b.value):m=o[f]),p=c&&m?m:e[f],!(c&&typeof v==typeof p)&&(i.bind&&c?S=Dc(p,gi):i.wrap&&c?S=Oc(p):n&&Ic(p)?S=Rc(p):S=p,(i.sham||p&&p.sham||v&&v.sham)&&yt(S,"sham",!0),yt(l,f,S),n&&(h=t+"Prototype",Ua(gt,h)||yt(gt,h,{}),yt(gt[h],f,p),i.real&&d&&(u||!d[f])&&yt(d,f,p)))},vs=Ue,Lc=je,Io=Function.prototype,xc=vs&&Object.getOwnPropertyDescriptor,Ys=Lc(Io,"name"),Bc=Ys&&function(){}.name==="something",Mc=Ys&&(!vs||vs&&xc(Io,"name").configurable),Vc={EXISTS:Ys,PROPER:Bc,CONFIGURABLE:Mc},No={},Fc=Math.ceil,Uc=Math.floor,jc=Math.trunc||function(e){var t=+e;return(t>0?Uc:Fc)(t)},Hc=jc,qs=function(i){var e=+i;return e!==e||e===0?0:Hc(e)},Gc=qs,Yc=Math.max,qc=Math.min,zc=function(i,e){var t=Gc(i);return t<0?Yc(t+e,0):qc(t,e)},Wc=qs,Qc=Math.min,Jc=function(i){return i>0?Qc(Wc(i),9007199254740991):0},Kc=Jc,zs=function(i){return Kc(i.length)},Xc=si,Zc=zc,eh=zs,ja=function(i){return function(e,t,r){var s=Xc(e),n=eh(s),o=Zc(r,n),l;if(i&&t!=t){for(;n>o;)if(l=s[o++],l!=l)return!0}else for(;n>o;o++)if((i||o in s)&&s[o]===t)return i||o||0;return!i&&-1}},th={includes:ja(!0),indexOf:ja(!1)},ih=Ce,Nr=je,rh=si,sh=th.indexOf,ah=Hs,Ha=ih([].push),nh=function(i,e){var t=rh(i),r=0,s=[],n;for(n in t)!Nr(ah,n)&&Nr(t,n)&&Ha(s,n);for(;e.length>r;)Nr(t,n=e[r++])&&(~sh(s,n)||Ha(s,n));return s},Co=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],oh=nh,lh=Co,uh=Object.keys||function(e){return oh(e,lh)},dh=Ue,ch=fo,hh=ct,fh=Xe,ph=si,mh=uh;No.f=dh&&!ch?Object.defineProperties:function(e,t){fh(e);for(var r=ph(t),s=mh(t),n=s.length,o=0,l;n>o;)hh.f(e,l=s[o++],r[l]);return e};var vh=ht,Do=vh("document","documentElement"),Sh=Xe,bh=No,Ga=Co,gh=Hs,yh=Do,Th=Ls,Eh=js,Ya=">",qa="<",Ss="prototype",bs="script",Oo=Eh("IE_PROTO"),Cr=function(){},Lo=function(i){return qa+bs+Ya+i+qa+"/"+bs+Ya},za=function(i){i.write(Lo("")),i.close();var e=i.parentWindow.Object;return i=null,e},$h=function(){var i=Th("iframe"),e="java"+bs+":",t;return i.style.display="none",yh.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Lo("document.F=Object")),t.close(),t.F},yi,Mi=function(){try{yi=new ActiveXObject("htmlfile")}catch(e){}Mi=typeof document!="undefined"?document.domain&&yi?za(yi):$h():za(yi);for(var i=Ga.length;i--;)delete Mi[Ss][Ga[i]];return Mi()};gh[Oo]=!0;var xo=Object.create||function(e,t){var r;return e!==null?(Cr[Ss]=Sh(e),r=new Cr,Cr[Ss]=null,r[Oo]=e):r=Mi(),t===void 0?r:bh.f(r,t)},kh=ye,Ph=!kh(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),Ah=je,wh=se,_h=Fs,Rh=js,Ih=Ph,Wa=Rh("IE_PROTO"),gs=Object,Nh=gs.prototype,Bo=Ih?gs.getPrototypeOf:function(i){var e=_h(i);if(Ah(e,Wa))return e[Wa];var t=e.constructor;return wh(t)&&e instanceof t?t.prototype:e instanceof gs?Nh:null},Ch=ai,Ws=function(i,e,t,r){return r&&r.enumerable?i[e]=t:Ch(i,e,t),i},Dh=ye,Oh=se,Lh=Ke,xh=xo,Qa=Bo,Bh=Ws,Mh=pe,ys=Mh("iterator"),Mo=!1,Ve,Dr,Or;[].keys&&(Or=[].keys(),"next"in Or?(Dr=Qa(Qa(Or)),Dr!==Object.prototype&&(Ve=Dr)):Mo=!0);var Vh=!Lh(Ve)||Dh(function(){var i={};return Ve[ys].call(i)!==i});Vh?Ve={}:Ve=xh(Ve);Oh(Ve[ys])||Bh(Ve,ys,function(){return this});var Vo={IteratorPrototype:Ve,BUGGY_SAFARI_ITERATORS:Mo},Fh=pe,Uh=Fh("toStringTag"),Fo={};Fo[Uh]="z";var Qs=String(Fo)==="[object z]",jh=Qs,Hh=se,Vi=tr,Gh=pe,Yh=Gh("toStringTag"),qh=Object,zh=Vi(function(){return arguments}())=="Arguments",Wh=function(i,e){try{return i[e]}catch(t){}},or=jh?Vi:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=Wh(e=qh(i),Yh))=="string"?t:zh?Vi(e):(r=Vi(e))=="Object"&&Hh(e.callee)?"Arguments":r},Qh=Qs,Jh=or,Kh=Qh?{}.toString:function(){return"[object "+Jh(this)+"]"},Xh=Qs,Zh=ct.f,ef=ai,tf=je,rf=Kh,sf=pe,Ja=sf("toStringTag"),Js=function(i,e,t,r){if(i){var s=t?i:i.prototype;tf(s,Ja)||Zh(s,Ja,{configurable:!0,value:e}),r&&!Xh&&ef(s,"toString",rf)}},af=Vo.IteratorPrototype,nf=xo,of=ar,lf=Js,uf=Ct,df=function(){return this},cf=function(i,e,t,r){var s=e+" Iterator";return i.prototype=nf(af,{next:of(+!r,t)}),lf(i,s,!1,!0),uf[s]=df,i},hf=De,ff=ke,Uo=Vc,pf=cf,mf=Bo,vf=Js,Ka=Ws,Sf=pe,Xa=Ct,jo=Vo,bf=Uo.PROPER;Uo.CONFIGURABLE;jo.IteratorPrototype;var Ti=jo.BUGGY_SAFARI_ITERATORS,Lr=Sf("iterator"),Za="keys",Ei="values",en="entries",gf=function(){return this},yf=function(i,e,t,r,s,n,o){pf(t,e,r);var l=function(b){if(b===s&&f)return f;if(!Ti&&b in c)return c[b];switch(b){case Za:return function(){return new t(this,b)};case Ei:return function(){return new t(this,b)};case en:return function(){return new t(this,b)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=i.prototype,h=c[Lr]||c["@@iterator"]||s&&c[s],f=!Ti&&h||l(s),p=e=="Array"&&c.entries||h,v,m,S;if(p&&(v=mf(p.call(new i)),v!==Object.prototype&&v.next&&(vf(v,d,!0,!0),Xa[d]=gf)),bf&&s==Ei&&h&&h.name!==Ei&&(u=!0,f=function(){return ff(h,this)}),s)if(m={values:l(Ei),keys:n?f:l(Za),entries:l(en)},o)for(S in m)(Ti||u||!(S in c))&&Ka(c,S,m[S]);else hf({target:e,proto:!0,forced:Ti||u},m);return o&&c[Lr]!==f&&Ka(c,Lr,f,{name:s}),Xa[e]=f,m},Tf=function(i,e){return{value:i,done:e}},Ef=si,Ks=Iu,tn=Ct,Ho=Eo,$f=ct.f,kf=yf,$i=Tf,Pf=go,Af=Ue,Go="Array Iterator",wf=Ho.set,_f=Ho.getterFor(Go);kf(Array,"Array",function(i,e){wf(this,{type:Go,target:Ef(i),index:0,kind:e})},function(){var i=_f(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,$i(void 0,!0)):t=="keys"?$i(r,!1):t=="values"?$i(e[r],!1):$i([r,e[r]],!1)},"values");var rn=tn.Arguments=tn.Array;Ks();Ks();Ks();if(!Pf&&Af&&rn.name!=="values")try{$f(rn,"name",{value:"values"})}catch(i){}var Rf=pe,If=Ct,Nf=Rf("iterator"),Cf=Array.prototype,Df=function(i){return i!==void 0&&(If.Array===i||Cf[Nf]===i)},Of=or,sn=Ms,Lf=ir,xf=Ct,Bf=pe,Mf=Bf("iterator"),Yo=function(i){if(!Lf(i))return sn(i,Mf)||sn(i,"@@iterator")||xf[Of(i)]},Vf=ke,Ff=ft,Uf=Xe,jf=sr,Hf=Yo,Gf=TypeError,Yf=function(i,e){var t=arguments.length<2?Hf(i):e;if(Ff(t))return Uf(Vf(t,i));throw Gf(jf(i)+" is not iterable")},qf=ke,an=Xe,zf=Ms,Wf=function(i,e,t){var r,s;an(i);try{if(r=zf(i,"return"),!r){if(e==="throw")throw t;return t}r=qf(r,i)}catch(n){s=!0,r=n}if(e==="throw")throw t;if(s)throw r;return an(r),t},Qf=nr,Jf=ke,Kf=Xe,Xf=sr,Zf=Df,ep=zs,nn=Bs,tp=Yf,ip=Yo,on=Wf,rp=TypeError,Fi=function(i,e){this.stopped=i,this.result=e},ln=Fi.prototype,Xs=function(i,e,t){var r=t&&t.that,s=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),d=Qf(e,r),u,c,h,f,p,v,m,S=function(g){return u&&on(u,"normal",g),new Fi(!0,g)},b=function(g){return s?(Kf(g),l?d(g[0],g[1],S):d(g[0],g[1])):l?d(g,S):d(g)};if(n)u=i.iterator;else if(o)u=i;else{if(c=ip(i),!c)throw rp(Xf(i)+" is not iterable");if(Zf(c)){for(h=0,f=ep(i);f>h;h++)if(p=b(i[h]),p&&nn(ln,p))return p;return new Fi(!1)}u=tp(i,c)}for(v=n?i.next:u.next;!(m=Jf(v,u)).done;){try{p=b(m.value)}catch(g){on(u,"throw",g)}if(typeof p=="object"&&p&&nn(ln,p))return p}return new Fi(!1)},sp=Us,ap=ct,np=ar,op=function(i,e,t){var r=sp(e);r in i?ap.f(i,r,np(0,t)):i[r]=t},lp=De,up=Xs,dp=op;lp({target:"Object",stat:!0},{fromEntries:function(e){var t={};return up(e,function(r,s){dp(t,r,s)},{AS_ENTRIES:!0}),t}});var cp=xs,hp=cp.Object.fromEntries,fp={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},pp=fp,mp=le,vp=or,Sp=ai,un=Ct,bp=pe,dn=bp("toStringTag");for(var xr in pp){var cn=mp[xr],Br=cn&&cn.prototype;Br&&vp(Br)!==dn&&Sp(Br,dn,xr),un[xr]=un.Array}var gp=hp,yp=gp,Tp=yp,Ep=Tp,oi=Ep,$p=tr,lr=typeof process!="undefined"&&$p(process)=="process",kp=ht,Pp=ct,Ap=pe,wp=Ue,hn=Ap("species"),_p=function(i){var e=kp(i),t=Pp.f;wp&&e&&!e[hn]&&t(e,hn,{configurable:!0,get:function(){return this}})},Rp=Bs,Ip=TypeError,Np=function(i,e){if(Rp(e,i))return i;throw Ip("Incorrect invocation")},Cp=Ce,Dp=se,Ts=Vs,Op=Cp(Function.toString);Dp(Ts.inspectSource)||(Ts.inspectSource=function(i){return Op(i)});var qo=Ts.inspectSource,Lp=Ce,xp=ye,zo=se,Bp=or,Mp=ht,Vp=qo,Wo=function(){},Fp=[],Qo=Mp("Reflect","construct"),Zs=/^\s*(?:class|function)\b/,Up=Lp(Zs.exec),jp=!Zs.exec(Wo),qt=function(e){if(!zo(e))return!1;try{return Qo(Wo,Fp,e),!0}catch(t){return!1}},Jo=function(e){if(!zo(e))return!1;switch(Bp(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return jp||!!Up(Zs,Vp(e))}catch(t){return!0}};Jo.sham=!0;var Hp=!Qo||xp(function(){var i;return qt(qt.call)||!qt(Object)||!qt(function(){i=!0})||i})?Jo:qt,Gp=Hp,Yp=sr,qp=TypeError,zp=function(i){if(Gp(i))return i;throw qp(Yp(i)+" is not a constructor")},fn=Xe,Wp=zp,Qp=ir,Jp=pe,Kp=Jp("species"),Ko=function(i,e){var t=fn(i).constructor,r;return t===void 0||Qp(r=fn(t)[Kp])?e:Wp(r)},Xp=Ce,Zp=Xp([].slice),em=TypeError,tm=function(i,e){if(i<e)throw em("Not enough arguments");return i},im=rr,Xo=/(?:ipad|iphone|ipod).*applewebkit/i.test(im),fe=le,rm=ko,sm=nr,pn=se,am=je,Zo=ye,mn=Do,nm=Zp,vn=Ls,om=tm,lm=Xo,um=lr,Es=fe.setImmediate,$s=fe.clearImmediate,dm=fe.process,Mr=fe.Dispatch,cm=fe.Function,Sn=fe.MessageChannel,hm=fe.String,Vr=0,Kt={},bn="onreadystatechange",ri,nt,Fr,Ur;Zo(function(){ri=fe.location});var ea=function(i){if(am(Kt,i)){var e=Kt[i];delete Kt[i],e()}},jr=function(i){return function(){ea(i)}},gn=function(i){ea(i.data)},yn=function(i){fe.postMessage(hm(i),ri.protocol+"//"+ri.host)};(!Es||!$s)&&(Es=function(e){om(arguments.length,1);var t=pn(e)?e:cm(e),r=nm(arguments,1);return Kt[++Vr]=function(){rm(t,void 0,r)},nt(Vr),Vr},$s=function(e){delete Kt[e]},um?nt=function(i){dm.nextTick(jr(i))}:Mr&&Mr.now?nt=function(i){Mr.now(jr(i))}:Sn&&!lm?(Fr=new Sn,Ur=Fr.port2,Fr.port1.onmessage=gn,nt=sm(Ur.postMessage,Ur)):fe.addEventListener&&pn(fe.postMessage)&&!fe.importScripts&&ri&&ri.protocol!=="file:"&&!Zo(yn)?(nt=yn,fe.addEventListener("message",gn,!1)):bn in vn("script")?nt=function(i){mn.appendChild(vn("script"))[bn]=function(){mn.removeChild(this),ea(i)}}:nt=function(i){setTimeout(jr(i),0)});var el={set:Es,clear:$s},tl=function(){this.head=null,this.tail=null};tl.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};var il=tl,fm=rr,pm=/ipad|iphone|ipod/i.test(fm)&&typeof Pebble!="undefined",mm=rr,vm=/web0s(?!.*chrome)/i.test(mm),dt=le,Tn=nr,Sm=Gs.f,Hr=el.set,bm=il,gm=Xo,ym=pm,Tm=vm,Gr=lr,En=dt.MutationObserver||dt.WebKitMutationObserver,$n=dt.document,kn=dt.process,ki=dt.Promise,Pn=Sm(dt,"queueMicrotask"),ks=Pn&&Pn.value,Tt,Yr,qr,Pi,An;if(!ks){var Ai=new bm,wi=function(){var i,e;for(Gr&&(i=kn.domain)&&i.exit();e=Ai.get();)try{e()}catch(t){throw Ai.head&&Tt(),t}i&&i.enter()};!gm&&!Gr&&!Tm&&En&&$n?(Yr=!0,qr=$n.createTextNode(""),new En(wi).observe(qr,{characterData:!0}),Tt=function(){qr.data=Yr=!Yr}):!ym&&ki&&ki.resolve?(Pi=ki.resolve(void 0),Pi.constructor=ki,An=Tn(Pi.then,Pi),Tt=function(){An(wi)}):Gr?Tt=function(){kn.nextTick(wi)}:(Hr=Tn(Hr,dt),Tt=function(){Hr(wi)}),ks=function(i){Ai.head||Tt(),Ai.add(i)}}var Em=ks,$m=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},ta=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},km=le,Dt=km.Promise,rl=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",Pm=rl,Am=lr,wm=!Pm&&!Am&&typeof window=="object"&&typeof document=="object",_m=le,Xt=Dt,Rm=se,Im=Ro,Nm=qo,Cm=pe,Dm=wm,Om=rl,zr=mo,wn=Xt&&Xt.prototype,Lm=Cm("species"),Ps=!1,sl=Rm(_m.PromiseRejectionEvent),xm=Im("Promise",function(){var i=Nm(Xt),e=i!==String(Xt);if(!e&&zr===66||!(wn.catch&&wn.finally))return!0;if(!zr||zr<51||!/native code/.test(i)){var t=new Xt(function(n){n(1)}),r=function(n){n(function(){},function(){})},s=t.constructor={};if(s[Lm]=r,Ps=t.then(function(){})instanceof r,!Ps)return!0}return!e&&(Dm||Om)&&!sl}),li={CONSTRUCTOR:xm,REJECTION_EVENT:sl,SUBCLASSING:Ps},Ot={},_n=ft,Bm=TypeError,Mm=function(i){var e,t;this.promise=new i(function(r,s){if(e!==void 0||t!==void 0)throw Bm("Bad Promise constructor");e=r,t=s}),this.resolve=_n(e),this.reject=_n(t)};Ot.f=function(i){return new Mm(i)};var Vm=De,zi=lr,Je=le,ui=ke,Fm=Ws,Um=Js,jm=_p,Hm=ft,As=se,Gm=Ke,Ym=Np,qm=Ko,al=el.set,ia=Em,zm=$m,Wm=ta,Qm=il,nl=Eo,ws=Dt,ra=li,ol=Ot,ur="Promise",ll=ra.CONSTRUCTOR,Jm=ra.REJECTION_EVENT;ra.SUBCLASSING;var Wr=nl.getterFor(ur),Km=nl.set,Xm=ws&&ws.prototype,$t=ws,Qr=Xm,ul=Je.TypeError,_s=Je.document,sa=Je.process,Rs=ol.f,Zm=Rs,ev=!!(_s&&_s.createEvent&&Je.dispatchEvent),dl="unhandledrejection",tv="rejectionhandled",Rn=0,cl=1,iv=2,aa=1,hl=2,_i,In,rv,fl=function(i){var e;return Gm(i)&&As(e=i.then)?e:!1},pl=function(i,e){var t=e.value,r=e.state==cl,s=r?i.ok:i.fail,n=i.resolve,o=i.reject,l=i.domain,d,u,c;try{s?(r||(e.rejection===hl&&av(e),e.rejection=aa),s===!0?d=t:(l&&l.enter(),d=s(t),l&&(l.exit(),c=!0)),d===i.promise?o(ul("Promise-chain cycle")):(u=fl(d))?ui(u,d,n,o):n(d)):o(t)}catch(h){l&&!c&&l.exit(),o(h)}},ml=function(i,e){i.notified||(i.notified=!0,ia(function(){for(var t=i.reactions,r;r=t.get();)pl(r,i);i.notified=!1,e&&!i.rejection&&sv(i)}))},vl=function(i,e,t){var r,s;ev?(r=_s.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),Je.dispatchEvent(r)):r={promise:e,reason:t},!Jm&&(s=Je["on"+i])?s(r):i===dl&&zm("Unhandled promise rejection",t)},sv=function(i){ui(al,Je,function(){var e=i.facade,t=i.value,r=Nn(i),s;if(r&&(s=Wm(function(){zi?sa.emit("unhandledRejection",t,e):vl(dl,e,t)}),i.rejection=zi||Nn(i)?hl:aa,s.error))throw s.value})},Nn=function(i){return i.rejection!==aa&&!i.parent},av=function(i){ui(al,Je,function(){var e=i.facade;zi?sa.emit("rejectionHandled",e):vl(tv,e,i.value)})},kt=function(i,e,t){return function(r){i(e,r,t)}},At=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=iv,ml(i,!0))},Is=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw ul("Promise can't be resolved itself");var r=fl(e);r?ia(function(){var s={done:!1};try{ui(r,e,kt(Is,s,i),kt(At,s,i))}catch(n){At(s,n,i)}}):(i.value=e,i.state=cl,ml(i,!1))}catch(s){At({done:!1},s,i)}}};ll&&($t=function(e){Ym(this,Qr),Hm(e),ui(_i,this);var t=Wr(this);try{e(kt(Is,t),kt(At,t))}catch(r){At(t,r)}},Qr=$t.prototype,_i=function(e){Km(this,{type:ur,done:!1,notified:!1,parent:!1,reactions:new Qm,rejection:!1,state:Rn,value:void 0})},_i.prototype=Fm(Qr,"then",function(e,t){var r=Wr(this),s=Rs(qm(this,$t));return r.parent=!0,s.ok=As(e)?e:!0,s.fail=As(t)&&t,s.domain=zi?sa.domain:void 0,r.state==Rn?r.reactions.add(s):ia(function(){pl(s,r)}),s.promise}),In=function(){var i=new _i,e=Wr(i);this.promise=i,this.resolve=kt(Is,e),this.reject=kt(At,e)},ol.f=Rs=function(i){return i===$t||i===rv?new In(i):Zm(i)});Vm({global:!0,constructor:!0,wrap:!0,forced:ll},{Promise:$t});Um($t,ur,!1,!0);jm(ur);var nv=pe,Sl=nv("iterator"),bl=!1;try{var ov=0,Cn={next:function(){return{done:!!ov++}},return:function(){bl=!0}};Cn[Sl]=function(){return this},Array.from(Cn,function(){throw 2})}catch(i){}var lv=function(i,e){if(!e&&!bl)return!1;var t=!1;try{var r={};r[Sl]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch(s){}return t},uv=Dt,dv=lv,cv=li.CONSTRUCTOR,gl=cv||!dv(function(i){uv.all(i).then(void 0,function(){})}),hv=De,fv=ke,pv=ft,mv=Ot,vv=ta,Sv=Xs,bv=gl;hv({target:"Promise",stat:!0,forced:bv},{all:function(e){var t=this,r=mv.f(t),s=r.resolve,n=r.reject,o=vv(function(){var l=pv(t.resolve),d=[],u=0,c=1;Sv(e,function(h){var f=u++,p=!1;c++,fv(l,t,h).then(function(v){p||(p=!0,d[f]=v,--c||s(d))},n)}),--c||s(d)});return o.error&&n(o.value),r.promise}});var gv=De,yv=li.CONSTRUCTOR,Dn=Dt;Dn&&Dn.prototype;gv({target:"Promise",proto:!0,forced:yv,real:!0},{catch:function(i){return this.then(void 0,i)}});var Tv=De,Ev=ke,$v=ft,kv=Ot,Pv=ta,Av=Xs,wv=gl;Tv({target:"Promise",stat:!0,forced:wv},{race:function(e){var t=this,r=kv.f(t),s=r.reject,n=Pv(function(){var o=$v(t.resolve);Av(e,function(l){Ev(o,t,l).then(r.resolve,s)})});return n.error&&s(n.value),r.promise}});var _v=De,Rv=ke,Iv=Ot,Nv=li.CONSTRUCTOR;_v({target:"Promise",stat:!0,forced:Nv},{reject:function(e){var t=Iv.f(this);return Rv(t.reject,void 0,e),t.promise}});var Cv=Xe,Dv=Ke,Ov=Ot,yl=function(i,e){if(Cv(i),Dv(e)&&e.constructor===i)return e;var t=Ov.f(i),r=t.resolve;return r(e),t.promise},Lv=De,xv=ht,Bv=go,Mv=Dt,Vv=li.CONSTRUCTOR,Fv=yl,Uv=xv("Promise"),jv=!Vv;Lv({target:"Promise",stat:!0,forced:Bv},{resolve:function(e){return Fv(jv&&this===Uv?Mv:this,e)}});var Hv=De,Ns=Dt,Gv=ye,Yv=ht,qv=se,zv=Ko,On=yl,Wv=Ns&&Ns.prototype,Qv=!!Ns&&Gv(function(){Wv.finally.call({then:function(){}},function(){})});Hv({target:"Promise",proto:!0,real:!0,forced:Qv},{finally:function(i){var e=zv(this,Yv("Promise")),t=qv(i);return this.then(t?function(r){return On(e,i()).then(function(){return r})}:i,t?function(r){return On(e,i()).then(function(){throw r})}:i)}});var Jv=ht,Tl=Jv,Kv=Tl,Xv=Kv("Promise","finally"),Zv=Xv,eS=Zv,tS=eS,iS=tS,dr=iS,wt;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(wt||(wt={}));var _t=(i,e=0,t=wt.OFFSET_P)=>{switch(t){case wt.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case wt.PLAYBACK_SHIFT:{if(e===0)return i;const r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}default:a.assertNever(t)}return i},k=(i,e,t=!1)=>{const r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};exports.VideoQuality=void 0;(function(i){i.INVARIANT="Invariant quality",i.Q_144P="144p",i.Q_240P="240p",i.Q_360P="360p",i.Q_480P="480p",i.Q_720P="720p",i.Q_1080P="1080p",i.Q_1440P="1440p",i.Q_2160P="2160p",i.Q_4320P="4320p"})(exports.VideoQuality||(exports.VideoQuality={}));const $e={[exports.VideoQuality.Q_144P]:{width:256,height:144},[exports.VideoQuality.Q_240P]:{width:428,height:240},[exports.VideoQuality.Q_360P]:{width:640,height:360},[exports.VideoQuality.Q_480P]:{width:856,height:480},[exports.VideoQuality.Q_720P]:{width:1280,height:720},[exports.VideoQuality.Q_1080P]:{width:1920,height:1080},[exports.VideoQuality.Q_1440P]:{width:2560,height:1440},[exports.VideoQuality.Q_2160P]:{width:3840,height:2160},[exports.VideoQuality.Q_4320P]:{width:7680,height:4320}},Ui=(i,e)=>$e[i].height>$e[e].height,rS=(i,e)=>$e[i].height>=$e[e].height,Zt=(i,e)=>$e[i].height<$e[e].height,sS=(i,e)=>$e[i].height<=$e[e].height,aS=i=>i.sort((e,t)=>e===t?0:e===exports.VideoQuality.INVARIANT?1:t===exports.VideoQuality.INVARIANT?-1:Zt(e,t)?1:-1)[0],nS=Object.keys($e).sort((i,e)=>Zt(i,e)?-1:1),pt=({width:i,height:e})=>{const t=Math.min(i,e),r=Math.max(i,e);return nS.find(s=>{const n=$e[s];return n.width>=r&&n.height>=t})},oS=i=>$e[i].height,Wi=i=>i===exports.VideoQuality.INVARIANT;class Q{constructor(e){this.transitionStarted$=new a.Subject,this.transitionEnded$=new a.Subject,this.transitionUpdated$=new a.Subject,this.forceChanged$=new a.Subject,this.stateChangeStarted$=a.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=a.merge(this.transitionEnded$,this.forceChanged$),this.state=e}setState(e){const t=this.transition,r=this.state;this.transition=void 0,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,r=this.state;r===e||a.isNonNullable(t)&&t.to===e||(this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}const lS=i=>{switch(i){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return a.assertNever(i)}};var L;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(L||(L={}));const uS=5,dS=5,cS=500,Ln=7e3;class hS{constructor(e){this.subscription=new a.Subscription,this.loadMediaTimeoutSubscription=new a.Subscription,this.videoState=new Q(L.STOPPED),this.syncPlayback=()=>{const r=this.videoState.getState(),s=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${r}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){r!==L.STOPPED&&(this.videoState.startTransitionTo(L.STOPPED),this.stop());return}if(!s){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===C.Requested&&r!==L.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(r){case L.PLAYING:case L.PAUSED:case L.READY:break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:a.assertNever(r)}break}case exports.PlaybackState.PLAYING:{switch(r){case L.PLAYING:break;case L.PAUSED:this.videoState.startTransitionTo(L.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case L.READY:this.videoState.startTransitionTo(L.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:a.assertNever(r)}break}case exports.PlaybackState.PAUSED:{switch(r){case L.PLAYING:this.videoState.startTransitionTo(L.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case L.PAUSED:break;case L.READY:this.videoState.startTransitionTo(L.PAUSED),this.videoState.setState(L.PAUSED);break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:a.assertNever(r)}break}default:a.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(lS(e.format)),this.params.output.isAudioTracksExist$.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 a.Subscription;this.subscription.add(e),this.subscription.add(a.merge(this.videoState.stateChangeStarted$.pipe(a.map(s=>`stateChangeStarted$ ${JSON.stringify(s)}`)),this.videoState.stateChangeEnded$.pipe(a.map(s=>`stateChangeEnded$ ${JSON.stringify(s)}`))).subscribe(s=>this.log({message:`[videoState] ${s}`})));const t=(s,n)=>this.subscription.add(s.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const s=new a.Subject;e.add(s.pipe(a.debounce(cS)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(o=>{this.logRemoteEvent(o);const l=o.value;this.params.output.position$.next(l),(this.params.desiredState.seekState.getState().state===C.Applying||Math.abs(l-n)>uS)&&s.next(l),n=l})),e.add(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemotePause():this.handleRemotePlay()}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),s=>{this.logRemoteEvent(s);const{remotePlayer:n}=this.params.connection,o=s.value,l=this.params.output.isBuffering$.getValue(),d=o===chrome.cast.media.PlayerState.BUFFERING;switch(l!==d&&this.params.output.isBuffering$.next(d),o){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&n.duration-n.currentTime<dS&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:a.assertNever(o)}}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({volume:s.value})}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({muted:s.value})});const r=a.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(L.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(L.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:C.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===L.PAUSED||e===L.PLAYING)&&(this.videoState.setState(L.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===L.PLAYING||e===L.PAUSED)&&(this.videoState.setState(L.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===L.READY&&this.videoState.setState(L.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===exports.PlaybackState.READY&&k(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==L.STOPPED&&this.videoState.setState(L.STOPPED)}handleRemoteVolumeChange(e){var t,r;const s=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:s.volume,muted:(r=e.muted)!==null&&r!==void 0?r:s.muted};(n.volume!==s.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const r=this.params.source;let s,n,o;switch(e){case exports.VideoFormat.MPEG:{const c=r[e];a.assertNonNullable(c);const h=aS(Object.keys(c));a.assertNonNullable(h);const f=c[h];a.assertNonNullable(f),s=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=r[e];a.assertNonNullable(c),s=c.url,n="application/x-mpegurl",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:{const c=r[e];a.assertNonNullable(c),s=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS_LIVE:{const c=r[e];a.assertNonNullable(c),s=_t(c.url),n="application/x-mpegurl",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const c="Unsupported format for Chromecast",h=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:a.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:h}),h}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}const l=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:s,n);l.contentUrl=s,l.streamType=o,l.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:d,subtitle:u}=this.params.meta;return a.isNonNullable(d)&&(l.metadata.title=d),a.isNonNullable(u)&&(l.metadata.subtitle=u),l}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const r=this.params.desiredState.seekState.getState();return r.state===C.Applying||r.state===C.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),r=new Promise((s,n)=>{this.loadMediaTimeoutSubscription.add(a.timeout(Ln).subscribe(()=>n(`timeout(${Ln})`)))});dr(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===C.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},s=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${s}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:a.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:s})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}function J(i,e,t,r){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function l(c){try{u(r.next(c))}catch(h){o(h)}}function d(c){try{u(r.throw(c))}catch(h){o(h)}}function u(c){c.done?n(c.value):s(c.value).then(l,d)}u((r=r.apply(i,e||[])).next())})}function R(i){return this instanceof R?(this.v=i,this):new R(i)}function Ee(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(i,e||[]),s,n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(f){r[f]&&(s[f]=function(p){return new Promise(function(v,m){n.push([f,p,v,m])>1||l(f,p)})})}function l(f,p){try{d(r[f](p))}catch(v){h(n[0][3],v)}}function d(f){f.value instanceof R?Promise.resolve(f.value.v).then(u,c):h(n[0][2],f)}function u(f){l("next",f)}function c(f){l("throw",f)}function h(f,p){f(p),n.shift(),n.length&&l(n[0][0],n[0][1])}}class xn{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;const r=this.listeners[e];for(let s=0,n=r.length;s<n;s++)if(r[s].callback===t){r.splice(s,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const r=this.listeners[e.type].slice();for(let s=0,n=r.length;s<n;s++){const o=r[s];try{o.callback.call(this,e)}catch(l){Promise.resolve().then(()=>{throw l})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class El extends xn{constructor(){super(),this.listeners||xn.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}let $l=class{constructor(){Object.defineProperty(this,"signal",{value:new El,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(s){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(s){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&($l.prototype[Symbol.toStringTag]="AbortController",El.prototype[Symbol.toStringTag]="AbortSignal");function kl(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function fS(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=i;if(!kl({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||s)&&(n=function(u,c){let h;c&&c.signal&&(h=c.signal,delete c.signal);const f=new t(u,c);return h&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),f},n.prototype=t.prototype);const o=e;return{fetch:(d,u)=>{const c=n&&n.prototype.isPrototypeOf(d)?d.signal:u?u.signal:void 0;if(c){let h;try{h=new DOMException("Aborted","AbortError")}catch(p){h=new Error("Aborted"),h.name="AbortError"}if(c.aborted)return Promise.reject(h);const f=new Promise((p,v)=>{c.addEventListener("abort",()=>v(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,o(d,u)])}return o(d,u)},Request:n}}const cr=kl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Pl=cr?fS({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Rt=cr?Pl.fetch:window.fetch;cr?Pl.Request:window.Request;const lt=cr?$l:window.AbortController,zt=i=>i.range?i.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class ei{constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){var t;const{url:r}=e.request,s=(t=this.dashJsRequestQueue.get(r))!==null&&t!==void 0?t:[];s.push(e),this.dashJsRequestQueue.set(r,s)}executeNextRequests(){return J(this,void 0,void 0,function*(){for(const[e,t]of this.dashJsRequestQueue.entries()){const r=this.activeRequests.get(e);if(r){t.length&&this.onBigRequestProgress(r);const s=t[0];if(!s||!s.request.range)continue;const[n,o]=zt(s.request);if(n>=r.from&&o<=r.to)continue;this.activeRequests.delete(e)}if(t.length){const s=this.sendBigRequest(e,t.map(({request:n})=>n));this.activeRequests.set(e,s)}}})}abort(e){var t;if(e){const{request:r}=e,s=((t=this.dashJsRequestQueue.get(r.url))!==null&&t!==void 0?t:[]).includes(e),n=this.activeRequests.get(r.url);s&&n&&n.abortController.abort()}else for(const{abortController:r}of this.activeRequests.values())r.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const r=t.map(zt),s=r[0][0];let n=r[0][1];for(let f=1;f<r.length&&n<this.params.minDataSize;f++){const p=r[f][1];p-s<=2*this.params.minDataSize&&(n=Math.max(n,p))}s===0?n=Math.max(n,s+this.params.minInitSize):n=Math.max(n,s+this.params.minDataSize);const o=new URL(e,location.href);o.searchParams.append("bytes",`${s}-${n}`);const l=o.toString(),d=new lt,u=d.signal,c={url:e,from:s,to:n,loaded:0,data:null,abortController:d};u.addEventListener("abort",()=>this.onBigRequestAbort(c));const h=f=>{var p,v;throw(v=(p=this.params).onError)===null||v===void 0||v.call(p,{id:"BigRequestParsing",category:a.ErrorCategory.PARSER,message:"Error parsing response data",thrown:f}),f};return Rt(l,{signal:u}).then(f=>{var p,v,m;if(c.response=f,!f.ok||!f.body){this.onBigRequestError(c);return}const[S,b]=f.body.tee();(v=(p=this.params).onDownloadStream)===null||v===void 0||v.call(p,b);const g=S.getReader(),P=parseInt((m=f.headers.get("Content-Length"))!==null&&m!==void 0?m:"",10)||n-s+1;c.data=new ArrayBuffer(P);const E=new Uint8Array(c.data),T=({done:w,value:F})=>J(this,void 0,void 0,function*(){w?this.onBigRequestProgress(c):F&&(E.set(F,c.loaded),c.loaded+=F.byteLength,this.onBigRequestProgress(c),yield g==null?void 0:g.read().then(T,ei.suppressStreamErrors).catch(h))});g==null||g.read().then(T,ei.suppressStreamErrors).catch(h)},ei.suppressAbort).catch(f=>this.onBigRequestError(c,f)),c}onBigRequestProgress({url:e,from:t,to:r,loaded:s,data:n,response:o}){var l,d,u,c,h,f,p,v;if(!this.activeRequests.has(e)||!n)return;const m=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const S of m){const{request:b}=S,[g,P]=zt(b),E=g>=t&&P<=t+s,T=t>=g&&t+s<P,w=n.slice(g-t,Math.min(P-t+1,s));if((E||T)&&(b.requestStartDate=(d=b.requestStartDate)!==null&&d!==void 0?d:new Date,b.firstByteDate=(u=b.firstByteDate)!==null&&u!==void 0?u:new Date,b.bytesLoaded=w.byteLength,b.bytesTotal=r-t),E){b.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((c=this.dashJsRequestQueue.get(e))!==null&&c!==void 0?c:[]).filter(O=>O!==S)),(h=S.success)===null||h===void 0||h.call(S,w,"",e);const F=o?Array.from(o.headers.entries()).map(([O,I])=>`${O}: ${I}`).join(`\r
7
- `):"";(f=this.dashMetrics)===null||f===void 0||f.addHttpRequest(b,e,(p=o==null?void 0:o.status)!==null&&p!==void 0?p:200,F,[])}else T&&((v=S.progress)===null||v===void 0||v.call(S,{loaded:s,total:r-t,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:t,to:r},s){var n,o,l,d;if((o=(n=this.params).onError)===null||o===void 0||o.call(n,{id:"BigRequest",category:a.ErrorCategory.NETWORK,message:"Download error",thrown:s}),!this.activeRequests.has(e))return;const u=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const c of u){const[h,f]=zt(c.request);(h>=t&&h<r||f>t&&f<=r)&&((d=c==null?void 0:c.error)===null||d===void 0||d.call(c,c.request,String(s)))}if(this.activeRequests.delete(e),s)throw s}onBigRequestAbort({url:e,from:t,to:r}){var s,n;if(!this.activeRequests.has(e))return;const o=(s=this.dashJsRequestQueue.get(e))!==null&&s!==void 0?s:[];for(const l of o){const[d,u]=zt(l.request);(d>=t&&d<r||u>t&&u<=r)&&((n=l==null?void 0:l.abort)===null||n===void 0||n.call(l,l.request))}this.activeRequests.delete(e)}static suppressAbort(e){if(!(e instanceof DOMException)||!(e.name==="AbortError"||e.code===20))throw e}static suppressStreamErrors(){}}class Qi{constructor(e,t,r){this.baseLoader=e,this.config=r,this.bigRequest=t,t.setMetrics(r.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(Qi.shouldDelegateToBase(t))return this.baseLoader.load(e);this.bigRequest.queueDashJSRequest(e),this.bigRequest.executeNextRequests()}abort(e){if(!e){this.baseLoader.abort(),this.bigRequest.abort();return}const{request:t}=e;Qi.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const pS=(i,e)=>t=>({create:r=>{const s=i(t).create(r);return new Qi(s,e,r)}}),mS=(i,e)=>{const t=new ei(e);return i.extend("SchemeLoaderFactory",function(){const{parent:r}=this,s=r.getLoader;return{getLoader:n=>{const o=s(n);return pS(o,t)}}},!0),()=>t.destroy()};var vS=i=>{let e,t=!1,r=!1;i.on("playbackTimeUpdated",({timeToEnd:s})=>{r=s<=3,t&&r&&(e==null||e())}),i.extend("MediaSourceController",function(){const{parent:s}=this,n=s.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&r&&(e==null||e())}}},!0)},SS=i=>{const e=new a.ValueSubject(1/0),t=new a.Subject,r=new a.ValueSubject(void 0),s=new a.ValueSubject(void 0);let n=NaN,o=!1;const l=()=>{n=Date.now(),o=!1},d=c=>{var h,f,p,v,m;const S=oi(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(P=>P.split(": ")));if("x-playback-duration"in S||"x-playback-duration-millis"in S){const P=parseInt((h=c.getResponseHeader("X-Playback-Duration"))!==null&&h!==void 0?h:"",10),E=parseInt((f=c.getResponseHeader("X-Playback-Duration-Millis"))!==null&&f!==void 0?f:"",10),T=(p=E!=null?E:P*1e3)!==null&&p!==void 0?p:NaN;a.isNonNullable(T)&&!isNaN(T)&&e.next(T)}const b=(v=S["x-delivery-type"])!==null&&v!==void 0?v:exports.HttpConnectionType.HTTP1,g=(m={1:!0,0:!1}[S["x-reused"]])!==null&&m!==void 0?m:void 0;r.next(b),s.next(g)},u=c=>{c.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return i.extend("XHRLoader",function(){const{parent:c}=this,h=c.load.bind(c);return{load:function(f){if(f.request.type==="MPD"){const p=f.onload,v=f.progress;f.onload=function(...m){return d(this),p(...m)},f.progress=function(...m){return u(this),v(...m)},l()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:s,connectionType$:r}},It=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},bS=i=>i.extend("RequestModifier",()=>({modifyRequestURL:It}),!0),gS=i=>{i.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:r=>{if(r.request&&r.request.range){const[s,n]=r.request.range.split("-").map(l=>parseInt(l,10)),o=new URL(r.request.url,location.href);o.searchParams.append("bytes",`${s}-${n}`),r.request.url=o.toString(),r.request.range=void 0}t(r)}}},!0)};const Ne=(i,e,t,{equal:r=(o,l)=>o===l,changed$:s,onError:n}={})=>{const o=i.getState(),l=e(),d=a.isNullable(s),u=new a.Subscription;return s&&u.add(s.subscribe(c=>{const h=i.getState();r(c,h)&&i.setState(c)},n)),r(l,o)||(t(o),d&&i.setState(o)),u.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),d&&i.setState(c.to)},n)),u},mt=(i,e,t)=>Ne(e,()=>i.loop,r=>{a.isNonNullable(r)&&(i.loop=r)},{onError:t}),He=(i,e,t,r)=>Ne(e,()=>({muted:i.muted,volume:i.volume}),s=>{a.isNonNullable(s)&&(i.muted=s.muted,i.volume=s.volume)},{equal:(s,n)=>s===n||(s==null?void 0:s.muted)===(n==null?void 0:n.muted)&&(s==null?void 0:s.volume)===(n==null?void 0:n.volume),changed$:t,onError:r}),Ze=(i,e,t,r)=>Ne(e,()=>i.playbackRate,s=>{a.isNonNullable(s)&&(i.playbackRate=s)},{changed$:t,onError:r}),yS=i=>["__",i.language,i.label].join("|"),TS=(i,e)=>{if(i.id===e)return!0;const[t,r,s]=e.split("|");return i.language===r&&i.label===s};class Oe{constructor(){this.available$=new a.Subject,this.current$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.subscription=new a.Subscription,this.externalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const s=n=>{this.error$.next({id:"TextTracksManager",category:a.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Ne(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{a.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>a.isNonNullable(n)&&a.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},d)=>l===o[d].id),changed$:this.available$.pipe(a.map(n=>n.filter(({type:o})=>o==="external"))),onError:s})),this.subscription.add(Ne(t.currentTextTrack,()=>{if(this.video)return;const n=this.htmlTextTracksAsArray().find(({mode:o})=>o==="showing");return n&&this.htmlTextTrackToITextTrack(n).id},n=>this.select(n),{changed$:this.current$,onError:s})),this.subscription.add(Ne(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){a.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(a.fromEvent(e,"addtrack").subscribe(()=>{const r=this.current$.getValue();this.select(r)})),this.subscription.add(a.merge(a.fromEvent(e,"addtrack"),a.fromEvent(e,"removetrack"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),a.filterChanged((r,s)=>r.length===s.length&&r.every(({id:n},o)=>n===s[o].id))).subscribe(this.available$)),this.subscription.add(a.merge(a.fromEvent(e,"change"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),a.map(r=>r&&this.htmlTextTrackToITextTrack(r).id),a.filterChanged()).subscribe(this.current$));const t=r=>{var s,n;return this.applyCueSettings((n=(s=r.target)===null||s===void 0?void 0:s.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(a.fromEvent(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)===null||s===void 0||s.addEventListener("cuechange",t);const o=l=>{var d,u,c,h,f;const p=(u=(d=l.target)===null||d===void 0?void 0:d.cues)!==null&&u!==void 0?u:null;p&&p.length&&(this.applyCueSettings((h=(c=l.target)===null||c===void 0?void 0:c.cues)!==null&&h!==void 0?h:null),(f=l.target)===null||f===void 0||f.removeEventListener("cuechange",o))};(n=r.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(a.fromEvent(e,"removetrack").subscribe(r=>{var s;(s=r.track)===null||s===void 0||s.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const r of Array.from(e)){const s=r;a.isNonNullable(t.align)&&(s.align=t.align),a.isNonNullable(t.position)&&(s.position=t.position),a.isNonNullable(t.size)&&(s.size=t.size),a.isNonNullable(t.line)&&(s.line=t.line)}}htmlTextTracksAsArray(e=!1){a.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Oe.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:r}=e,s=e.id!==""?e.id:yS(e);return this.externalTracks.has(s)?{id:s,type:"external",language:t,label:r,url:this.externalTracks.get(s).url}:{id:s,type:"internal",language:t,label:r}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.id===""&&e.label===""&&e.language==="")}setExternal(e){e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks.keys()).filter(t=>!e.find(r=>r.id===t)).forEach(t=>this.detach(t))}select(e){a.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))a.isNonNullable(e)&&TS(t,e)?t.mode="showing":t.mode="disabled"}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){a.assertNonNullable(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),this.externalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){a.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e);t&&this.video.removeChild(t),this.externalTracks.delete(e)}}var Ge=i=>{const e=document.createElement("video");return e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i.appendChild(e),e};class na{constructor(){this.pausedTime=0,this.streamOffset=0,this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0}}var Al=()=>{const{userAgent:i}=window.navigator;return!/chrome/i.test(i)&&/webkit|safari|khtml/i.test(i)};const Cs=3;class ES{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,r=this._source.buffered.length;t<r;t++){let s=this._source.buffered.start(t);const n=this._source.buffered.end(t);s>e&&s-e<Cs&&(s=e),this._buffer.push({from:s,to:n,i:t})}return this._buffer.sort(function(t,r){return t.from-r.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const r=this.getNext(e);if(r&&r.from-e.to<(t||Cs))return r}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,r){this._buffer.forEach(({from:s,to:n})=>{const o=s>=e&&s<t,l=n>=e&&n<t;o&&l||(o?r(t,n):l?r(s,e):s<e&&n>t?(r(t,n),r(s,e)):r(s,n))})}destroy(){this._buffer=[]}}var wl=(i,e,t=Cs)=>{let r=0,s=0;for(let n=0;n<i.length;n++){const o=i.start(n),l=i.end(n);if(o<=e&&e<=l){if(r=o,s=l,!t)return{from:r,to:s};for(let d=n-1;d>=0;d--)i.end(d)+t>=r&&(r=i.start(d));for(let d=n+1;d<i.length;d++)i.start(d)-t<=s&&(s=i.end(d))}}return{from:r,to:s}};const Ye=i=>{const e=p=>a.fromEvent(i,p).pipe(a.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],r=a.merge(...t.map(p=>a.fromEvent(i,p))).pipe(a.map(p=>p.type==="ended"?i.readyState<2:i.readyState<3),a.filterChanged()),s=a.merge(a.fromEvent(i,"progress"),a.fromEvent(i,"timeupdate")).pipe(a.map(()=>wl(i.buffered,i.currentTime))),n=Al()?a.combine({play:e("play").pipe(a.once()),playing:e("playing")}).pipe(a.mapTo(void 0)):e("playing"),o=a.fromEvent(i,"volumechange").pipe(a.map(()=>({muted:i.muted,volume:i.volume}))),l=a.fromEvent(i,"ratechange").pipe(a.map(()=>i.playbackRate)),d=a.fromEvent(i,"error").pipe(a.filter(()=>Boolean(i.error||i.played.length)),a.map(()=>{var p;const v=i.error;return{id:v?`MediaError#${v.code}`:"HtmlVideoError",category:a.ErrorCategory.VIDEO_PIPELINE,message:v?v.message:"Error event from HTML video element",thrown:(p=i.error)!==null&&p!==void 0?p:void 0}})),u=a.fromEvent(i,"timeupdate").pipe(a.map(()=>i.currentTime)),c=new a.Subject,h=.3;let f;return u.subscribe(p=>{i.loop&&a.isNonNullable(f)&&a.isNonNullable(p)&&f>=i.duration-h&&p<=h&&c.next(f),f=p}),{playing$:n,pause$:e("pause").pipe(a.filter(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:u,durationChange$:a.fromEvent(i,"durationchange").pipe(a.map(()=>i.duration)),isBuffering$:r,currentBuffer$:s,volumeState$:o,playbackRateState$:l}},oa=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var $S=De,kS=Fs,PS=zs,AS=qs;$S({target:"Array",proto:!0},{at:function(e){var t=kS(this),r=PS(t),s=AS(e),n=s>=0?s:r+s;return n<0||n>=r?void 0:t[n]}});var wS=Tl,_S=wS("Array","at"),RS=_S,IS=RS,NS=IS,CS=NS,xe=CS;let la=!1,Be={};const DS=i=>{la=i},OS=()=>{Be={}},LS=i=>{i(Be)},Ri=(i,e)=>{var t;la&&(Be.meta=(t=Be.meta)!==null&&t!==void 0?t:{},Be.meta[i]=e)};class Ie{constructor(e){this.name=e}next(e){var t,r;if(!la)return;Be.series=(t=Be.series)!==null&&t!==void 0?t:{};const s=(r=Be.series[this.name])!==null&&r!==void 0?r:[];s.push([Date.now(),e]),Be.series[this.name]=s}}const xS=new Ie("best_bitrate"),BS=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class MS{constructor(){this.history={}}recordSelection(e){this.history[e.id]=a.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const di=(i,{container:e,throughput:t,tuning:r,limits:s,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:d,history:u})=>{var c,h,f,p;const v=r.usePixelRatio&&(c=window.devicePixelRatio)!==null&&c!==void 0?c:1,m=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*v*r.containerSizeFactor,height:e.height*v*r.containerSizeFactor},S=m&&pt(m),b=r.considerPlaybackRate&&a.isNonNullable(l)?l:1,g=i.filter(N=>!Wi(N.quality)).sort((N,_)=>Ui(N.quality,_.quality)?-1:1),P=(h=xe(g,-1))===null||h===void 0?void 0:h.quality,E=(f=xe(g,0))===null||f===void 0?void 0:f.quality,T=a.isNullable(s)||a.isNonNullable(s.min)&&a.isNonNullable(s.max)&&Zt(s.max,s.min)||a.isNonNullable(s.min)&&E&&Ui(s.min,E)||a.isNonNullable(s.max)&&P&&Zt(s.max,P),w=b*BS(o!=null?o:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),O=g.filter(N=>{const _=S?Zt(N.quality,S):!0,G=a.isNonNullable(t)&&isFinite(t)&&a.isNonNullable(N.bitrate)?t-n>=N.bitrate*w:!0,K=r.lazyQualitySwitch&&a.isNonNullable(r.minBufferToSwitchUp)&&d&&!Wi(d.quality)&&(o!=null?o:0)<r.minBufferToSwitchUp&&Ui(N.quality,d.quality),te=T||(a.isNullable(s.max)||sS(N.quality,s.max))&&(a.isNullable(s.min)||rS(N.quality,s.min));return _&&G&&!K&&te})[0];O&&O.bitrate&&xS.next(O.bitrate);const I=(p=O!=null?O:g[Math.ceil((g.length-1)/2)])!==null&&p!==void 0?p:i[0],U=I&&u&&u.history[I.id]&&a.now()-u.history[I.id]<=r.trackCooldown&&(!u.last||I.id!==u.last.id);if(I!=null&&I.id&&u&&!U&&u.recordSelection(I),U&&(u!=null&&u.last)){const N=u.last;return u==null||u.recordSwitch(N),N}return u==null||u.recordSwitch(I),I};var de=i=>new URL(i).hostname;const VS=300,Ji=(i,e=VS)=>new a.Observable(t=>{const{width:r,height:s}=i.getBoundingClientRect();if(t.next({width:r,height:s}),!window.ResizeObserver)return;const n=new ResizeObserver(cu(o=>{const l=o[0];if(!l)return;let d,u;l.contentBoxSize&&l.contentBoxSize[0]?(u=l.contentBoxSize[0].blockSize,d=l.contentBoxSize[0].inlineSize):l.contentRect&&(d=l.contentRect.width,u=l.contentRect.height),a.isNonNullable(d)&&a.isNonNullable(u)&&t.next({width:d,height:u})},e));return n.observe(i),()=>n.disconnect()}),FS=5e3,Wt={};var x;(function(i){i.DOWNLOADING_LIB="downloading_lib",i.STOPPED="stopped",i.STREAM_INITIALIZED="stream_initialized",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(x||(x={}));const re=(i,e)=>new a.Observable(t=>{const r=s=>t.next(s);return i.on(e,r),()=>i.off(e,r)});class US{constructor(e){this.subscription=new a.Subscription,this.videoState=new Q(x.DOWNLOADING_LIB),this.textTracksManager=new Oe,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new a.ValueSubject(void 0),this.maxSeekBackTime$=new a.ValueSubject(1/0),this.availableFrom$=new a.ValueSubject(void 0),this.elementSize$=new a.ValueSubject(void 0),this.liveOffset=new na,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState(),o=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===x.DOWNLOADING_LIB||t===x.STREAM_INITIALIZED))switch((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===C.Requested&&t!==x.STOPPED&&r!==exports.PlaybackState.STOPPED&&(o?this.seek(n.position-this.liveOffset.getTotalPausedTime()):this.seek(n.position)),r){case exports.PlaybackState.STOPPED:{switch(t){case x.STOPPED:break;case x.PLAYING:case x.PAUSED:case x.READY:this.stop();break;default:a.assertNever(t)}break}case exports.PlaybackState.READY:{switch(t){case x.STOPPED:this.prepare();break;case x.PLAYING:case x.PAUSED:case x.READY:break;default:a.assertNever(t)}break}case exports.PlaybackState.PLAYING:{switch(t){case x.PLAYING:break;case x.PAUSED:o&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case x.READY:this.play();break;case x.STOPPED:this.prepare();break;default:a.assertNever(t)}break}case exports.PlaybackState.PAUSED:{switch(t){case x.PLAYING:this.pause(),this.liveOffset.pause();break;case x.PAUSED:break;case x.READY:this.videoState.setState(x.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case x.STOPPED:this.prepare();break;default:a.assertNever(t)}break}default:a.assertNever(r)}},this.video=Ge(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioTracksExist$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=s=>{var n;e||this.params.output.error$.next({id:s==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:a.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${(n=s==null?void 0:s.toString)===null||n===void 0?void 0:n.call(s)}`,thrown:s}),e=!0},r=window.setTimeout(()=>t("timeout"),FS);dr(import("dashjs/dist/dash.mediaplayer.min.js").then(s=>{e||(Wt.MediaPlayer=s.MediaPlayer,Wt.Debug=s.Debug,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){a.assertNonNullable(Wt.MediaPlayer,"dashjs not loaded"),a.assertNonNullable(Wt.Debug,"dashjs not loaded"),this.player=Wt.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter(t=>(t.height&&(this.frameRatesByFrameHeight[t.height]=t.frameRate?oa(t.frameRate+""):void 0),!0)),(this.params.format===exports.VideoFormat.DASH_WEBM||this.params.format===exports.VideoFormat.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=mS(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&&gS(this.player),vS(this.player),this.params.tuning.requestQuick&&bS(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(x.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,r=m=>{e.error$.next({id:"DashIFProvider",category:a.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:m})},s=(m,S)=>this.subscription.add(m.subscribe(S,r));s(Ji(this.video),this.elementSize$),s(re(this.player,"error").pipe(a.map(m=>{const S=typeof m.error=="object"?m.error.code:m.error,b=typeof m.error=="object"?m.error.message:void 0;return{id:`DashJS#${S}`,message:b}})),e.error$),s(re(this.player,"playbackError").pipe(a.map(m=>({id:"DashJSPlayback",message:m.error}))),e.error$);const n=re(this.player,"qualityChangeRendered").pipe(a.filter(({mediaType:m})=>m==="video"),a.map(({newQuality:m})=>{var S;return(S=this.videoTracks.find(({bitrateInfo:b})=>b.qualityIndex===m))===null||S===void 0?void 0:S.track}));n.pipe(a.filter(a.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(a.filter(({to:m})=>m===x.STREAM_INITIALIZED),a.once()).subscribe(()=>{this.subscription.add(Ne(t.videoTrack,()=>{var m,S;const b=this.player.getQualityFor("video");return(S=(m=this.videoTracks.find(({bitrateInfo:g})=>g.qualityIndex===b))===null||m===void 0?void 0:m.track)===null||S===void 0?void 0:S.id},m=>{var S;if(a.isNullable(m))return;const b=(S=this.videoTracks.find(({track:g})=>g.id===m))===null||S===void 0?void 0:S.bitrateInfo;b&&this.player.setQualityFor("video",b.qualityIndex)},{changed$:n.pipe(a.map(m=>m==null?void 0:m.id)),onError:r}))},r)),this.subscription.add(Ne(t.autoVideoTrackSwitching,()=>{var m,S,b;return(b=(S=(m=this.player.getSettings().streaming)===null||m===void 0?void 0:m.abr)===null||S===void 0?void 0:S.autoSwitchBitrate)===null||b===void 0?void 0:b.video},m=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:m}}}}),{onError:r})),s(re(this.player,"bufferStateChanged").pipe(a.filter(({mediaType:m})=>m==="video"),a.map(({state:m})=>m==="bufferStalled")),e.isBuffering$),s(re(this.player,"fragmentLoadingStarted"),({mediaType:m,request:{url:S}})=>{var b,g;const P=this.player.getDashMetrics(),E=P.getLatestFragmentRequestHeaderValueByID(m,"X-Reused"),T=(b=P.getLatestFragmentRequestHeaderValueByID(m,"X-Delivery-Type"))!==null&&b!==void 0?b:exports.HttpConnectionType.HTTP1,w=(g={1:!0,0:!1}[E])!==null&&g!==void 0?g:void 0;this.params.output.httpConnectionType$.next(T),this.params.output.httpConnectionReused$.next(w),e.hostname$.next(de(S))}),s(re(this.player,"streamInitialized"),({streamInfo:{duration:m,manifestInfo:{isDynamic:S,availableFrom:b}}})=>{this.isLive$.next(S),this.availableFrom$.next(b.getTime()),S||e.duration$.next(m),this.videoTracks=[];const g=this.player.getQualityFor("video");let P;for(const E of this.player.getBitrateInfoListFor("video")){const T=E.qualityIndex.toString(10),w=pt(E),F=E.bitrate/1e3,O={width:E.width,height:E.height},I=this.frameRatesByFrameHeight[E.height];if(w){const U={id:T,quality:w,bitrate:F,size:O,fps:I};this.videoTracks.push({track:U,bitrateInfo:E}),E.qualityIndex===g&&(P=U)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:E})=>E)),P&&e.currentVideoTrack$.next(P),this.videoState.setState(x.STREAM_INITIALIZED),this.videoState.startTransitionTo(x.READY)}),s(re(this.player,"fragmentLoadingCompleted"),({request:m})=>{if(!m.requestEndDate||!m.firstByteDate||!m.bytesLoaded)return;const S=m.requestEndDate.getTime()-m.firstByteDate.getTime(),b=m.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(b,S)}),s(a.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const m=this.params.dependencies.throughputEstimator.throughput$.getValue(),S=di(this.videoTracks.map(({track:g})=>g),{container:this.elementSize$.getValue(),throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),b=this.videoTracks.find(({track:g})=>g===S);b!=null&&b.bitrateInfo&&this.player.setQualityFor("video",b==null?void 0:b.bitrateInfo.qualityIndex,!1)}),s(a.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(a.filter(a.isNonNullable))}).pipe(a.filter(({isLive:m})=>m),a.map(({maxSeekBackTime:m})=>-m/1e3)),this.params.output.duration$);const o=re(this.player,"playbackTimeUpdated").pipe(a.map(({time:m})=>m!=null?m:0));s(a.combine({availableFrom:this.availableFrom$.pipe(a.filter(a.isNonNullable)),currentTime:o}),({availableFrom:m,currentTime:S})=>this.params.output.liveTime$.next(m+S*1e3)),s(o.pipe(a.filter(()=>this.isLive$.getValue()===!1)),e.position$),s(re(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),s(re(this.player,"playbackEnded"),e.endedEvent$),s(re(this.player,"playbackProgress").pipe(a.map(()=>wl(this.video.buffered,this.video.currentTime))),e.currentBuffer$),s(re(this.player,"playbackPlaying"),()=>{this.videoState.setState(x.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)}),s(re(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(x.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),s(re(this.player,"playbackPaused"),()=>{this.videoState.setState(x.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)}),s(re(this.player,"canPlay"),()=>{var m;((m=this.videoState.getTransition())===null||m===void 0?void 0:m.to)===x.READY&&this.videoState.setState(x.READY)}),s(this.isLive$,e.isLive$),s(Ji(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const l=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));s(l,this.syncPlayback);const{playbackDuration$:d,ping$:u,connectionType$:c,connectionReused$:h}=SS(this.player);s(c,this.params.output.httpConnectionType$),s(h,this.params.output.httpConnectionReused$),s(d,this.maxSeekBackTime$),s(u.pipe(a.once()),e.firstBytesEvent$),s(re(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&s(a.combine({isLive:this.isLive$,isShort:e.duration$.pipe(a.map(m=>m<60))}),({isLive:m,isShort:S})=>{const b=!m&&S;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:b}}})}),s(o.pipe(a.filter(m=>m>this.params.tuning.insufficientBufferRuleMargin),a.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(re(this.player,"manifestLoaded").pipe(a.once()).subscribe(()=>{this.subscription.add(re(this.player,"playbackPlaying").pipe(a.once(),a.mapTo(void 0)).subscribe(e.firstFrameEvent$,r))},r)),this.subscription.add(mt(this.video,t.isLooped,r));const{volumeState$:f,looped$:p,playbackRateState$:v}=Ye(this.video);this.subscription.add(He(this.video,t.volume,f,r)),this.subscription.add(f.subscribe(e.volume$,r)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(Ze(this.video,t.playbackRate,v,r))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(x.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(x.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3);const s=_t(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,wt.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(x.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(x.PAUSED),this.video.pause()}destroy(){var e,t;this.subscription.unsubscribe(),this.textTracksManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(r){}this.video.remove(),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var ci=i=>{switch(i){case"mobile":return exports.VideoQuality.Q_144P;case"lowest":return exports.VideoQuality.Q_240P;case"low":return exports.VideoQuality.Q_360P;case"sd":case"medium":return exports.VideoQuality.Q_480P;case"hd":case"high":return exports.VideoQuality.Q_720P;case"fullhd":case"full":return exports.VideoQuality.Q_1080P;case"quadhd":case"quad":return exports.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return exports.VideoQuality.Q_2160P}},et=i=>J(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(t instanceof DOMException&&(t.code===20||t.name==="AbortError"))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(r){return i.muted=!1,console.warn(r),!1}}return!0});function oe(){return a.now()}function _l(i){return oe()-i}function Bn(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,s=o=>r.test(o);return{resolve:(o,l,d=!1)=>{s(o)||(o.startsWith("/")||(o="/"+o),o=t+o);let u=o.indexOf("?")>-1?"&":"?";return d&&(o+=u+"lowLat=1",u="&"),l&&(o+=u+"_rnd="+Math.floor(999999999*Math.random())),o}}}function jS(i,e,t){const r=(...s)=>{t.apply(null,s),i.removeEventListener(e,r)};i.addEventListener(e,r)}function ji(i,e,t,r){const s=window.XMLHttpRequest;let n,o,l,d=!1,u=0,c,h,f=!1,p="arraybuffer",v=7e3,m=2e3,S=()=>{if(d)return;a.assertNonNullable(c);const _=_l(c);let G;if(_<m){G=m-_,setTimeout(S,G);return}m*=2,m>v&&(m=v),o&&o.abort(),o=new s,w()};const b=_=>(n=_,N),g=_=>(h=_,N),P=()=>(p="json",N),E=()=>{if(!d){if(--u>=0){S(),r&&r();return}d=!0,h&&h(),t&&t()}},T=_=>(f=_,N),w=()=>{c=oe(),o=new s,o.open("get",i);let _=0,G,K=0;const te=()=>(a.assertNonNullable(c),Math.max(c,Math.max(G||0,K||0)));if(n&&o.addEventListener("progress",$=>{const D=oe();n.updateChunk&&$.loaded>_&&(n.updateChunk(te(),$.loaded-_),_=$.loaded,G=D)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>E())),o.addEventListener("load",()=>{if(d)return;a.assertNonNullable(o);const $=o.status;if($>=200&&$<300){if(o.response.byteLength&&n){const D=o.response.byteLength-_;D&&n.updateChunk&&n.updateChunk(te(),D)}h&&h(),o&&e(o.response)}else E()}),o.addEventListener("error",()=>{E()}),f){const $=()=>{a.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(K=oe(),o.removeEventListener("readystatechange",$))};o.addEventListener("readystatechange",$)}return o.responseType=p,o.send(),N},N={withBitrateReporting:b,withParallel:T,withJSONResponse:P,withRetryCount:_=>(u=_,N),withRetryInterval:(_,G)=>(a.isNonNullable(_)&&(m=_),a.isNonNullable(G)&&(v=G),N),withTimeout:_=>(l=_,N),withFinally:g,send:w,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return N}const HS=100,GS=2e3,YS=500;let qS=class{constructor(e){this.intervals=[],this.currentRate=0,this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-YS;if(t-e>GS){let r=0,s=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)r+=n.end-n.start,s+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,l=n.end-n.start;r+=o;const d=n.bytes*o/l;s+=d,n.start=t,n.bytes-=d}}}if(s>0&&r>0){const n=s*8/(r/1e3);return this._updateRate(n),this.logger(`rate updated, new=${Math.round(n/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(s)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>HS&&(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 zS{constructor(e,t,r,s,n){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=s,this.logger=n}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const r=oe(),s=d=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=d,e._errorCB?e._errorCB(d):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=d=>{e._complete=1,e._responseData=d,e._downloadTime=oe()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(d,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},o=()=>{e._finallyCB&&e._finallyCB()},l=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=ji(t,n,()=>s("error"),l),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(o),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=oe()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=oe();if(Object.keys(this.activeRequests).length>=e)return!1;const r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,s){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=r,o._retryCB=s,o._finallyCB=n._finallyCB,o._error||o._complete?(this._removeFromActive(e),setTimeout(()=>{o._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(o._responseData,o._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(o._errorMsg)),n._finallyCB&&n._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const l=this.pendingQueue.indexOf(e);l!==-1&&this.pendingQueue.splice(l,1),this.logger(`Request not prefetched, starting new request, url=${e}${l===-1?"":"; removed pending"}`),this._sendRequest(n,e)}},n._cb=t,n._errorCB=r,n._retryCB=s,n.abort=function(){n.request&&n.request.abort()},n.withFinally=o=>(n._finallyCB=o,n),n}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Ii=1e4,Ni=3,WS=300,QS=2e3,JS=6e4,KS=10,XS=1,ZS=500;class eb{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 qS(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Bn(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Bn(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r;Boolean(e.error)&&!this.destroyed&&(t(`Video element error: ${(r=e.error)===null||r===void 0?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,r=t.buffered.length;let s;r!==0&&(s=t.buffered.start(r-1),t.currentTime<s&&(e("Fixup stall"),t.currentTime=s))}_selectQuality(e){const{videoElement:t}=this.params;let r,s,n;const o=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let l=0;l<this.manifest.length;++l)n=this.manifest[l],!(this.maxAutoQuality&&n.video.height>this.maxAutoQuality)&&(n.bitrate<e&&o>Math.min(n.video.height,n.video.width)?(!s||n.bitrate>s.bitrate)&&(s=n):(!r||r.bitrate>n.bitrate)&&(r=n));return s||r}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||a.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:r,videoElement:s,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,s.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{jS(s,"progress",()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),n({name:"playing"})):o()})};o()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new zS(Ni,Ii,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:r,playerCallback:s}=this.params;let n=!1,o=null,l=null,d=null,u=null,c=!1;const h=()=>{const E=n&&(!c||c===this.rep);return E||t("Not running!"),E},f=(E,T,w)=>{d&&d.abort(),d=ji(this.urlResolver.resolve(E,!1),T,w,()=>this._retryCallback()).withTimeout(Ii).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ni).withFinally(()=>{d=null}).send()},p=(E,T,w)=>{a.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),T,w,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},v=E=>{const T=r.playbackRate;r.playbackRate!==E&&(t(`Playback rate switch: ${T}=>${E}`),r.playbackRate=E)},m=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)v(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){v(1);return}const w=oe()-1e4;let F=0;for(let I=0;I<this.bufferStates.length;I++){const U=this.bufferStates[I];E=Math.min(E,U.buf),U.ts<w&&F++}this.bufferStates.splice(0,F),t(`update playback rate; minBuffer=${E} drop=${F} jitter=${this.sourceJitter}`);let O=E-XS;this.sourceJitter>=0?O-=this.sourceJitter/2:this.sourceJitter-=1,O>3?v(1.15):O>1?v(1.1):O>.3?v(1.05):v(1)}},b=E=>{let T;const w=()=>T&&T.start?T.start.length:0,F=$=>T.start[$]/1e3,O=$=>T.dur[$]/1e3,I=$=>T.fragIndex+$,U=($,D)=>({chunkIdx:I($),startTS:F($),dur:O($),discontinuity:D}),N=()=>{let $=0;if(T&&T.dur){let D=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,z=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ee=D;this.sourceJitter>1&&(ee+=this.sourceJitter-1);let ie=T.dur.length-1;for(;ie>=0&&(ee-=T.dur[ie],!(ee<=0));--ie);$=Math.min(ie,T.dur.length-1-z),$=Math.max($,0)}return U($,!0)},_=$=>{const D=w();if(!(D<=0)){if(a.isNonNullable($)){for(let z=0;z<D;z++)if(F(z)>$)return U(z)}return N()}},G=$=>{const D=w(),z=$?$.chunkIdx+1:0,ee=z-T.fragIndex;if(!(D<=0)){if(!$||ee<0||ee-D>KS)return t(`Resync: offset=${ee} bChunks=${D} chunk=`+JSON.stringify($)),N();if(!(ee>=D))return U(z-T.fragIndex,!1)}},K=($,D,z)=>{u&&u.abort(),u=ji(this.urlResolver.resolve($,!0,this.lowLatency),D,z,()=>this._retryCallback()).withTimeout(Ii).withRetryCount(Ni).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:($,D)=>{K(E,z=>{if(!h())return;T=z;const ee=Boolean(T.lowLatency);ee!==this.lowLatency&&m(ee);let ie=0;for(let ce=0;ce<T.dur.length;++ce)ie+=T.dur[ce];ie>0&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ie/T.dur.length)),s({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,$(_(D))},()=>this._handleNetworkError())},nextChunk:G}},g=()=>{n=!1,l&&l.abort(),d&&d.abort(),u&&u.abort(),a.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:E=>{const{videoElement:T,logger:w}=this.params;let F=b(e.jidxUrl),O,I,U,N,_=0,G,K,te;const $=()=>{G&&(clearTimeout(G),G=void 0);const j=Math.max(ZS,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ae=_+j,ue=oe(),me=Math.min(1e4,ae-ue);_=ue;const tt=()=>{u||h()&&F.seek(()=>{h()&&(_=oe(),D(),$())})};me>0?G=window.setTimeout(()=>{this.paused?$():tt()},me):tt()},D=()=>{let j;for(;j=F.nextChunk(N);)N=j,Pe(j);const ae=F.nextChunk(U);if(ae){if(U&&ae.discontinuity){w("Detected discontinuity; restarting playback"),this.paused?$():(g(),this._initPlayerWith(e));return}ce(ae)}else $()},z=(j,ae)=>{if(!h()||!this.sourceBuffer)return;let ue,me,tt;const Ae=qe=>{window.setTimeout(()=>{h()&&z(j,ae)},qe)};if(this.sourceBuffer.updating)w("Source buffer is updating; delaying appendBuffer"),Ae(100);else{const qe=oe(),it=T.currentTime;!this.paused&&T.buffered.length>1&&K===it&&qe-te>500&&(w("Stall suspected; trying to fix"),this._fixupStall()),K!==it&&(K=it,te=qe);const xt=this._getBufferSizeSec();if(xt>30)w(`Buffered ${xt} seconds; delaying appendBuffer`),Ae(2e3);else try{this.sourceBuffer.appendBuffer(j),this.videoPlayStarted?(this.bufferStates.push({ts:qe,buf:xt}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ae&&ae()}catch(vt){if(vt.name==="QuotaExceededError")w("QuotaExceededError; delaying appendBuffer"),tt=this.sourceBuffer.buffered.length,tt!==0&&(ue=this.sourceBuffer.buffered.start(0),me=it,me-ue>4&&this.sourceBuffer.remove(ue,me-3)),Ae(1e3);else throw vt}}},ee=()=>{I&&O&&(w([`Appending chunk, sz=${I.byteLength}:`,JSON.stringify(U)]),z(I,function(){I=null,D()}))},ie=j=>e.fragUrlTemplate.replace("%%id%%",j.chunkIdx),ce=j=>{h()&&p(ie(j),(ae,ue)=>{if(h()){if(ue/=1e3,I=ae,U=j,o=j.startTS,ue){const me=Math.min(10,j.dur/ue);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*me:me}ee()}},()=>this._handleNetworkError())},Pe=j=>{h()&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ie(j),!1)))},Lt=j=>{h()&&(e.cachedHeader=j,z(j,()=>{O=!0,ee()}))};n=!0,F.seek(j=>{if(h()){if(_=oe(),!j){$();return}N=j,!a.isNullable(E)||j.startTS>E?ce(j):(U=j,D())}},E),e.cachedHeader?Lt(e.cachedHeader):f(e.headerUrl,Lt,()=>this._handleNetworkError())},stop:g,getTimestampSec:()=>o},c}_switchToQuality(e){const{logger:t,playerCallback:r}=this.params;let s;e.bitrate!==this.bitrate&&(this.rep&&(s=this.rep.getTimestampSec(),a.isNonNullable(s)&&(s+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,a.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(s),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return a.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,r=h=>{if(!this.autoQuality)return;let f,p,v;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(p=this._getBufferSizeSec(),v=h/this.bitrate,p>10&&v>.8||p>15&&v>.5||p>20&&v>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}f=this._selectQuality(h),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${h}`)},n=(()=>({updateChunk:(f,p)=>{const v=oe();if(this.chunkRateEstimator.addInterval(f,v,p)){const S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:v-f,speed:S}),!0}},get:()=>{const f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}}))();let o=-1/0,l,d=!0;const u=()=>{let h=n.get();if(h&&l&&this.autoQuality){if(d&&h>l&&_l(o)<3e4)return;r(h)}d=this.autoQuality};return{updateChunk:(h,f)=>{const p=n.updateChunk(h,f);return p&&u(),p},notifySwitch:h=>{const f=oe();h<l&&(o=f),l=h}}}_fetchManifest(e,t,r){this.manifestRequest=ji(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Ii).withRetryCount(Ni).withRetryInterval(WS,QS).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;et(t).then(r=>{r||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:r,videoElement:s}=this.params,n=o=>{const l=[];return o!=null&&o.length?(o.forEach((d,u)=>{d.video&&s.canPlayType(d.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(d.codecs)&&(d.index=u,l.push(d))}),l.sort(function(d,u){return d.video&&u.video?u.video.height-d.video.height:u.bitrate-d.bitrate}),l):(this.params.playerCallback({name:"error",type:"partial_metadata"}),[])};this.manifest=n(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},JS))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var B;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(B||(B={}));const tb=[B.PAUSED,B.PLAYING,B.READY],ib=[B.PAUSED,B.PLAYING,B.READY];class rb{constructor(e){this.subscription=new a.Subscription,this.videoState=new Q(B.STOPPED),this.representations$=new a.ValueSubject([]),this.textTracksManager=new Oe,this.maxSeekBackTime$=new a.ValueSubject(1/0),this.zeroTime$=new a.ValueSubject(void 0),this.liveOffset=new na,this._dashCb=s=>{var n,o,l,d;switch(s.name){case"buffering":{const u=s.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${s.type}`,category:a.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=s.manifest,c=[];for(const h of u){const f=(n=h.name)!==null&&n!==void 0?n:h.index.toString(10),p=(o=ci(h.name))!==null&&o!==void 0?o:pt(h.video),v=h.bitrate/1e3,m=Object.assign({},h.video);if(!p)continue;const S={id:f,quality:p,bitrate:v,size:m};c.push({track:S,representation:h})}this.representations$.next(c),this.params.output.availableVideoTracks$.next(c.map(({track:h})=>h)),((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===B.MANIFEST_READY&&this.videoState.setState(B.MANIFEST_READY);break}case"qualitySwitch":{const u=s.quality,c=(d=this.representations$.getValue().find(({representation:h})=>h===u))===null||d===void 0?void 0:d.track;this.params.output.hostname$.next(new URL(u.headerUrl,this.params.source.url).hostname),a.isNonNullable(c)&&this.params.output.currentVideoTrack$.next(c);break}case"bandwidth":{const{size:u,duration:c}=s;this.params.dependencies.throughputEstimator.addRawSpeed(u,c);break}case"index":{this.maxSeekBackTime$.next(s.shiftDuration),this.zeroTime$.next(s.zeroTime);break}}},this.syncPlayback=()=>{var s;const n=this.videoState.getState(),o=this.videoState.getTransition(),l=this.params.desiredState.playbackState.getState(),d=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${n}; videoTransition: ${JSON.stringify(o)}; desiredPlaybackState: ${l}; seekState: ${JSON.stringify(u)};`}),l===exports.PlaybackState.STOPPED){n!==B.STOPPED&&(this.videoState.startTransitionTo(B.STOPPED),this.dash.destroy(),this.video.setAttribute("src",""),this.video.load(),this.videoState.setState(B.STOPPED));return}if(!o){if(ib.includes(n)){const c=(s=this.params.desiredState.videoTrack.getTransition())===null||s===void 0?void 0:s.to;a.isNonNullable(c)&&this.setVideoTrack(c);const h=this.params.desiredState.autoVideoTrackSwitching.getTransition();h&&this.setAutoQuality(h.to)}if((d==null?void 0:d.to)!==exports.PlaybackState.PAUSED&&u.state===C.Requested&&tb.includes(n)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(n){case B.STOPPED:this.videoState.startTransitionTo(B.MANIFEST_READY),this.dash.attachSource(_t(this.params.source.url));return;case B.MANIFEST_READY:this.videoState.startTransitionTo(B.READY),this.prepare();break;case B.READY:if(l===exports.PlaybackState.PAUSED)this.videoState.setState(B.PAUSED);else if(l===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(B.PLAYING);const c=d==null?void 0:d.from;c&&c===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(B.PAUSED)})}return;case B.PLAYING:l===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(B.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case B.PAUSED:l===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(B.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(B.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return a.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=s=>{e.output.error$.next({id:"DashLiveProvider",category:a.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:s})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(s)}`})}),this.video=Ge(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioTracksExist$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const r=Ye(this.video);this.subscription.add(r.canplay$.subscribe(()=>{var s;((s=this.videoState.getTransition())===null||s===void 0?void 0:s.to)===B.READY&&this.videoState.setState(B.READY)},t)).add(r.pause$.subscribe(()=>{this.videoState.setState(B.PAUSED)},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===C.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(B.PLAYING)},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(s=>-s/1e3)).subscribe(this.params.output.duration$)).add(a.combine({zeroTime:this.zeroTime$.pipe(a.filter(a.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:s,position:n})=>this.params.output.liveTime$.next(s+n*1e3),t)).add(mt(this.video,this.params.desiredState.isLooped,t)).add(He(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ze(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:s}})=>{const n=s&&oS(s);this.dash.setMaxAutoQuality(n)})).add(this.videoState.stateChangeEnded$.subscribe(s=>{var n;switch(s.to){case B.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case B.MANIFEST_READY:case B.READY:((n=this.params.desiredState.playbackState.getTransition())===null||n===void 0?void 0:n.to)===exports.PlaybackState.READY&&this.params.desiredState.playbackState.setState(exports.PlaybackState.READY);break;case B.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case B.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(s.to)}},t)).add(a.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const e=new eb({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,r,s,n,o;const l=this.representations$.getValue(),d=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),u=(s=(r=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||r===void 0?void 0:r.to)!==null&&s!==void 0?s:this.params.desiredState.autoVideoTrackSwitching.getState(),c=!u&&a.isNonNullable(d)?d:(n=di(l.map(({track:f})=>f),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState()}))===null||n===void 0?void 0:n.id,h=(o=l.find(({track:f})=>f.id===c))===null||o===void 0?void 0:o.representation;a.assertNonNullable(h,"Representations missing"),this.dash.startPlay(h,u),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(c),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(u)}setVideoTrack(e){var t;const r=(t=this.representations$.getValue().find(({track:s})=>s.id===e))===null||t===void 0?void 0:t.representation;a.assertNonNullable(r,`No such representation ${e}`),this.dash.switchByName(r.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=-e,r=t<=this.maxSeekBackTime$.getValue()?t:0;this.params.output.position$.next(e/1e3),this.liveOffset.resetTo(r),this.dash.reinit(_t(this.params.source.url,r))}}var Rl=i=>{var e,t;const r=i.get("X-Delivery-Type"),s=i.get("X-Reused"),n=r===null?exports.HttpConnectionType.HTTP1:(e=r)!==null&&e!==void 0?e:void 0,o=s===null?void 0:(t={1:!0,0:!1}[s])!==null&&t!==void 0?t:void 0;return{type:n,reused:o}},ot=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){const s=i.start(r)*1e3,n=i.end(r)*1e3;s<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const sb=i=>{const e=document.createElement("a");return e.href=i,e.origin},ab=i=>{const e=document.createElement("a");return e.href=i,e.host};class Il{constructor(e,t=[],r,s,n,o){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=r,this._progressCb=s,this._headersCb=n,this._errorCb=o,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{var t,r,s,n,o,l,d,u;if(a.assertNonNullable(this._xhr),((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(r=this._errorCb)===null||r===void 0||r.call(this,`Http${(s=this._xhr)===null||s===void 0?void 0:s.status}`,`XHR response code ${(n=this._xhr)===null||n===void 0?void 0:n.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const c=oi(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(h=>h.split(":").map(f=>f.trim())));(o=this._headersCb)===null||o===void 0||o.call(this,new Headers(c))}else this._xhr.readyState===4?(l=this._completeCb)===null||l===void 0||l.call(this,this._xhr.response):this._xhr.readyState===3&&((d=this._progressCb)===null||d===void 0||d.call(this,this._xhr.response))}catch(c){throw(u=this._errorCb)===null||u===void 0||u.call(this,"XHR2CallbackError",`xhr2 callback threw ${String(c)}`,c),c}},this._xhr.onerror=()=>{var t;(t=this._xhr)===null||t===void 0||t.abort(),this._retryTimeout=window.setTimeout(()=>{var r;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(r=this._errorCb)===null||r===void 0||r.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let s;this._failoverIndex>=this._failoverHosts.length?(s=this._url,this._failoverIndex=0):(s=this._url.replace(ab(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",s,!0),this._xhr.send(null)}},500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class Ki{constructor(e){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t==null||t()}catch(r){if(r.name==="QuotaExceededError"){this._isFull=!0;const s=this._sourceBuffer.buffered;let n=0;for(let o=0,l=s.length;o<l;o++)n+=s.end(o)-s.start(o);n&&(this._maxBufferDuration=Math.round(n))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",r),r}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,r,s,n,o,l){this.abort(()=>{let d=0;const u=Date.now();let c=0,h=0,f=0;const p=m=>{s(Ki._str2ua(m.substr(d))),d=m.length};let v=e.baseURL+"&bytes="+t+"-"+r;this._params.requestQuic&&(v=It(v)),this._lastXhr=new Il(v,e.failoverHosts,m=>{this._lastXhr=void 0,p(m);const S=Date.now()-u;this._params.onBandwidthChange({size:m.length,duration:S,speed:8*m.length/(S/1e3)}),this._onDashCallback("loading",{size:m.length,done:!0}),n==null||n()},m=>{if(m.length-d>l&&p(m),h===0){h=Date.now();return}f=m.length-c;const S=Date.now()-h;f>=100*1024&&S>=1e3&&(this._params.onBandwidthChange({size:f,duration:S,speed:8*f/(S/1e3)}),f=0,c=m.length,h=Date.now()),this._onDashCallback("loading",{size:m.length,done:!1})},o,(m,S,b)=>this._params.onError(m,S,b))})}abort(e){var t;(t=this._lastXhr)===null||t===void 0||t.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e==null||e()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(r){throw this._params.onError("SourceBuffer","Source Buffer update error",r),r}};return this._sourceBuffer.addEventListener("updateend",t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener("updateend",e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=Ki._concatUint8(this._appendPromiseUint8Array,e):(this._appendPromiseUint8Array=e,this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,()=>{this._appendPromiseUint8Array=void 0,t&&this._sbUpdatingWatch(t)})}))}endOfStream(){this._mediaSource.readyState==="open"&&this._sbUpdatingWatch(()=>this._mediaSource.endOfStream())}static _concatUint8(e,t){const r=new Uint8Array(e.byteLength+t.byteLength);return r.set(e,0),r.set(t,e.byteLength),r}static _str2ua(e){const t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}remove(e,t){this._sbUpdatingWatch(()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(e,t),this._maxBufferDuration=Number.POSITIVE_INFINITY})}destroy(){var e;(e=this._lastXhr)===null||e===void 0||e.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._mediaSource.readyState==="open"&&this._sourceBuffer.abort()}}class nb{constructor(e){var t;this._representations=[],this._appendVector={},this._cachingPaused=!1,this._duration=0,this.STREAM_END_THRESHOLD=1,this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=(t=e.onDashCallback)!==null&&t!==void 0?t:()=>{},this._config=e.config}_parseDurationFromISO8601(e){const t=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/,r=(l,d)=>{const u=l?parseFloat(l.replace(",",".")):NaN;return(isNaN(u)?0:u)*d},s=t.exec(e),n=(s==null?void 0:s[1])==="-"?-1:1,o={years:r(s==null?void 0:s[2],n),months:r(s==null?void 0:s[3],n),weeks:r(s==null?void 0:s[4],n),days:r(s==null?void 0:s[5],n),hours:r(s==null?void 0:s[6],n),minutes:r(s==null?void 0:s[7],n),seconds:r(s==null?void 0:s[8],n)};return o.hours*3600+o.minutes*60+o.seconds}getRepresentations(){return this._representations}attachSource(e,t){let r=e;this._config.REQUEST_QUIC&&(r=It(r)),new Il(r,t,s=>{this.attachManifest(s,t,sb(r))},void 0,s=>{this._params.onResponseHeaders(s)},(s,n,o)=>this._params.onError(s,n,o))}attachManifest(e,t,r){const n=new DOMParser().parseFromString(e,"text/xml").documentElement,o=(u,c)=>{const h=u.attributes.getNamedItem(c);return h?h.value:null};this._duration=this._parseDurationFromISO8601(String(o(n,"mediaPresentationDuration")));const l=[],d=[];if(Array.prototype.forEach.call(n.getElementsByTagName("Representation"),u=>{var c,h,f,p,v,m,S,b,g,P,E,T,w,F,O,I,U,N,_;const G=u.getElementsByTagName("SegmentBase")[0],K=G&&o(G,"indexRange").split("-"),te=G&&G.getElementsByTagName("Initialization")[0],$=te&&o(te,"range").split("-");if(!$||!K){const Pe=u.parentElement;if((Pe==null?void 0:Pe.getAttribute("contentType"))==="text"){const Lt=(c=u.getAttribute("id"))!==null&&c!==void 0?c:void 0,j=(r?r+"/":"")+((v=(p=(f=(h=u.getElementsByTagName("BaseURL"))===null||h===void 0?void 0:h[0])===null||f===void 0?void 0:f.childNodes)===null||p===void 0?void 0:p[0])===null||v===void 0?void 0:v.data),ae=(m=Pe.getAttribute("lang"))!==null&&m!==void 0?m:void 0;j&&d.push({id:Lt,url:j,language:ae})}return}const D=.1,z=Number((S=u.attributes.getNamedItem("bandwidth"))===null||S===void 0?void 0:S.value),ee=(r?r+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ie;const ce=(g=(b=u.attributes.getNamedItem("frameRate"))===null||b===void 0?void 0:b.value)!==null&&g!==void 0?g:void 0;ie=ce?oa(ce):void 0,l.push({width:Number((P=u.attributes.getNamedItem("width"))===null||P===void 0?void 0:P.value),height:Number((E=u.attributes.getNamedItem("height"))===null||E===void 0?void 0:E.value),bandwidth:z,baseURL:ee,failoverHosts:t,indexFrom:Number(K[0]),indexTo:Number(K[1]),initFrom:Number($[0]),initTo:Number($[1]),codecs:(w=(T=u.attributes.getNamedItem("codecs"))===null||T===void 0?void 0:T.value)!==null&&w!==void 0?w:void 0,mimeType:(O=(F=u.attributes.getNamedItem("mimeType"))===null||F===void 0?void 0:F.value)!==null&&O!==void 0?O:void 0,fps:ie,bufferSize:D*z/8,bufferLength:D,name:(U=(I=u.attributes.getNamedItem("okQuality"))===null||I===void 0?void 0:I.value)!==null&&U!==void 0?U:void 0,id:(_=(N=u.attributes.getNamedItem("id"))===null||N===void 0?void 0:N.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");f.setAttribute("src",h),u&&f.setAttribute("id",u),c&&f.setAttribute("srclang",c),this._video.appendChild(f)}),this._representations.sort((u,c)=>c.bandwidth-u.bandwidth),this._params.onManifestReady(this._representations)}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const r=Date.now();this._stream.load(e,e.initFrom,e.indexTo,s=>{let n=e.initTo-e.initFrom+1;if(!s.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(s.buffer,0,n);const o=new DataView(s.buffer);n+=12;const l=o.getUint32(n+4,!1);n+=8;let d=o.getUint32(n,!1),u=o.getUint32(n+4,!1)+(e.indexTo+1);n+=8;const c=o.getUint16(n+2,!1);n+=4,e.refs=[];for(let f=0;f<c;f+=1){const p=u+(o.getUint32(n,!1)&2147483647),v=d+o.getUint32(n+4,!1);n+=12,e.refs.push({fromTime:d/l,toTime:v/l,fromOffset:u,toOffset:p-1}),u=p,d=v}const h=e.refs[e.refs.length-1];h.toTime-h.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,s=>{this._params.onResponseHeaders(s),this._params.onIdxRequestPing(Date.now()-r)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const r=new t;let s,n;const o=()=>{const u=this._findRef(this._video.currentTime);if(!u||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const p=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),p)}const c=this._appendVector[String(u.fromTime)];c!==s&&(s=c,this._params.onRepresentationPlay(c));let h;if(this._findRef(u.toTime)){const p=this._buffer.getByTime(this._video.currentTime);if(!p){this._onDashCallback("buffering");return}h=p.to-this._video.currentTime,h<e.bufferLength&&(this._onDashCallback("buffering"),n!==p.to&&(n=p.to,window.setTimeout(()=>{try{const v=this._buffer.getNextWithGap(p);v&&(this._video.currentTime=v.from)}catch(v){throw this._params.onError("GapSyncError",`Seek Error ${String(v)}`,v),v}},h*1e3)))}},l=()=>{this._loopTimeout=window.setTimeout(()=>{try{o()}catch(u){throw this._params.onError("LoopError",`Dash Loop exception ${String(u)}`,u),u}l()},250)},d=()=>{if(!this._stream)try{const u=r.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Ki({mediaSource:r,sourceBuffer:u,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(u){throw this._params.onError("DashSourceOpen",`Source open exception ${String(u)}`,u),u}this._loadInitAndSidx(e),r.duration||(r.duration=this._duration),this._loopTimeout||l(),r.removeEventListener("sourceopen",d),r.removeEventListener("webkitsourceopen",d)};r.addEventListener("sourceopen",d,!1),r.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(r),this._video.addEventListener("waiting",()=>{const u=this._video&&this._video.played.length;u&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(u-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,r=!1,s=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const n=this._findRef(t);if(n){if(r){this._isLastRef(n)&&t>=n.toTime&&(t=n.fromTime);const o=this._findRef(this._video.currentTime),l=Math.abs(this._video.currentTime-t),d=s||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||n===o||l<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=d?t:n.fromTime}this._appendVector[String(n.fromTime)]=e,this._stream.load(e,n.fromOffset,n.toOffset,(o,l)=>this._stream.append(o,l),()=>{this._lastLoadOffset=n.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},o=>this._params.onResponseHeaders(o),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const r=this._buffer.getByTime(this._video.currentTime),s=this._findRef(this._video.currentTime);if(!r||!s){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(s.toTime<r.to+n){const o=this._findRef(s.toTime);o&&o.toTime<r.to+n?(this._buffer.smartRemove(s.fromTime-n,o.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(s.fromTime-n,s.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,s.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t){this._stream&&this._buffer.getByTime(e)?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0,t)}updateRefsForCurrentTime(){const e=this._video.currentTime;(!this._stream||a.isNullable(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const r=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!r)return;if(Array.isArray(r)&&r.length===0){this._params.onError("emptyrefs","Empty refs");return}let s;for(let n=0;n<r.length;n++){const o=r[n];if(o.fromTime<=e&&o.toTime>e)return o;o.fromTime>e&&(!s||o.fromTime<s.fromTime)&&(s=o)}if(!s){const n=r[r.length-1];if(e>n.toTime)return n}return s}_isLastRef(e){var t;const r=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!r)return!1;const s=r[r.length-1];return e.fromTime===s.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const r=this._video.buffered.start(t),s=this._video.buffered.end(t);if(e>r&&e<s)return Math.round(s*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var M;(function(i){i.STOPPED="stopped",i.MANIFEST_LOADED="manifest-loaded",i.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",i.METADATA_LOADED="metadata-loaded",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(M||(M={}));const ob=[M.PAUSED,M.PLAYING];class lb{constructor(e){this.videoState=new Q(M.STOPPED),this.subscription=new a.Subscription,this.representations$=new a.ValueSubject([]),this.currentRepresentation$=new a.ValueSubject(void 0),this.textTracksManager=new Oe,this.elementSize$=new a.ValueSubject(void 0),this.dashLiteEvents={idxRequestPing$:new a.Subject,responseHeaders$:new a.Subject,manifestReady$:new a.Subject,representationPlay$:new a.Subject,error$:new a.Subject},this.handleManifestReady=t=>{var r,s,n;const o=[];for(const l of t){const d=(s=(r=l.name)!==null&&r!==void 0?r:l.id)!==null&&s!==void 0?s:l.height.toString(10),u=(n=l.name&&ci(l.name))!==null&&n!==void 0?n:pt(l),c=l.bandwidth/1e3,h={width:l.width,height:l.height},f=l.fps;if(!u)continue;const p={id:d,quality:u,bitrate:c,size:h,fps:f};o.push({track:p,representation:l})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:l})=>l)),this.videoState.setState(M.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var r;const s=(r=this.representations$.getValue().find(({representation:n})=>n===t))===null||r===void 0?void 0:r.track;s&&(this.params.output.currentVideoTrack$.next(s),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(s.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return a.assertNonNullable(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${s}; seekState: ${JSON.stringify(o)};`}),s===exports.PlaybackState.STOPPED){t!==M.STOPPED&&(this.videoState.startTransitionTo(M.STOPPED),this.dash.destroy(),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(M.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!r)switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&o.state===C.Requested&&ob.includes(t)&&this.seek(o.position,o.forcePrecise),t){case M.STOPPED:this.videoState.startTransitionTo(M.MANIFEST_LOADED),this.prepare();return;case M.MANIFEST_LOADED:this.videoState.startTransitionTo(M.INITIAL_REPRESENTATION_SELECTED);return;case M.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(M.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case M.METADATA_LOADED:this.videoState.startTransitionTo(M.READY),this.dash.updateRefsForCurrentTime();return;case M.READY:s===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):s===exports.PlaybackState.PAUSED?(this.videoState.setState(M.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(M.PLAYING),this.playIfAllowed());return;case M.PLAYING:s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(M.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case M.PAUSED:s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(M.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),a.merge(this.videoState.stateChangeStarted$.pipe(a.map(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:r})=>{this.log({message:`[videoState change] ${r}: ${JSON.stringify(t)}`})}),this.video=Ge(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioTracksExist$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new ES(this.video),this.dash=new nb({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:t=>this.dashLiteEvents.manifestReady$.next(t),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,r,s)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:r,thrown:s,category:a.ErrorCategory.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,r=l=>{e.error$.next({id:"DashProvider",category:a.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:l})},s=()=>{const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:l},n=Ye(this.video),o=(l,d)=>this.subscription.add(l.subscribe(d,r));o(n.timeUpdate$,e.position$),o(n.durationChange$,e.duration$),o(n.ended$,e.endedEvent$),o(n.looped$,e.loopedEvent$),o(n.error$,e.error$),o(n.isBuffering$,e.isBuffering$),o(n.playing$,e.firstFrameEvent$),o(n.canplay$,e.canplay$),this.subscription.add(n.seeking$.subscribe(()=>{a.isNullable(this.params.desiredState.seekState.getState().state!==C.Applying)&&(this.videoState.getState()===M.PLAYING||this.videoState.getState()===M.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(mt(this.video,t.isLooped,r)),this.subscription.add(He(this.video,t.volume,n.volumeState$,r)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ze(this.video,t.playbackRate,n.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),o(Ji(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===M.READY&&this.videoState.setState(M.READY)},r)).add(n.pause$.subscribe(()=>{this.videoState.setState(M.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(M.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},r)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(M.METADATA_LOADED)},r)).add(n.currentBuffer$.subscribe(l=>{this.buffer.fill(),e.currentBuffer$.next(l)},r)).add(this.dashLiteEvents.error$.pipe(a.map(({id:l,message:d,thrown:u})=>({id:`DashLite_${l}`,category:a.ErrorCategory.WTF,message:d,thrown:u}))).subscribe(this.params.output.error$)).add(a.merge(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$,this.params.output.element$,this.elementSize$,a.fromEvent(this.video,"progress")).pipe(a.map(()=>{var l,d,u;const c=this.currentRepresentation$.getValue(),h=this.representations$.getValue(),f=this.params.desiredState.autoVideoTrackSwitching.getTransition(),p=this.params.desiredState.videoTrack.getState(),v=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),m=this.elementSize$.getValue(),S=s();f&&this.params.desiredState.autoVideoTrackSwitching.setState(f.to);let b;if(!S&&a.isNonNullable(p))b=p;else{const g=ot(this.video.buffered,this.video.currentTime*1e3),P=S?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,E=Math.min(g/P,1);b=(d=di(h.map(({track:T})=>T),{container:m,throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:E,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 a.isNonNullable(b)?(u=h.find(({track:g})=>g.id===b))===null||u===void 0?void 0:u.representation:void 0}),a.filterChanged()).subscribe(this.currentRepresentation$,r)).add(a.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(a.filter(l=>l.to===M.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(a.filter(a.isNonNullable))}).pipe(a.once()).subscribe(()=>this.videoState.setState(M.INITIAL_REPRESENTATION_SELECTED),r)).add(this.currentRepresentation$.pipe(a.filter(a.isNonNullable),a.filterChanged((l,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&s()?l.height<=d.height:l===d)).subscribe(l=>{const d=ot(this.video.buffered,this.video.currentTime*1e3),u=Math.min(d/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||u<=.5||!s())&&(this.dash.setQualityByRepresentation(l,!0),this.params.output.hostname$.next(de(l.baseURL)))},r)).add(this.dashLiteEvents.responseHeaders$.subscribe(l=>{const{type:d,reused:u}=Rl(l);this.params.output.httpConnectionType$.next(d),this.params.output.httpConnectionReused$.next(u)})).add(this.dashLiteEvents.idxRequestPing$.pipe(a.once(),a.mapTo(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(l=>this.params.dependencies.throughputEstimator.addRawRtt(l))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,r)).add(this.dashLiteEvents.representationPlay$.pipe(a.filter(a.isNonNullable)).subscribe(this.handleRepresentationPlay,r)).add(a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return a.assertNever(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){et(this.video).then(e=>{e||(this.videoState.setState(M.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}}var Se;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(Se||(Se={}));var Xi;(function(i){i.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",i.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Xi||(Xi={}));var be;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(be||(be={}));var H;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(H||(H={}));var Nt;(function(i){i.MP4="mp4",i.WEBM="webm"})(Nt||(Nt={}));var Ds=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};const ub=(i,e={})=>{const r=e.timeout||1,s=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-s-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-s))}})},1)},db=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Mn=db?ub:window.requestIdleCallback;var Jr,Kr;let Nl=!1;try{Nl=Al()&&parseInt((Kr=(Jr=navigator.userAgent.match(/Version\/(\d+)/))===null||Jr===void 0?void 0:Jr[1])!==null&&Kr!==void 0?Kr:"",10)<16}catch(i){console.error(i)}class cb{constructor(e){this.bufferFull$=new a.Subject,this.error$=new a.Subject,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const r=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!r),this.currentTask=null}this.queue.length&&this.pull()}catch(r){this.error$.next({id:"BufferTaskQueueUnknown",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:r})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return J(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(r=>{const s={operation:"append",data:e,signal:t,callback:r};this.queue.push(s),this.pull()})})}remove(e,t,r){return J(this,void 0,void 0,function*(){return r&&r.aborted?!1:new Promise(s=>{const n={operation:"remove",from:e,to:t,signal:r,callback:s};this.queue.unshift(n),this.pull()})})}abort(e){return J(this,void 0,void 0,function*(){return new Promise(t=>{let r;Nl&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(const{callback:s}of this.queue)s(!1);r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask)}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:r}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&r==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"&&r==="remove"||this.error$.next({id:`BufferTaskQueue:${r}`,category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:n}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:a.assertNever(t)}}}var Vn=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};const Cl=new TextDecoder("ascii"),Dl=i=>{let e=0,t=i.getUint32(e);e+=4;const r=new DataView(i.buffer,i.byteOffset+e,4),s=Cl.decode(r);e+=4,t===0?t=1/0:t===1&&(e+=8,t=1/0);const n=Math.min(t,i.byteLength)-e,o=new DataView(i.buffer,i.byteOffset+e,n);return{id:s,size:t,contents:o}},hb=i=>Cl.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",fb=(i,e,t)=>{const r=Dl(i),s=[];let n=0;const o=()=>{const m=r.contents.getUint32(n);return n+=4,m};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,v=(t?t.to+1:i.byteOffset+i.byteLength)+h;for(let m=0;m<f;m++){const S=o(),b=S>>>31,g=S<<1>>>1,P=o();if(o(),b!==0)throw new Error("Unsupported multilevel sidx");const E=P/u*1e3;s.push({status:H.NONE,time:{from:p,to:p+E},byte:{from:v,to:v+g-1}}),p+=E,v+=g}return s},pb=i=>{let e=0,t=!1,r=!1;for(;e<=i.byteLength&&!t;){const s=new DataView(i.buffer,i.byteOffset+e);try{const n=Dl(s);if(r||(r=n.id==="mdat"),e+n.size<=i.byteLength)e+=n.size;else break}catch(n){t=!0}}return e>0&&e<=i.byteLength&&r?new DataView(i.buffer,i.byteOffset,e):null},mb={validateData:hb,parseInit:()=>null,getIndexRange:()=>{},parseSegments:fb,parseFeedableSegmentChunk:pb};var y;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.Chapters=272869232]="Chapters",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.SilentTracks=22612]="SilentTracks",i[i.SilentTrackNumber=22743]="SilentTrackNumber",i[i.Position=167]="Position",i[i.PrevSize=171]="PrevSize",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.EncryptedBlock=175]="EncryptedBlock",i[i.Attachments=423732329]="Attachments",i[i.Tags=307544935]="Tags",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.CueRelativePosition=240]="CueRelativePosition",i[i.CueDuration=178]="CueDuration",i[i.CueBlockNumber=21368]="CueBlockNumber",i[i.CueCodecState=234]="CueCodecState",i[i.CueReference=219]="CueReference",i[i.CueRefTime=150]="CueRefTime"})(y||(y={}));var A;(function(i){i.SignedInteger="int",i.UnsignedInteger="uint",i.Float="float",i.String="string",i.UTF8="utf8",i.Date="date",i.Master="master",i.Binary="binary"})(A||(A={}));const Fn={[y.EBML]:{type:A.Master},[y.EBMLVersion]:{type:A.UnsignedInteger},[y.EBMLReadVersion]:{type:A.UnsignedInteger},[y.EBMLMaxIDLength]:{type:A.UnsignedInteger},[y.EBMLMaxSizeLength]:{type:A.UnsignedInteger},[y.DocType]:{type:A.String},[y.DocTypeVersion]:{type:A.UnsignedInteger},[y.DocTypeReadVersion]:{type:A.UnsignedInteger},[y.Void]:{type:A.Binary},[y.Segment]:{type:A.Master},[y.SeekHead]:{type:A.Master},[y.Seek]:{type:A.Master},[y.SeekID]:{type:A.Binary},[y.SeekPosition]:{type:A.UnsignedInteger},[y.Info]:{type:A.Master},[y.TimestampScale]:{type:A.UnsignedInteger},[y.Duration]:{type:A.Float},[y.Tracks]:{type:A.Master},[y.Chapters]:{type:A.Master},[y.Cluster]:{type:A.Master},[y.Timestamp]:{type:A.UnsignedInteger},[y.SilentTracks]:{type:A.Master},[y.SilentTrackNumber]:{type:A.UnsignedInteger},[y.Position]:{type:A.UnsignedInteger},[y.PrevSize]:{type:A.UnsignedInteger},[y.SimpleBlock]:{type:A.Binary},[y.BlockGroup]:{type:A.Master},[y.EncryptedBlock]:{type:A.Binary},[y.Attachments]:{type:A.Master},[y.Tags]:{type:A.Master},[y.Cues]:{type:A.Master},[y.CuePoint]:{type:A.Master},[y.CueTime]:{type:A.UnsignedInteger},[y.CueTrackPositions]:{type:A.Master},[y.CueTrack]:{type:A.UnsignedInteger},[y.CueClusterPosition]:{type:A.UnsignedInteger},[y.CueRelativePosition]:{type:A.UnsignedInteger},[y.CueDuration]:{type:A.UnsignedInteger},[y.CueBlockNumber]:{type:A.UnsignedInteger},[y.CueCodecState]:{type:A.UnsignedInteger},[y.CueReference]:{type:A.Master},[y.CueRefTime]:{type:A.UnsignedInteger}},Ol=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const r=Zi(i,t),s=r in Fn,n=s?Fn[r].type:A.Binary,o=i.getUint8(t);let l=0;o&128?l=1:o&64?l=2:o&32?l=3:o&16?l=4:o&8?l=5:o&4?l=6:o&2?l=7:o&1&&(l=8);const d=new DataView(i.buffer,i.byteOffset+t+1,l-1),u=((o&255>>l)<<(l-1)*8)+Zi(d),c=t+l;let h;return c+u>i.byteLength?h=new DataView(i.buffer,i.byteOffset+c):h=new DataView(i.buffer,i.byteOffset+c,u),{tag:s?r:"0x"+r.toString(16).toUpperCase(),type:n,tagHeaderSize:c,tagSize:c+u,value:h,valueSize:u}},Zi=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint16(0)<<8|i.getUint8(2);case 4:return i.getUint32(0);case 5:return i.getUint32(0)<<8|i.getUint8(4);case 6:return i.getUint32(0)<<16|i.getUint16(4);case 7:return i.getUint32(0)<<32|i.getUint16(4)<<8|i.getUint8(6);case 8:return i.getUint32(0)<<32|i.getUint32(4)}return 0},Me=(i,e)=>{switch(e){case A.SignedInteger:return i.getInt8(0);case A.UnsignedInteger:return Zi(i);case A.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case A.String:return new TextDecoder("ascii").decode(i);case A.UTF8:return new TextDecoder("utf-8").decode(i);case A.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case A.Master:return i;case A.Binary:return i;default:a.assertNever(e)}},hi=(i,e)=>{let t=0;for(;t<i.byteLength;){const r=new DataView(i.buffer,i.byteOffset+t),s=Ol(r);if(!e(s))return;s.type===A.Master&&hi(s.value,e),t=s.value.byteOffset-i.byteOffset+s.valueSize}},vb=i=>{if(i.getUint32(0)!==y.EBML)return!1;let e,t,r;const s=Ol(i);return hi(s.value,({tag:n,type:o,value:l})=>(n===y.EBMLReadVersion?e=Me(l,o):n===y.DocType?t=Me(l,o):n===y.DocTypeReadVersion&&(r=Me(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)},Ll=[y.Info,y.SeekHead,y.Tracks,y.Chapters,y.Cluster,y.Cues,y.Attachments,y.Tags],Sb=[y.Timestamp,y.SilentTracks,y.SilentTrackNumber,y.Position,y.PrevSize,y.SimpleBlock,y.BlockGroup,y.EncryptedBlock],bb=i=>{let e,t,r,s,n=!1,o=!1,l=!1,d,u;return hi(i,({tag:c,type:h,value:f,valueSize:p})=>{if(c===y.SeekID){const v=Me(f,h);u=Zi(v)}else c!==y.SeekPosition&&(u=void 0);return c===y.Segment?(e=f.byteOffset,t=f.byteOffset+p):c===y.Info?n=!0:c===y.SeekHead?o=!0:c===y.TimestampScale?r=Me(f,h):c===y.Duration?s=Me(f,h):c===y.SeekPosition&&u===y.Cues?d=Me(f,h):n&&o&&Ll.includes(c)&&(l=!0),!l}),a.assertNonNullable(e,"Failed to parse webm Segment start"),a.assertNonNullable(t,"Failed to parse webm Segment end"),a.assertNonNullable(s,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(s/1e9*r*1e3),cuesSeekPosition:d}},gb=i=>{if(a.isNullable(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},yb=(i,e)=>{let t=!1,r=!1;const s=l=>a.isNonNullable(l.time)&&a.isNonNullable(l.position),n=[];let o;return hi(i,({tag:l,type:d,value:u})=>{switch(l){case y.Cues:t=!0;break;case y.CuePoint:o&&s(o)&&n.push(o),o={};break;case y.CueTime:o&&(o.time=Me(u,d));break;case y.CueTrackPositions:break;case y.CueClusterPosition:o&&(o.position=Me(u,d));break;default:t&&Ll.includes(l)&&(r=!0)}return!(t&&r)}),o&&s(o)&&n.push(o),n.map((l,d)=>{const{time:u,position:c}=l,h=n[d+1];return{status: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}}})},Tb=i=>{let e=0,t=!1;try{hi(i,r=>r.tag===y.Cluster?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):Sb.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||(t=[y.SimpleBlock,y.BlockGroup,y.EncryptedBlock].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},Eb={validateData:vb,parseInit:bb,getIndexRange:gb,parseSegments:yb,parseFeedableSegmentChunk:Tb};class Un{constructor(e,t,r,s,{fetcher:n,tuning:o,getCurrentPosition:l,compatibilityMode:d=!1}){switch(this.onLastSegment$=new a.ValueSubject(!1),this.fullyBuffered$=new a.ValueSubject(!1),this.playingRepresentation$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.gaps=[],this.subscription=new a.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new lt,this.destroyAbortController=new lt,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=a.abortable(this.destroyAbortController.signal,function(u){return Ee(this,arguments,function*(){const c=this.representations.get(u);a.assertNonNullable(c,`Cannot find representation ${u}`),this.playingRepresentationId=u,this.downloadingRepresentationId=u,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${c.mime}; codecs="${c.codecs}"`),this.sourceBufferTaskQueue=new cb(this.sourceBuffer),this.subscription.add(a.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},v=>this.error$.next({id:"SegmentEjection",category:a.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:v}))),this.subscription.add(a.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:a.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(v=>{if(!this.sourceBuffer)return;const m=Math.min(this.bufferLimit,Vn(this.sourceBuffer.buffered)*.8);this.bufferLimit=m,this.pruneBuffer(this.getCurrentPosition(),v)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(v=>this.error$.next(v))),yield yield R(this.loadInit(c,"high",!0));const h=this.initData.get(c.id),f=this.segments.get(c.id);if(a.assertNonNullable(h,"No init buffer for starting representation"),a.assertNonNullable(f,"No segments for starting representation"),!(h instanceof ArrayBuffer))return yield R(void 0);let p=0;for(const v of f)v.time.from-p>0&&this.gaps.push({representation:c.id,from:p,to:v.time.from}),p=v.time.to;a.isNonNullable(c.duration)&&c.duration-p>0&&this.gaps.push({representation:c.id,from:p,to:c.duration}),yield yield R(this.sourceBufferTaskQueue.append(h,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId)})}.bind(this)),this.switchTo=a.abortable(this.destroyAbortController.signal,function(u){return Ee(this,arguments,function*(){if(u===this.downloadingRepresentationId||u===this.switchingToRepresentationId)return yield R(void 0);this.switchingToRepresentationId=u;const c=this.representations.get(u);a.assertNonNullable(c,`No such representation ${u}`);let h=this.initData.get(u);if(a.isNullable(h)?yield yield R(this.loadInit(c,"high",!1)):h instanceof Promise&&(yield yield R(h)),h=this.initData.get(u),!h||!(h instanceof ArrayBuffer)||!this.sourceBuffer)return yield R(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=u,this.abort(),yield yield R(this.sourceBufferTaskQueue.append(h,this.downloadAbortController.signal));const f=this.getCurrentPosition();a.isNonNullable(f)&&this.maintain(f)})}.bind(this)),this.fetcher=n,this.tuning=o,this.compatibilityMode=d,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=l,this.container=r,r){case Nt.MP4:this.containerParser=mb;break;case Nt.WEBM:this.containerParser=Eb;break;default:a.assertNever(r)}this.initData=new Map(s.map(u=>[u.id,null])),this.segments=new Map,this.representations=new Map(s.map(u=>[u.id,u])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new lt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(a.isNullable(e)||a.isNullable(this.downloadingRepresentationId)||a.isNullable(this.playingRepresentationId)||a.isNullable(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(a.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;const s=r.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=ot(this.sourceBuffer.buffered,e),h=s?s.time.to+100:-1/0;s&&c>=s.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&Vn(this.sourceBuffer.buffered)>=this.bufferLimit){const u=ot(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<c);return}let l=[];if(!this.activeSegments.size&&(l=this.selectForwardBufferSegments(r,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&s)if(l.includes(s))u="high";else{const c=xe(l,0);c&&c.time.from-s.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}!this.preloadOnly&&!this.allInitsLoaded&&s&&s.status===H.FED&&!l.length&&ot(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=xe(r,-1);d&&d.status===H.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===d))}findSegmentStartTime(e){var t,r,s;const n=(r=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&r!==void 0?r:this.playingRepresentationId;if(!n)return;const o=this.segments.get(n);if(!o)return;const l=o.find(d=>d.time.from<=e&&d.time.to>=e);return(s=l==null?void 0:l.time.from)!==null&&s!==void 0?s:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;this.initData.clear(),this.segments.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer&&this.mediaSource.readyState==="open"&&(this.abortBuffer(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,r){const s=e.findIndex(({status:h,time:{from:f,to:p}},v)=>{const m=f<=r&&p>=r,S=f>r||m||v===0&&r===0,b=Math.min(this.forwardBufferTarget,this.bufferLimit),g=this.preloadOnly&&f<=r+b||p<=r+b;return(h===H.NONE||h===H.PARTIALLY_EJECTED&&S&&g&&this.sourceBuffer&&!Ds(this.sourceBuffer.buffered,r))&&S&&g});if(s===-1)return[];if(t!==be.BYTE_RANGE)return e.slice(s,s+1);const n=e;let o=0,l=0;const d=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let h=s;h<n.length&&(o<=u||l<=c);h++){const f=n[h];if(o+=f.byte.to+1-f.byte.from,l+=f.time.to+1-f.time.from,f.status===H.NONE||f.status===H.PARTIALLY_EJECTED)d.push(f);else break}return d}loadSegments(e,t,r="auto"){return J(this,void 0,void 0,function*(){if(!e.length)return;let s,n,o=e;const{type:l}=t.segmentReference;switch(l){case be.BYTE_RANGE:{s=t.segmentReference.url,n={from:xe(e,0).byte.from,to:xe(e,-1).byte.to};break}case be.TEMPLATE:{const u=xe(e,0);s=new URL(u.url,t.segmentReference.baseUrl).toString(),o=[u];break}default:a.assertNever(l)}for(const u of o)u.status=H.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(yield a.abortable(d,function(){return Ee(this,arguments,function*(){const u=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield R(new Promise(c=>setTimeout(c,u)))})}.bind(this))(),d.aborted))for(const u of this.activeSegments)e.includes(u.segment)&&this.abortSegment(u.segment);return void this.fetcher.fetch(s,{range:n,onProgress:(u,c)=>{if(!d.aborted)try{this.onSomeDataLoaded(u,t.id,n?n.from:0,c,d)}catch(h){this.error$.next({id:"SegmentFeeding",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}},signal:d,priority:r}).then(()=>this.failedDownloads=0,u=>{for(const c of this.activeSegments)e.includes(c.segment)&&this.abortSegment(c.segment);this.onSegmentDownloadError(u)})})}onSegmentDownloadError(e){var t;let r=!1;const s=this.getCurrentPosition();this.sourceBuffer&&a.isNonNullable(s)&&(r=ot((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,s)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,r||this.error$.next({id:"SegmentDownload",category:a.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,r,s,n){if(!this.activeSegments.size)return;const o=()=>{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 v of(f=this.segments.get(p.id))!==null&&f!==void 0?f:[])v.status===H.FED&&v.time.from===h.segment.time.from&&v.time.to===h.segment.time.to&&(v.status=H.NONE);this.activeSegments.delete(h),this.detectGapsWhenIdle(t,[h.segment])},d=this.representations.get(t);if(!d)return;const u=d.segmentReference.type,c=e.byteLength;for(const h of this.activeSegments){const{segment:f}=h,p=u===be.BYTE_RANGE,v=p?f.byte.to-f.byte.from+1:c;if(h.representationId!==t||!(!p||f.byte.from>=r&&f.byte.to<r+e.byteLength))continue;if(n.aborted){o();continue}const S=p?f.byte.from-r:0,b=p?f.byte.to-r:e.byteLength,g=S<s,P=b<=s;if(f.status===H.DOWNLOADING&&g&&P){f.status=H.DOWNLOADED,this.activeSegments.delete(h);const E=new DataView(e.buffer,e.byteOffset+S,v);this.sourceBufferTaskQueue.append(E,n).then(T=>T&&!n.aborted?l(h):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&g&&(h.loadedBytes=Math.min(v,s-S),h.loadedBytes>h.feedingBytes)){const E=new DataView(e.buffer,e.byteOffset+S+h.feedingBytes,h.loadedBytes-h.feedingBytes),T=h.loadedBytes===v?E:this.containerParser.parseFeedableSegmentChunk(E);T!=null&&T.byteLength&&(f.status=H.PARTIALLY_FED,h.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,n).then(w=>{if(n.aborted)o();else if(w)h.fedBytes+=T.byteLength,h.fedBytes===v&&l(h);else{if(h.feedingBytes<v)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[s,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const r=this.representations.get(e);r&&(this.initLoadIdleCallback=Mn(()=>dr(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return J(this,void 0,void 0,function*(){const s=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!r&&this.failedDownloads>0?a.abortable(this.destroyAbortController.signal,function(){return Ee(this,arguments,function*(){const l=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield R(new Promise(d=>setTimeout(d,l)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s)).then(l=>{if(!l)return;const{dataView:d,segments:u}=l,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c),this.segments.set(e.id,u)}).then(()=>this.failedDownloads=0,l=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:a.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o})}pruneBuffer(e,t,r=!1){return J(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||a.isNullable(e)||this.sourceBuffer.updating)return!1;let s=0,n=1/0,o=-1/0,l=!1;const d=u=>{var c;n=Math.min(n,u.time.from),o=Math.max(o,u.time.to);const h="size"in u?(c=u.size)!==null&&c!==void 0?c:0:u.byte.to-u.byte.from;s+=h};for(const u of this.segments.values())for(const c of u){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||s>=t)break;c.status===H.FED&&d(c)}if(l=isFinite(n)&&isFinite(o),!l){s=0,n=1/0,o=-1/0;for(const u of this.segments.values())for(const c of u){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||s>t)break;c.status===H.FED&&d(c)}}if(l=isFinite(n)&&isFinite(o),!l)for(let u=0;u<this.sourceBuffer.buffered.length;u++){const c=this.sourceBuffer.buffered.start(u)*1e3,h=this.sourceBuffer.buffered.end(u)*1e3;for(const f of this.segments.values())for(const p of f)if(p.status===H.NONE&&Math.round(p.time.from)<=Math.round(c)&&Math.round(p.time.to)>=Math.round(h)){n=c,o=h;break}}if(l=isFinite(n)&&isFinite(o),!l&&r){s=0,n=1/0,o=-1/0;const u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const c of this.segments.values())for(const h of c)h.time.from>e+u&&h.status===H.FED&&d(h)}return l=isFinite(n)&&isFinite(o),l?this.sourceBufferTaskQueue.remove(n,o):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}detectGaps(e,t){if(this.sourceBuffer)for(const r of t){let s={representation:e,from:r.time.from,to:r.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3;if(!(l<=r.time.from||o>=r.time.to)){if(o<=r.time.from&&l>=r.time.to){s=void 0;break}l>r.time.from&&l<r.time.to&&(s.from=l),o<r.time.to&&o>r.time.from&&(s.to=o)}}s&&s.to-s.from>=1&&!this.gaps.some(n=>s&&n.from===s.from&&n.to===s.to)&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Mn(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:a.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(a.isNullable(this.sourceBuffer)||a.isNullable(this.playingRepresentationId))return;const e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){const s=Math.round(this.sourceBuffer.buffered.start(r)*1e3),n=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:s,to:n})}const t=1;for(const r of this.segments.values())for(const s of r){const{status:n}=s;if(n!==H.FED&&n!==H.PARTIALLY_EJECTED)continue;const o=Math.floor(s.time.from),l=Math.ceil(s.time.to),d=e.some(c=>c.from-t<=o&&c.to+t>=l),u=e.some(c=>o>=c.from-t&&o<=c.to+t||l>=c.from-t&&l<=c.to+t);d||(u?s.status=H.PARTIALLY_EJECTED:s.status=H.NONE)}}}var Pt;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(Pt||(Pt={}));class $b{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.abortAllController=new lt,this.subscription=new a.Subscription,this.fetchManifest=a.abortable(this.abortAllController.signal,function(s){return Ee(this,arguments,function*(){let n=s;this.requestQuic&&(n=It(n));const o=yield yield R(Rt(n,{signal:this.abortAllController.signal}).catch(Qt));return o?(this.onHeadersReceived(o.headers),yield R(o.text())):yield R(null)})}.bind(this)),this.fetch=a.abortable(this.abortAllController.signal,function(s,{rangeMethod:n=this.compatibilityMode?Pt.HEADER:Pt.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0}={}){var h,f,p,v;return Ee(this,arguments,function*(){let m=s;const S=new Headers;if(o)switch(n){case Pt.HEADER:{S.append("Range",`bytes=${o.from}-${o.to}`);break}case Pt.PARAM:{const $=new URL(m,location.href);$.searchParams.append("bytes",`${o.from}-${o.to}`),m=$.toString();break}default:a.assertNever(n)}this.requestQuic&&(m=It(m));let b=this.abortAllController.signal;if(u){const $=new lt;if(this.subscription.add(a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.fromEvent(u,"abort")).subscribe(()=>{try{$.abort()}catch(D){Qt(D)}})),this.abortAllController.signal.aborted||u.aborted)try{$.abort()}catch(D){Qt(D)}b=$.signal}const g=a.now(),P=yield yield R(Rt(m,{priority:d,headers:S,signal:b}).catch(Qt)),E=a.now();if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(E-g),!P)return yield R(null);if(!P.ok||!P.body)return yield R(Promise.reject(new Error(`Fetch error ${P.status}: ${P.statusText}`)));this.onHeadersReceived(P.headers);const T=parseInt((f=P.headers.get("Content-Length"))!==null&&f!==void 0?f:"",10)||o&&o.to-o.from+1||NaN;if(!T){const $=yield yield R(P.arrayBuffer());return(p=this.throughputEstimator)===null||p===void 0||p.addRawSpeed($.byteLength,a.now()-E),l==null||l(new DataView($),$.byteLength),yield R($)}if(!l&&!c)return yield R(P.arrayBuffer());const[w,F]=P.body.tee(),O=w.getReader();c&&((v=this.throughputEstimator)===null||v===void 0||v.trackStream(F));let I=0;const U=new ArrayBuffer(T),N=new Uint8Array(U),_=new DataView(U);let G=!1;const K=$=>{G=!0,Qt($)},te=a.abortable(b,function({done:$,value:D}){return Ee(this,arguments,function*(){if(I===0&&this.lastRequestFirstBytes$.next(a.now()-g),b.aborted)return yield R(void 0);$?l==null||l(_,I):D&&(N.set(D,I),I+=D.byteLength,l==null||l(_,I),yield yield R(O==null?void 0:O.read().then(te,K)))})}.bind(this));return yield yield R(O==null?void 0:O.read().then(te,K)),yield R(G?null:U)})}.bind(this)),this.fetchByteRangeRepresentation=a.abortable(this.abortAllController.signal,function(s,n,o){var l;return Ee(this,arguments,function*(){if(s.type!==be.BYTE_RANGE)return yield R(null);const{from:d,to:u}=s.initRange;let c=d,h=u,f=!1,p,v;s.indexRange&&(p=s.indexRange.from,v=s.indexRange.to,f=u+1===p,f&&(c=Math.min(p,d),h=Math.max(v,u))),c=Math.min(c,0);const m=yield yield R(this.fetch(s.url,{range:{from:c,to:h},priority:o,measureThroughput:!1}));if(!m)return yield R(null);const S=new DataView(m,d-c,u-c+1);if(!n.validateData(S))throw new Error("Invalid media file");const b=n.parseInit(S),g=(l=s.indexRange)!==null&&l!==void 0?l:n.getIndexRange(b);if(!g)throw new ReferenceError("No way to load representation index");let P;if(f)P=new DataView(m,g.from-c,g.to-g.from+1);else{const T=yield yield R(this.fetch(s.url,{range:g,priority:o,measureThroughput:!1}));if(!T)return yield R(null);P=new DataView(T)}const E=n.parseSegments(P,b,g);return yield R({dataView:new DataView(m),segments:E})})}.bind(this)),this.fetchTemplateRepresentation=a.abortable(this.abortAllController.signal,function(s,n){return Ee(this,arguments,function*(){if(s.type!==be.TEMPLATE)return yield R(null);const o=new URL(s.initUrl,s.baseUrl).toString(),l=yield yield R(this.fetch(o,{priority:n,measureThroughput:!1}));if(!l)return yield R(null);const d=s.segments.map(u=>Object.assign(Object.assign({},u),{status:H.NONE,size:void 0}));return yield R({segments:d,dataView:new DataView(l)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r}onHeadersReceived(e){const{type:t,reused:r}=Rl(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){var s,n;return J(this,void 0,void 0,function*(){const{type:o}=e;switch(o){case be.BYTE_RANGE:return(s=yield this.fetchByteRangeRepresentation(e,t,r))!==null&&s!==void 0?s:null;case be.TEMPLATE:return(n=yield this.fetchTemplateRepresentation(e,r))!==null&&n!==void 0?n:null;default:a.assertNever(o)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Qt=i=>{if(!(i instanceof DOMException)||!(i.name==="AbortError"||i.code===20))throw i},jn=i=>{if(!i.startsWith("P"))return;const e=(o,l)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*l},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),s=(r==null?void 0:r[1])==="-"?-1:1,n={days:e(r==null?void 0:r[5],s),hours:e(r==null?void 0:r[6],s),minutes:e(r==null?void 0:r[7],s),seconds:e(r==null?void 0:r[8],s)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},Xr=(i,e)=>{let t=i;t=t.replaceAll("$$","$");const r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,n]of Object.entries(r)){const o=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(o,(l,d)=>a.isNullable(n)?l:a.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},kb=(i,e)=>{var t,r,s,n,o,l,d,u,c,h,f,p,v,m,S,b,g,P,E,T,w,F,O,I,U,N,_,G,K,te,$,D,z,ee,ie,ce,Pe;const j=new DOMParser().parseFromString(i,"application/xml"),ae={video:[],audio:[],text:[]},ue=j.children[0],me=ue.getElementsByTagName("Period")[0],tt=me.children;let Ae;const qe=ue.getAttribute("mediaPresentationDuration"),it=me.getAttribute("duration");if(qe)Ae=jn(qe);else if(it){const we=jn(it);a.isNonNullable(we)&&(Ae=we)}let xt=0;const vt=(r=(t=ue.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&r!==void 0?r:[],Ul=vt.includes(Xi.WEBM_AS_IN_FFMPEG)||vt.includes(Xi.WEBM_AS_IN_SPEC)?Nt.WEBM:Nt.MP4;for(const we of tt){const fi=we.getAttribute("mimeType"),jl=we.getAttribute("codecs"),ua=(s=we.getAttribute("contentType"))!==null&&s!==void 0?s:fi==null?void 0:fi.split("/")[0],Hl=(o=(n=we.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],Gl=we.querySelectorAll("Representation"),Yl=we.querySelector("SegmentTemplate");if(ua!=="text")for(const ne of Gl){const Bt=(l=ne.getAttribute("mimeType"))!==null&&l!==void 0?l:fi,da=(u=(d=ne.getAttribute("codecs"))!==null&&d!==void 0?d:jl)!==null&&u!==void 0?u:"",pi=(h=(c=ne.getAttribute("contentType"))!==null&&c!==void 0?c:Bt==null?void 0:Bt.split("/")[0])!==null&&h!==void 0?h:ua,ql=(p=(f=we.getAttribute("profiles"))===null||f===void 0?void 0:f.split(","))!==null&&p!==void 0?p:[],zl=parseInt((v=ne.getAttribute("width"))!==null&&v!==void 0?v:"",10),ca=parseInt((m=ne.getAttribute("height"))!==null&&m!==void 0?m:"",10),ha=parseInt((S=ne.getAttribute("bandwidth"))!==null&&S!==void 0?S:"",10)/1e3,fa=(b=ne.getAttribute("frameRate"))!==null&&b!==void 0?b:"",Wl=(g=ne.getAttribute("quality"))!==null&&g!==void 0?g:void 0,Ql=fa?oa(fa):void 0,Jl=(P=ne.getAttribute("id"))!==null&&P!==void 0?P:(xt++).toString(10),Kl=pi==="video"?`${ca}p`:pi==="audio"?`${ha}Kbps`:da,Xl=`${Jl}@${Kl}`,Zl=(w=(T=(E=ne.querySelector("BaseURL"))===null||E===void 0?void 0:E.textContent)===null||T===void 0?void 0:T.trim())!==null&&w!==void 0?w:"",pa=new URL(Zl,e).toString(),eu=[...vt,...Hl,...ql];let fr;const tu=ne.querySelector("SegmentBase"),rt=(F=ne.querySelector("SegmentTemplate"))!==null&&F!==void 0?F:Yl;if(tu){const Mt=(I=(O=ne.querySelector("SegmentBase Initialization"))===null||O===void 0?void 0:O.getAttribute("range"))!==null&&I!==void 0?I:"",[Vt,mr]=Mt.split("-").map(st=>parseInt(st,10)),Ft={from:Vt,to:mr},Ut=(U=ne.querySelector("SegmentBase"))===null||U===void 0?void 0:U.getAttribute("indexRange"),[vr,mi]=Ut?Ut.split("-").map(st=>parseInt(st,10)):[],jt=Ut?{from:vr,to:mi}:void 0;fr={type:be.BYTE_RANGE,url:pa,initRange:Ft,indexRange:jt}}else if(rt){const Mt={representationId:(N=ne.getAttribute("id"))!==null&&N!==void 0?N:void 0,bandwidth:(_=ne.getAttribute("bandwidth"))!==null&&_!==void 0?_:void 0},Vt=parseInt((G=rt.getAttribute("timescale"))!==null&&G!==void 0?G:"",10),mr=(K=rt.getAttribute("initialization"))!==null&&K!==void 0?K:"",Ft=rt.getAttribute("media"),Ut=($=parseInt((te=rt.getAttribute("startNumber"))!==null&&te!==void 0?te:"",10))!==null&&$!==void 0?$:1,vr=Xr(mr,Mt);if(!Ft)throw new ReferenceError("No media attribute in SegmentTemplate");const mi=(D=rt.querySelectorAll("SegmentTimeline S"))!==null&&D!==void 0?D:[],jt=[];if(mi.length){let st=Ut,at=0;for(const Ht of mi){const St=parseInt((z=Ht.getAttribute("d"))!==null&&z!==void 0?z:"",10)*1e3,Gt=parseInt((ee=Ht.getAttribute("r"))!==null&&ee!==void 0?ee:"",10)||0,Yt=(ce=parseInt((ie=Ht.getAttribute("t"))!==null&&ie!==void 0?ie:"",10))!==null&&ce!==void 0?ce:void 0;for(let ma=0;ma<Gt+1;ma++){const iu=Xr(Ft,Object.assign(Object.assign({},Mt),{segmentNumber:st.toString(10),segmentTime:Yt.toString(10)})),ru=Yt?Yt/Vt:at;at+=St/Vt;const su=at;st++,jt.push({time:{from:ru,to:su},url:iu})}}}else if(a.isNonNullable(Ae)){const at=parseInt((Pe=rt.getAttribute("duration"))!==null&&Pe!==void 0?Pe:"",10)/Vt*1e3,Ht=Math.ceil(Ae/at);let St=0;for(let Gt=1;Gt<Ht;Gt++){const Yt=Xr(Ft,Object.assign(Object.assign({},Mt),{segmentNumber:Gt.toString(10),segmentTime:St.toString(10)}));jt.push({time:{from:St,to:St+at},url:Yt}),St+=at}}fr={type:be.TEMPLATE,baseUrl:pa,initUrl:vr,segments:jt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!pi||!Bt)continue;const pr={video:Se.VIDEO,audio:Se.AUDIO,text:Se.TEXT}[pi];pr&&ae[pr].push({id:Xl,kind:pr,segmentReference:fr,profiles:eu,duration:Ae,bitrate:ha,mime:Bt,codecs:da,width:zl,height:ca,fps:Ql,quality:Wl})}}return{duration:Ae,container:Ul,representations:ae}},Pb=["timeupdate","progress","play","seeked","stalled"];var ve;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(ve||(ve={}));let Ab=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new a.Subscription,this.state$=new Q(ve.NONE),this.currentVideoRepresentation$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.forceEnded$=new a.Subject,this.gapWatchdogStarted=!1,this.destroyController=new lt,this.initManifest=a.abortable(this.destroyController.signal,function(t,r){return Ee(this,arguments,function*(){this.element=t,this.state$.startTransitionTo(ve.MANIFEST_READY);const s=yield yield R(this.fetcher.fetchManifest(r).catch(l=>this.error$.next({id:"LoadManifest",category:a.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:l})));if(!s)return yield R(void 0);let n;try{n=kb(s!=null?s:"",r)}catch(l){this.error$.next({id:"ManifestParsing",category:a.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:l})}if(!n)return yield R(void 0);const o=({mime:l,codecs:d})=>{var u,c,h;return Boolean(((u=t.canPlayType)===null||u===void 0?void 0:u.call(t,l))&&((h=(c=window.MediaSource)===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0?void 0:h.call(c,`${l}; codecs="${d}"`)))};this.manifest=Object.assign(Object.assign({},n),{representations:oi(Object.entries(n.representations).map(([l,d])=>[l,d.filter(o)]))}),this.manifest.representations.video.length?this.state$.setState(ve.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:a.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this)),this.initRepresentations=a.abortable(this.destroyController.signal,function(t,r){return Ee(this,arguments,function*(){a.assertNonNullable(this.manifest),a.assertNonNullable(this.element),this.state$.startTransitionTo(ve.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0};this.videoBufferManager=new Un(Se.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(r)&&(this.audioBufferManager=new Un(Se.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,s),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));const n=a.merge(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(a.map(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),o=a.merge(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(a.map(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.subscription.add(a.merge(this.forceEnded$,a.combine({allBuffersFull:n,someBufferEnded:o}).pipe(a.filter(({allBuffersFull:l,someBufferEnded:d})=>l&&d))).subscribe(()=>{var l;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{(l=this.source)===null||l===void 0||l.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.subscription.add(a.merge(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.source.readyState!=="open"&&(yield yield R(new Promise(l=>{var d;return(d=this.source)===null||d===void 0?void 0:d.addEventListener("sourceopen",l)}))),a.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&a.isNonNullable(r)?yield yield R(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(r)])):yield yield R(this.videoBufferManager.startWith(t)),this.state$.setState(ve.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,r;if(!this.element||!this.videoBufferManager)return;const s=this.element.currentTime*1e3;this.videoBufferManager.maintain(s),(t=this.audioBufferManager)===null||t===void 0||t.maintain(s),(this.videoBufferManager.gaps.length||!((r=this.audioBufferManager)===null||r===void 0)&&r.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=a.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),n=>{this.error$.next({id:"GapWatchdog",category:a.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new $b({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initBuffer(){a.assertNonNullable(this.element),this.state$.setState(ve.RUNNING),this.subscription.add(a.merge(...Pb.map(e=>a.fromEvent(this.element,e)),a.fromEvent(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:a.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(a.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(a.fromEvent(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Ds(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}switchRepresentation(e,t){return J(this,void 0,void 0,function*(){const r={[Se.VIDEO]:this.videoBufferManager,[Se.AUDIO]:this.audioBufferManager,[Se.TEXT]:null}[e];return r==null?void 0:r.switchTo(t)})}seek(e,t){var r,s,n,o,l;a.assertNonNullable(this.element),a.assertNonNullable(this.videoBufferManager);let d;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?d=e:d=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!==null&&r!==void 0?r:e,(n=(s=this.audioBufferManager)===null||s===void 0?void 0:s.findSegmentStartTime(e))!==null&&n!==void 0?n:e),Ds(this.element.buffered,d)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)===null||o===void 0||o.abort()),this.videoBufferManager.maintain(d),(l=this.audioBufferManager)===null||l===void 0||l.maintain(d),this.element.currentTime=d/1e3}stop(){var e,t;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(e=this.videoBufferManager)===null||e===void 0||e.destroy(),this.videoBufferManager=null,(t=this.audioBufferManager)===null||t===void 0||t.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(ve.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3,t=[];for(const r of this.bufferManagers)for(const s of r.gaps)r.playingRepresentation$.getValue()===s.representation&&s.from<=e&&s.to>e&&(this.element.duration*1e3-s.to<this.tuning.endGapTolerance?t.push(1/0):t.push(s.to));if(t.length){const r=Math.max(...t);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=r/1e3}}};var X;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(X||(X={}));const wb=({id:i,width:e,height:t,bitrate:r,fps:s,quality:n})=>{var o;const l=(o=n?ci(n):void 0)!==null&&o!==void 0?o:pt({width:e,height:t});return l&&{id:i,quality:l,bitrate:r,size:{width:e,height:t},fps:s}},_b=({id:i,bitrate:e})=>({id:i,bitrate:e}),Rb=(i,e,t)=>{var r;const s=e.indexOf(t);return(r=xe(i,Math.round(i.length*s/e.length)))!==null&&r!==void 0?r:xe(i,-1)};class Ib{constructor(e){this.subscription=new a.Subscription,this.videoState=new Q(X.STOPPED),this.elementSize$=new a.ValueSubject(void 0),this.textTracksManager=new Oe,this.videoTracks=[],this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new MS,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(n.state===C.Requested&&(s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&t!==X.STOPPED&&r!==exports.PlaybackState.STOPPED&&this.seek(n.position,n.forcePrecise),r===exports.PlaybackState.STOPPED){t!==X.STOPPED&&(this.videoState.startTransitionTo(X.STOPPED),this.player.stop(),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(X.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(t){case X.STOPPED:this.videoState.startTransitionTo(X.READY),this.prepare();return;case X.READY:r===exports.PlaybackState.PAUSED?(this.videoState.setState(X.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(X.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.READY&&k(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case X.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(X.PAUSED),this.video.pause()):(s==null?void 0:s.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case X.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(X.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}}},this.params=e,this.video=Ge(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioTracksExist$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Ab({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,r=Ye(this.video),s=u=>{e.error$.next({id:"DashVKProvider",category:a.ErrorCategory.WTF,message:"DashVKProvider internal logic error",thrown:u})},n=(u,c)=>this.subscription.add(u.subscribe(c,s));n(r.timeUpdate$,e.position$),n(r.durationChange$,e.duration$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.lastRequestFirstBytes$.pipe(a.filter(a.isNonNullable),a.once(),a.mapTo(void 0)),e.firstBytesEvent$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(mt(this.video,t.isLooped,s)),this.subscription.add(He(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Ze(this.video,t.playbackRate,r.playbackRateState$,s)),n(Ji(this.video),this.elementSize$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(X.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(X.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(r.canplay$.subscribe(()=>{this.videoState.getState()===X.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var c;if(u===ve.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[];const h=this.player.getRepresentations();a.assertNonNullable(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((m,S)=>S.bitrate-m.bitrate),p=Array.from(h.video).sort((m,S)=>S.bitrate-m.bitrate);if(!this.params.tuning.isAudioDisabled)for(const m of f){const S=_b(m);S&&this.audioTracks.push({track:S,representation:m})}for(const m of p){const S=wb(m);if(S){this.videoTracks.push({track:S,representation:m});const b=!this.params.tuning.isAudioDisabled&&Rb(f,p,m);b&&this.audioRepresentations.set(m.id,b)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:m})=>m)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:m})=>m)),this.params.output.isAudioTracksExist$.next(!!this.audioTracks.length);const v=this.selectVideoRepresentation();a.assertNonNullable(v),this.player.initRepresentations(v.id,(c=this.audioRepresentations.get(v.id))===null||c===void 0?void 0:c.id)}else u===ve.REPRESENTATIOS_READY&&(this.videoState.setState(X.READY),this.player.initBuffer())},s));const o=u=>e.error$.next({id:"RepresentationSwitch",category:a.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(a.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,a.fromEvent(this.video,"progress")).subscribe(()=>{const u=this.player.state$.getState(),c=this.player.state$.getTransition();if(u!==ve.RUNNING||c||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const h=this.selectVideoRepresentation();if(h){this.player.switchRepresentation(Se.VIDEO,h.id).catch(o);const f=this.audioRepresentations.get(h.id);f&&this.player.switchRepresentation(Se.AUDIO,f.id).catch(o)}},s)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(a.filterChanged(),a.map(u=>{var c;return u&&((c=this.videoTracks.find(({representation:{id:h}})=>h===u))===null||c===void 0?void 0:c.track)})).subscribe(e.currentVideoTrack$,s)),this.textTracksManager.connect(this.video,t,e);const l=t.playbackState.stateChangeStarted$.pipe(a.map(({to:u})=>u===exports.PlaybackState.READY),a.filterChanged());this.subscription.add(a.merge(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const u=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(a.merge(l,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,s))}selectVideoRepresentation(){var e,t,r,s,n,o;const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.videoTrack.getState(),u=(e=this.videoTracks.find(({track:{id:b}})=>b===d))===null||e===void 0?void 0:e.track,c=this.params.output.currentVideoTrack$.getValue(),h=ot(this.video.buffered,this.video.currentTime*1e3),f=l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=Math.min(h/Math.min(f,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),v=Math.max(u&&!l&&(r=(t=this.audioRepresentations.get(u.id))===null||t===void 0?void 0:t.bitrate)!==null&&r!==void 0?r:0,c&&(n=(s=this.audioRepresentations.get(c.id))===null||s===void 0?void 0:s.bitrate)!==null&&n!==void 0?n:0),m=di(this.videoTracks.map(({track:b})=>b),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:p,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),S=l?m!=null?m:u:u!=null?u:m;return S&&((o=this.videoTracks.find(({track:b})=>b===S))===null||o===void 0?void 0:o.representation)}prepare(){return J(this,void 0,void 0,function*(){this.player.initManifest(this.video,this.params.source.url)})}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){et(this.video).then(e=>{e||(this.videoState.setState(X.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}}const Nb=5e3,Le={};var V;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(V||(V={}));const Ci=(i,e)=>new a.Observable(t=>{const r=(s,n)=>t.next(n);return i.on(e,r),()=>i.off(e,r)});class Cb{constructor(e){this.subscription=new a.Subscription,this.videoState=new Q(V.INITIALIZING),this.textTracksManager=new Oe,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(t!==V.INITIALIZING)switch((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===C.Requested&&this.seek(n.position),r){case exports.PlaybackState.STOPPED:switch(t){case V.STOPPED:break;case V.READY:case V.PLAYING:case V.PAUSED:this.stop();break;default:a.assertNever(t)}break;case exports.PlaybackState.READY:switch(t){case V.STOPPED:this.prepare();break;case V.READY:case V.PLAYING:case V.PAUSED:break;default:a.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case V.PLAYING:break;case V.STOPPED:this.prepare();break;case V.READY:case V.PAUSED:this.playIfAllowed();break;default:a.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case V.PAUSED:break;case V.STOPPED:this.prepare();break;case V.READY:this.videoState.setState(V.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case V.PLAYING:this.pause();break;default:a.assertNever(t)}break;default:a.assertNever(r)}},this.video=Ge(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioTracksExist$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)===null||e===void 0||e.detachMedia(),(t=this.hls)===null||t===void 0||t.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:a.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:s}),e=!0},r=window.setTimeout(()=>t("timeout"),Nb);dr(import("hls.js/dist/hls.min.js").then(s=>{e||(Le.Hls=s.default,Le.Events=s.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){a.assertNonNullable(Le.Hls,"hls.js not loaded"),this.hls=new Le.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(V.STOPPED)}subscribe(){a.assertNonNullable(Le.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:a.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},s=Ye(this.video),n=(u,c)=>this.subscription.add(u.subscribe(c,r));n(s.timeUpdate$,t.position$),n(s.durationChange$,t.duration$),n(s.ended$,t.endedEvent$),n(s.looped$,t.loopedEvent$),n(s.error$,t.error$),n(s.isBuffering$,t.isBuffering$),n(s.currentBuffer$,t.currentBuffer$),n(s.loadStart$,t.firstBytesEvent$),n(s.playing$,t.firstFrameEvent$),n(s.canplay$,t.canplay$),n(s.seeked$,t.seekedEvent$),this.subscription.add(mt(this.video,e.isLooped,r)),this.subscription.add(He(this.video,e.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ze(this.video,e.playbackRate,s.playbackRateState$,r)),this.subscription.add(Ci(this.hls,Le.Events.ERROR).subscribe(u=>{var c;u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:a.ErrorCategory.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${(c=u.err)===null||c===void 0?void 0:c.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(V.PLAYING),k(e.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(V.PAUSED),k(e.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===V.READY&&this.videoState.setState(V.READY),this.videoState.getState()===V.PLAYING&&this.playIfAllowed()},r)),n(Ci(this.hls,Le.Events.MANIFEST_PARSED).pipe(a.map(({levels:u})=>u.reduce((c,h)=>{var f,p;const v=h.name||h.height.toString(10),{width:m,height:S}=h,b=(p=ci((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&p!==void 0?p:pt({width:m,height:S});if(!b)return c;const g=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,P={id:v.toString(),quality:b,bitrate:h.bitrate/1e3,size:{width:m,height:S},fps:g};return this.trackLevels.set(v,{track:P,level:h}),c.push(P),c},[]))),t.availableVideoTracks$),n(Ci(this.hls,Le.Events.LEVEL_LOADING).pipe(a.map(({url:u})=>de(u))),t.hostname$),this.subscription.add(Ne(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:r}));const o=u=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:h})=>h===u))===null||c===void 0?void 0:c.track},l=Ci(this.hls,Le.Events.LEVEL_SWITCHED).pipe(a.map(({level:u})=>o(this.hls.levels[u])));l.pipe(a.filter(a.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Ne(e.videoTrack,()=>{var u;return(u=o(this.hls.levels[this.hls.currentLevel]))===null||u===void 0?void 0:u.id},u=>{var c;if(a.isNullable(u))return;const h=(c=this.trackLevels.get(u))===null||c===void 0?void 0:c.level;if(!h)return;const f=this.hls.levels.indexOf(h),p=this.hls.currentLevel,v=this.hls.levels[p];!v||h.bitrate>v.bitrate?this.hls.nextLevel=f:(this.hls.loadLevel=f,this.hls.loadLevel=f)},{changed$:l.pipe(a.map(u=>u==null?void 0:u.id)),onError:r})),n(s.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=a.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo(V.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return J(this,void 0,void 0,function*(){this.videoState.startTransitionTo(V.PLAYING),(yield et(this.video))||(this.videoState.setState(V.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(V.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.setAttribute("src",""),this.video.load(),this.videoState.setState(V.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const Hn="X-Playback-Duration";var Gn=i=>J(void 0,void 0,void 0,function*(){const e=yield Rt(i,{method:"HEAD"});return e.headers.has(Hn)?parseInt(e.headers.get(Hn),10):void 0});const Db=i=>{let e=null;if(i.QUALITY&&(e=ci(i.QUALITY)),!e&&i.RESOLUTION){const[t,r]=i.RESOLUTION.split("x").map(s=>parseInt(s,10));e=pt({width:t,height:r})}return e!=null?e:null},xl=(i,e=i)=>J(void 0,void 0,void 0,function*(){var t;const n=(yield(yield Rt(i)).text()).split(`
6
+ "use strict";var au=Object.create;var va=Object.defineProperty;var nu=Object.getOwnPropertyDescriptor;var ou=Object.getOwnPropertyNames;var lu=Object.getPrototypeOf,uu=Object.prototype.hasOwnProperty;var du=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ou(e))!uu.call(i,s)&&s!==t&&va(i,s,{get:()=>e[s],enumerable:!(r=nu(e,s))||r.enumerable});return i};var Sa=(i,e,t)=>(t=i!=null?au(lu(i)):{},du(e||!i||!i.__esModule?va(t,"default",{value:i,enumerable:!0}):t,i));var a=require("@vkontakte/videoplayer-shared/es2015.cjs.js"),cu=require("lodash/debounce.js");const hu="2.0.81",fu="@vkontakte/videoplayer-core";exports.PlaybackState=void 0;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(i){i.MPEG="MPEG",i.DASH="DASH",i.DASH_SEP="DASH_SEP",i.DASH_SEP_VK="DASH_SEP",i.DASH_WEBM="DASH_WEBM",i.DASH_WEBM_VK="DASH_WEBM",i.DASH_ONDEMAND="DASH_ONDEMAND",i.DASH_ONDEMAND_VK="DASH_ONDEMAND",i.DASH_LIVE="DASH_LIVE",i.DASH_LIVE_WEBM="DASH_LIVE_WEBM",i.HLS="HLS",i.HLS_ONDEMAND="HLS_ONDEMAND",i.HLS_JS="HLS",i.HLS_LIVE="HLS_LIVE",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(exports.VideoFormat||(exports.VideoFormat={}));var he;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(he||(he={}));exports.ChromecastState=void 0;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var C;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(C||(C={}));var pu=i=>new Promise((e,t)=>{const r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});class mu{constructor(e){var t;this.connection$=new a.ValueSubject(void 0),this.castState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new a.Subject,this.realCastState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const r="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${r}`}),e.isDisabled||!r)return;const s=a.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=Boolean(window.__onGCastApiAvailable);s?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||pu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:a.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,s,n;(n=(s=(r=cast.framework.CastContext.getInstance())===null||r===void 0?void 0:r.getCurrentSession())===null||s===void 0?void 0:s.getMediaSession())===null||n===void 0||n.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){a.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();a.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();a.isNullable(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(a.fromEvent(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(s=>{var n,o;switch(s.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=r.getCurrentSession())===null||n===void 0?void 0:n.getMediaSession())===null||o===void 0?void 0:o.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return a.assertNever(s.sessionState)}})).add(a.merge(a.fromEvent(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(a.tap(s=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(s)}`})}),a.map(s=>s.castState)),a.observableFrom([r.getCastState()])).pipe(a.filterChanged(),a.map(vu),a.tap(s=>{this.log({message:`realCastState$: ${s}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(s=>{var n;const o=s===exports.ChromecastState.CONNECTED,l=a.isNonNullable(this.connection$.getValue());if(o&&!l){const d=r.getCurrentSession();a.assertNonNullable(d);const u=d.getCastDevice(),c=(n=d.getMediaSession())===null||n===void 0?void 0:n.media.contentId;(a.isNullable(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:d,castDevice:u}))}else!o&&l&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(s===exports.ChromecastState.CONNECTED?a.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:s)}))}initializeCastApi(){var e;let t,r,s;try{t=cast.framework.CastContext.getInstance(),r=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,s=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:r,autoJoinPolicy:s}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:a.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const vu=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return exports.ChromecastState.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return exports.ChromecastState.AVAILABLE;case cast.framework.CastState.CONNECTING:return exports.ChromecastState.CONNECTING;case cast.framework.CastState.CONNECTED:return exports.ChromecastState.CONNECTED;default:return a.assertNever(i)}};var ba=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},ye=function(i){try{return!!i()}catch(e){return!0}},Su=ye,er=!Su(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),so=er,ao=Function.prototype,hs=ao.call,bu=so&&ao.bind.bind(hs,hs),Ce=so?bu:function(i){return function(){return hs.apply(i,arguments)}},no=Ce,gu=no({}.toString),yu=no("".slice),tr=function(i){return yu(gu(i),8,-1)},Tu=Ce,Eu=ye,$u=tr,Sr=Object,ku=Tu("".split),Pu=Eu(function(){return!Sr("z").propertyIsEnumerable(0)})?function(i){return $u(i)=="String"?ku(i,""):Sr(i)}:Sr,ir=function(i){return i==null},Au=ir,wu=TypeError,oo=function(i){if(Au(i))throw wu("Can't call method on "+i);return i},_u=Pu,Ru=oo,si=function(i){return _u(Ru(i))},Iu=function(){},Ct={},vi=function(i){return i&&i.Math==Math&&i},le=vi(typeof globalThis=="object"&&globalThis)||vi(typeof window=="object"&&window)||vi(typeof self=="object"&&self)||vi(typeof ba=="object"&&ba)||function(){return this}()||Function("return this")(),fs=typeof document=="object"&&document.all,Nu=typeof fs=="undefined"&&fs!==void 0,lo={all:fs,IS_HTMLDDA:Nu},uo=lo,Cu=uo.all,se=uo.IS_HTMLDDA?function(i){return typeof i=="function"||i===Cu}:function(i){return typeof i=="function"},Du=le,Ou=se,ga=Du.WeakMap,Lu=Ou(ga)&&/native code/.test(String(ga)),ya=se,co=lo,xu=co.all,Ke=co.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:ya(i)||i===xu}:function(i){return typeof i=="object"?i!==null:ya(i)},Bu=ye,Ue=!Bu(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),ct={},Mu=le,Ta=Ke,ps=Mu.document,Vu=Ta(ps)&&Ta(ps.createElement),Ls=function(i){return Vu?ps.createElement(i):{}},Fu=Ue,Uu=ye,ju=Ls,ho=!Fu&&!Uu(function(){return Object.defineProperty(ju("div"),"a",{get:function(){return 7}}).a!=7}),Hu=Ue,Gu=ye,fo=Hu&&Gu(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Yu=Ke,qu=String,zu=TypeError,Xe=function(i){if(Yu(i))return i;throw zu(qu(i)+" is not an object")},Wu=er,Si=Function.prototype.call,ke=Wu?Si.bind(Si):function(){return Si.apply(Si,arguments)},xs={},br=xs,gr=le,Qu=se,Ea=function(i){return Qu(i)?i:void 0},ht=function(i,e){return arguments.length<2?Ea(br[i])||Ea(gr[i]):br[i]&&br[i][e]||gr[i]&&gr[i][e]},Ju=Ce,Bs=Ju({}.isPrototypeOf),rr=typeof navigator!="undefined"&&String(navigator.userAgent)||"",po=le,yr=rr,$a=po.process,ka=po.Deno,Pa=$a&&$a.versions||ka&&ka.version,Aa=Pa&&Pa.v8,Te,Hi;Aa&&(Te=Aa.split("."),Hi=Te[0]>0&&Te[0]<4?1:+(Te[0]+Te[1]));!Hi&&yr&&(Te=yr.match(/Edge\/(\d+)/),(!Te||Te[1]>=74)&&(Te=yr.match(/Chrome\/(\d+)/),Te&&(Hi=+Te[1])));var mo=Hi,wa=mo,Ku=ye,vo=!!Object.getOwnPropertySymbols&&!Ku(function(){var i=Symbol();return!String(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&wa&&wa<41}),Xu=vo,So=Xu&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Zu=ht,ed=se,td=Bs,id=So,rd=Object,bo=id?function(i){return typeof i=="symbol"}:function(i){var e=Zu("Symbol");return ed(e)&&td(e.prototype,rd(i))},sd=String,sr=function(i){try{return sd(i)}catch(e){return"Object"}},ad=se,nd=sr,od=TypeError,ft=function(i){if(ad(i))return i;throw od(nd(i)+" is not a function")},ld=ft,ud=ir,Ms=function(i,e){var t=i[e];return ud(t)?void 0:ld(t)},Tr=ke,Er=se,$r=Ke,dd=TypeError,cd=function(i,e){var t,r;if(e==="string"&&Er(t=i.toString)&&!$r(r=Tr(t,i))||Er(t=i.valueOf)&&!$r(r=Tr(t,i))||e!=="string"&&Er(t=i.toString)&&!$r(r=Tr(t,i)))return r;throw dd("Can't convert object to primitive value")},Gi={},hd={get exports(){return Gi},set exports(i){Gi=i}},go=!0,_a=le,fd=Object.defineProperty,pd=function(i,e){try{fd(_a,i,{value:e,configurable:!0,writable:!0})}catch(t){_a[i]=e}return e},md=le,vd=pd,Ra="__core-js_shared__",Sd=md[Ra]||vd(Ra,{}),Vs=Sd,Ia=Vs;(hd.exports=function(i,e){return Ia[i]||(Ia[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.27.2",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.27.2/LICENSE",source:"https://github.com/zloirock/core-js"});var bd=oo,gd=Object,Fs=function(i){return gd(bd(i))},yd=Ce,Td=Fs,Ed=yd({}.hasOwnProperty),je=Object.hasOwn||function(e,t){return Ed(Td(e),t)},$d=Ce,kd=0,Pd=Math.random(),Ad=$d(1 .toString),yo=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Ad(++kd+Pd,36)},wd=le,_d=Gi,Na=je,Rd=yo,Id=vo,Nd=So,Et=wd.Symbol,kr=_d("wks"),Cd=Nd?Et.for||Et:Et&&Et.withoutSetter||Rd,pe=function(i){return Na(kr,i)||(kr[i]=Id&&Na(Et,i)?Et[i]:Cd("Symbol."+i)),kr[i]},Dd=ke,Ca=Ke,Da=bo,Od=Ms,Ld=cd,xd=pe,Bd=TypeError,Md=xd("toPrimitive"),Vd=function(i,e){if(!Ca(i)||Da(i))return i;var t=Od(i,Md),r;if(t){if(e===void 0&&(e="default"),r=Dd(t,i,e),!Ca(r)||Da(r))return r;throw Bd("Can't convert object to primitive value")}return e===void 0&&(e="number"),Ld(i,e)},Fd=Vd,Ud=bo,Us=function(i){var e=Fd(i,"string");return Ud(e)?e:e+""},jd=Ue,Hd=ho,Gd=fo,bi=Xe,Oa=Us,Yd=TypeError,Pr=Object.defineProperty,qd=Object.getOwnPropertyDescriptor,Ar="enumerable",wr="configurable",_r="writable";ct.f=jd?Gd?function(e,t,r){if(bi(e),t=Oa(t),bi(r),typeof e=="function"&&t==="prototype"&&"value"in r&&_r in r&&!r[_r]){var s=qd(e,t);s&&s[_r]&&(e[t]=r.value,r={configurable:wr in r?r[wr]:s[wr],enumerable:Ar in r?r[Ar]:s[Ar],writable:!1})}return Pr(e,t,r)}:Pr:function(e,t,r){if(bi(e),t=Oa(t),bi(r),Hd)try{return Pr(e,t,r)}catch(s){}if("get"in r||"set"in r)throw Yd("Accessors not supported");return"value"in r&&(e[t]=r.value),e};var ar=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},zd=Ue,Wd=ct,Qd=ar,ai=zd?function(i,e,t){return Wd.f(i,e,Qd(1,t))}:function(i,e,t){return i[e]=t,i},Jd=Gi,Kd=yo,La=Jd("keys"),js=function(i){return La[i]||(La[i]=Kd(i))},Hs={},Xd=Lu,To=le,Zd=Ke,ec=ai,Rr=je,Ir=Vs,tc=js,ic=Hs,xa="Object already initialized",ms=To.TypeError,rc=To.WeakMap,Yi,ii,qi,sc=function(i){return qi(i)?ii(i):Yi(i,{})},ac=function(i){return function(e){var t;if(!Zd(e)||(t=ii(e)).type!==i)throw ms("Incompatible receiver, "+i+" required");return t}};if(Xd||Ir.state){var _e=Ir.state||(Ir.state=new rc);_e.get=_e.get,_e.has=_e.has,_e.set=_e.set,Yi=function(i,e){if(_e.has(i))throw ms(xa);return e.facade=i,_e.set(i,e),e},ii=function(i){return _e.get(i)||{}},qi=function(i){return _e.has(i)}}else{var bt=tc("state");ic[bt]=!0,Yi=function(i,e){if(Rr(i,bt))throw ms(xa);return e.facade=i,ec(i,bt,e),e},ii=function(i){return Rr(i,bt)?i[bt]:{}},qi=function(i){return Rr(i,bt)}}var Eo={set:Yi,get:ii,has:qi,enforce:sc,getterFor:ac},nc=er,$o=Function.prototype,Ba=$o.apply,Ma=$o.call,ko=typeof Reflect=="object"&&Reflect.apply||(nc?Ma.bind(Ba):function(){return Ma.apply(Ba,arguments)}),oc=tr,lc=Ce,Po=function(i){if(oc(i)==="Function")return lc(i)},Gs={},Ao={},wo={}.propertyIsEnumerable,_o=Object.getOwnPropertyDescriptor,uc=_o&&!wo.call({1:2},1);Ao.f=uc?function(e){var t=_o(this,e);return!!t&&t.enumerable}:wo;var dc=Ue,cc=ke,hc=Ao,fc=ar,pc=si,mc=Us,vc=je,Sc=ho,Va=Object.getOwnPropertyDescriptor;Gs.f=dc?Va:function(e,t){if(e=pc(e),t=mc(t),Sc)try{return Va(e,t)}catch(r){}if(vc(e,t))return fc(!cc(hc.f,e,t),e[t])};var bc=ye,gc=se,yc=/#|\.prototype\./,ni=function(i,e){var t=Ec[Tc(i)];return t==kc?!0:t==$c?!1:gc(e)?bc(e):!!e},Tc=ni.normalize=function(i){return String(i).replace(yc,".").toLowerCase()},Ec=ni.data={},$c=ni.NATIVE="N",kc=ni.POLYFILL="P",Ro=ni,Fa=Po,Pc=ft,Ac=er,wc=Fa(Fa.bind),nr=function(i,e){return Pc(i),e===void 0?i:Ac?wc(i,e):function(){return i.apply(e,arguments)}},gi=le,_c=ko,Rc=Po,Ic=se,Nc=Gs.f,Cc=Ro,gt=xs,Dc=nr,yt=ai,Ua=je,Oc=function(i){var e=function(t,r,s){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,r)}return new i(t,r,s)}return _c(i,this,arguments)};return e.prototype=i.prototype,e},De=function(i,e){var t=i.target,r=i.global,s=i.stat,n=i.proto,o=r?gi:s?gi[t]:(gi[t]||{}).prototype,l=r?gt:gt[t]||yt(gt,t,{})[t],d=l.prototype,u,c,h,f,p,v,m,S,b;for(f in e)u=Cc(r?f:t+(s?".":"#")+f,i.forced),c=!u&&o&&Ua(o,f),v=l[f],c&&(i.dontCallGetSet?(b=Nc(o,f),m=b&&b.value):m=o[f]),p=c&&m?m:e[f],!(c&&typeof v==typeof p)&&(i.bind&&c?S=Dc(p,gi):i.wrap&&c?S=Oc(p):n&&Ic(p)?S=Rc(p):S=p,(i.sham||p&&p.sham||v&&v.sham)&&yt(S,"sham",!0),yt(l,f,S),n&&(h=t+"Prototype",Ua(gt,h)||yt(gt,h,{}),yt(gt[h],f,p),i.real&&d&&(u||!d[f])&&yt(d,f,p)))},vs=Ue,Lc=je,Io=Function.prototype,xc=vs&&Object.getOwnPropertyDescriptor,Ys=Lc(Io,"name"),Bc=Ys&&function(){}.name==="something",Mc=Ys&&(!vs||vs&&xc(Io,"name").configurable),Vc={EXISTS:Ys,PROPER:Bc,CONFIGURABLE:Mc},No={},Fc=Math.ceil,Uc=Math.floor,jc=Math.trunc||function(e){var t=+e;return(t>0?Uc:Fc)(t)},Hc=jc,qs=function(i){var e=+i;return e!==e||e===0?0:Hc(e)},Gc=qs,Yc=Math.max,qc=Math.min,zc=function(i,e){var t=Gc(i);return t<0?Yc(t+e,0):qc(t,e)},Wc=qs,Qc=Math.min,Jc=function(i){return i>0?Qc(Wc(i),9007199254740991):0},Kc=Jc,zs=function(i){return Kc(i.length)},Xc=si,Zc=zc,eh=zs,ja=function(i){return function(e,t,r){var s=Xc(e),n=eh(s),o=Zc(r,n),l;if(i&&t!=t){for(;n>o;)if(l=s[o++],l!=l)return!0}else for(;n>o;o++)if((i||o in s)&&s[o]===t)return i||o||0;return!i&&-1}},th={includes:ja(!0),indexOf:ja(!1)},ih=Ce,Nr=je,rh=si,sh=th.indexOf,ah=Hs,Ha=ih([].push),nh=function(i,e){var t=rh(i),r=0,s=[],n;for(n in t)!Nr(ah,n)&&Nr(t,n)&&Ha(s,n);for(;e.length>r;)Nr(t,n=e[r++])&&(~sh(s,n)||Ha(s,n));return s},Co=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],oh=nh,lh=Co,uh=Object.keys||function(e){return oh(e,lh)},dh=Ue,ch=fo,hh=ct,fh=Xe,ph=si,mh=uh;No.f=dh&&!ch?Object.defineProperties:function(e,t){fh(e);for(var r=ph(t),s=mh(t),n=s.length,o=0,l;n>o;)hh.f(e,l=s[o++],r[l]);return e};var vh=ht,Do=vh("document","documentElement"),Sh=Xe,bh=No,Ga=Co,gh=Hs,yh=Do,Th=Ls,Eh=js,Ya=">",qa="<",Ss="prototype",bs="script",Oo=Eh("IE_PROTO"),Cr=function(){},Lo=function(i){return qa+bs+Ya+i+qa+"/"+bs+Ya},za=function(i){i.write(Lo("")),i.close();var e=i.parentWindow.Object;return i=null,e},$h=function(){var i=Th("iframe"),e="java"+bs+":",t;return i.style.display="none",yh.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Lo("document.F=Object")),t.close(),t.F},yi,Mi=function(){try{yi=new ActiveXObject("htmlfile")}catch(e){}Mi=typeof document!="undefined"?document.domain&&yi?za(yi):$h():za(yi);for(var i=Ga.length;i--;)delete Mi[Ss][Ga[i]];return Mi()};gh[Oo]=!0;var xo=Object.create||function(e,t){var r;return e!==null?(Cr[Ss]=Sh(e),r=new Cr,Cr[Ss]=null,r[Oo]=e):r=Mi(),t===void 0?r:bh.f(r,t)},kh=ye,Ph=!kh(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),Ah=je,wh=se,_h=Fs,Rh=js,Ih=Ph,Wa=Rh("IE_PROTO"),gs=Object,Nh=gs.prototype,Bo=Ih?gs.getPrototypeOf:function(i){var e=_h(i);if(Ah(e,Wa))return e[Wa];var t=e.constructor;return wh(t)&&e instanceof t?t.prototype:e instanceof gs?Nh:null},Ch=ai,Ws=function(i,e,t,r){return r&&r.enumerable?i[e]=t:Ch(i,e,t),i},Dh=ye,Oh=se,Lh=Ke,xh=xo,Qa=Bo,Bh=Ws,Mh=pe,ys=Mh("iterator"),Mo=!1,Ve,Dr,Or;[].keys&&(Or=[].keys(),"next"in Or?(Dr=Qa(Qa(Or)),Dr!==Object.prototype&&(Ve=Dr)):Mo=!0);var Vh=!Lh(Ve)||Dh(function(){var i={};return Ve[ys].call(i)!==i});Vh?Ve={}:Ve=xh(Ve);Oh(Ve[ys])||Bh(Ve,ys,function(){return this});var Vo={IteratorPrototype:Ve,BUGGY_SAFARI_ITERATORS:Mo},Fh=pe,Uh=Fh("toStringTag"),Fo={};Fo[Uh]="z";var Qs=String(Fo)==="[object z]",jh=Qs,Hh=se,Vi=tr,Gh=pe,Yh=Gh("toStringTag"),qh=Object,zh=Vi(function(){return arguments}())=="Arguments",Wh=function(i,e){try{return i[e]}catch(t){}},or=jh?Vi:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=Wh(e=qh(i),Yh))=="string"?t:zh?Vi(e):(r=Vi(e))=="Object"&&Hh(e.callee)?"Arguments":r},Qh=Qs,Jh=or,Kh=Qh?{}.toString:function(){return"[object "+Jh(this)+"]"},Xh=Qs,Zh=ct.f,ef=ai,tf=je,rf=Kh,sf=pe,Ja=sf("toStringTag"),Js=function(i,e,t,r){if(i){var s=t?i:i.prototype;tf(s,Ja)||Zh(s,Ja,{configurable:!0,value:e}),r&&!Xh&&ef(s,"toString",rf)}},af=Vo.IteratorPrototype,nf=xo,of=ar,lf=Js,uf=Ct,df=function(){return this},cf=function(i,e,t,r){var s=e+" Iterator";return i.prototype=nf(af,{next:of(+!r,t)}),lf(i,s,!1,!0),uf[s]=df,i},hf=De,ff=ke,Uo=Vc,pf=cf,mf=Bo,vf=Js,Ka=Ws,Sf=pe,Xa=Ct,jo=Vo,bf=Uo.PROPER;Uo.CONFIGURABLE;jo.IteratorPrototype;var Ti=jo.BUGGY_SAFARI_ITERATORS,Lr=Sf("iterator"),Za="keys",Ei="values",en="entries",gf=function(){return this},yf=function(i,e,t,r,s,n,o){pf(t,e,r);var l=function(b){if(b===s&&f)return f;if(!Ti&&b in c)return c[b];switch(b){case Za:return function(){return new t(this,b)};case Ei:return function(){return new t(this,b)};case en:return function(){return new t(this,b)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=i.prototype,h=c[Lr]||c["@@iterator"]||s&&c[s],f=!Ti&&h||l(s),p=e=="Array"&&c.entries||h,v,m,S;if(p&&(v=mf(p.call(new i)),v!==Object.prototype&&v.next&&(vf(v,d,!0,!0),Xa[d]=gf)),bf&&s==Ei&&h&&h.name!==Ei&&(u=!0,f=function(){return ff(h,this)}),s)if(m={values:l(Ei),keys:n?f:l(Za),entries:l(en)},o)for(S in m)(Ti||u||!(S in c))&&Ka(c,S,m[S]);else hf({target:e,proto:!0,forced:Ti||u},m);return o&&c[Lr]!==f&&Ka(c,Lr,f,{name:s}),Xa[e]=f,m},Tf=function(i,e){return{value:i,done:e}},Ef=si,Ks=Iu,tn=Ct,Ho=Eo,$f=ct.f,kf=yf,$i=Tf,Pf=go,Af=Ue,Go="Array Iterator",wf=Ho.set,_f=Ho.getterFor(Go);kf(Array,"Array",function(i,e){wf(this,{type:Go,target:Ef(i),index:0,kind:e})},function(){var i=_f(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,$i(void 0,!0)):t=="keys"?$i(r,!1):t=="values"?$i(e[r],!1):$i([r,e[r]],!1)},"values");var rn=tn.Arguments=tn.Array;Ks();Ks();Ks();if(!Pf&&Af&&rn.name!=="values")try{$f(rn,"name",{value:"values"})}catch(i){}var Rf=pe,If=Ct,Nf=Rf("iterator"),Cf=Array.prototype,Df=function(i){return i!==void 0&&(If.Array===i||Cf[Nf]===i)},Of=or,sn=Ms,Lf=ir,xf=Ct,Bf=pe,Mf=Bf("iterator"),Yo=function(i){if(!Lf(i))return sn(i,Mf)||sn(i,"@@iterator")||xf[Of(i)]},Vf=ke,Ff=ft,Uf=Xe,jf=sr,Hf=Yo,Gf=TypeError,Yf=function(i,e){var t=arguments.length<2?Hf(i):e;if(Ff(t))return Uf(Vf(t,i));throw Gf(jf(i)+" is not iterable")},qf=ke,an=Xe,zf=Ms,Wf=function(i,e,t){var r,s;an(i);try{if(r=zf(i,"return"),!r){if(e==="throw")throw t;return t}r=qf(r,i)}catch(n){s=!0,r=n}if(e==="throw")throw t;if(s)throw r;return an(r),t},Qf=nr,Jf=ke,Kf=Xe,Xf=sr,Zf=Df,ep=zs,nn=Bs,tp=Yf,ip=Yo,on=Wf,rp=TypeError,Fi=function(i,e){this.stopped=i,this.result=e},ln=Fi.prototype,Xs=function(i,e,t){var r=t&&t.that,s=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),d=Qf(e,r),u,c,h,f,p,v,m,S=function(g){return u&&on(u,"normal",g),new Fi(!0,g)},b=function(g){return s?(Kf(g),l?d(g[0],g[1],S):d(g[0],g[1])):l?d(g,S):d(g)};if(n)u=i.iterator;else if(o)u=i;else{if(c=ip(i),!c)throw rp(Xf(i)+" is not iterable");if(Zf(c)){for(h=0,f=ep(i);f>h;h++)if(p=b(i[h]),p&&nn(ln,p))return p;return new Fi(!1)}u=tp(i,c)}for(v=n?i.next:u.next;!(m=Jf(v,u)).done;){try{p=b(m.value)}catch(g){on(u,"throw",g)}if(typeof p=="object"&&p&&nn(ln,p))return p}return new Fi(!1)},sp=Us,ap=ct,np=ar,op=function(i,e,t){var r=sp(e);r in i?ap.f(i,r,np(0,t)):i[r]=t},lp=De,up=Xs,dp=op;lp({target:"Object",stat:!0},{fromEntries:function(e){var t={};return up(e,function(r,s){dp(t,r,s)},{AS_ENTRIES:!0}),t}});var cp=xs,hp=cp.Object.fromEntries,fp={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},pp=fp,mp=le,vp=or,Sp=ai,un=Ct,bp=pe,dn=bp("toStringTag");for(var xr in pp){var cn=mp[xr],Br=cn&&cn.prototype;Br&&vp(Br)!==dn&&Sp(Br,dn,xr),un[xr]=un.Array}var gp=hp,yp=gp,Tp=yp,Ep=Tp,oi=Ep,$p=tr,lr=typeof process!="undefined"&&$p(process)=="process",kp=ht,Pp=ct,Ap=pe,wp=Ue,hn=Ap("species"),_p=function(i){var e=kp(i),t=Pp.f;wp&&e&&!e[hn]&&t(e,hn,{configurable:!0,get:function(){return this}})},Rp=Bs,Ip=TypeError,Np=function(i,e){if(Rp(e,i))return i;throw Ip("Incorrect invocation")},Cp=Ce,Dp=se,Ts=Vs,Op=Cp(Function.toString);Dp(Ts.inspectSource)||(Ts.inspectSource=function(i){return Op(i)});var qo=Ts.inspectSource,Lp=Ce,xp=ye,zo=se,Bp=or,Mp=ht,Vp=qo,Wo=function(){},Fp=[],Qo=Mp("Reflect","construct"),Zs=/^\s*(?:class|function)\b/,Up=Lp(Zs.exec),jp=!Zs.exec(Wo),qt=function(e){if(!zo(e))return!1;try{return Qo(Wo,Fp,e),!0}catch(t){return!1}},Jo=function(e){if(!zo(e))return!1;switch(Bp(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return jp||!!Up(Zs,Vp(e))}catch(t){return!0}};Jo.sham=!0;var Hp=!Qo||xp(function(){var i;return qt(qt.call)||!qt(Object)||!qt(function(){i=!0})||i})?Jo:qt,Gp=Hp,Yp=sr,qp=TypeError,zp=function(i){if(Gp(i))return i;throw qp(Yp(i)+" is not a constructor")},fn=Xe,Wp=zp,Qp=ir,Jp=pe,Kp=Jp("species"),Ko=function(i,e){var t=fn(i).constructor,r;return t===void 0||Qp(r=fn(t)[Kp])?e:Wp(r)},Xp=Ce,Zp=Xp([].slice),em=TypeError,tm=function(i,e){if(i<e)throw em("Not enough arguments");return i},im=rr,Xo=/(?:ipad|iphone|ipod).*applewebkit/i.test(im),fe=le,rm=ko,sm=nr,pn=se,am=je,Zo=ye,mn=Do,nm=Zp,vn=Ls,om=tm,lm=Xo,um=lr,Es=fe.setImmediate,$s=fe.clearImmediate,dm=fe.process,Mr=fe.Dispatch,cm=fe.Function,Sn=fe.MessageChannel,hm=fe.String,Vr=0,Kt={},bn="onreadystatechange",ri,nt,Fr,Ur;Zo(function(){ri=fe.location});var ea=function(i){if(am(Kt,i)){var e=Kt[i];delete Kt[i],e()}},jr=function(i){return function(){ea(i)}},gn=function(i){ea(i.data)},yn=function(i){fe.postMessage(hm(i),ri.protocol+"//"+ri.host)};(!Es||!$s)&&(Es=function(e){om(arguments.length,1);var t=pn(e)?e:cm(e),r=nm(arguments,1);return Kt[++Vr]=function(){rm(t,void 0,r)},nt(Vr),Vr},$s=function(e){delete Kt[e]},um?nt=function(i){dm.nextTick(jr(i))}:Mr&&Mr.now?nt=function(i){Mr.now(jr(i))}:Sn&&!lm?(Fr=new Sn,Ur=Fr.port2,Fr.port1.onmessage=gn,nt=sm(Ur.postMessage,Ur)):fe.addEventListener&&pn(fe.postMessage)&&!fe.importScripts&&ri&&ri.protocol!=="file:"&&!Zo(yn)?(nt=yn,fe.addEventListener("message",gn,!1)):bn in vn("script")?nt=function(i){mn.appendChild(vn("script"))[bn]=function(){mn.removeChild(this),ea(i)}}:nt=function(i){setTimeout(jr(i),0)});var el={set:Es,clear:$s},tl=function(){this.head=null,this.tail=null};tl.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};var il=tl,fm=rr,pm=/ipad|iphone|ipod/i.test(fm)&&typeof Pebble!="undefined",mm=rr,vm=/web0s(?!.*chrome)/i.test(mm),dt=le,Tn=nr,Sm=Gs.f,Hr=el.set,bm=il,gm=Xo,ym=pm,Tm=vm,Gr=lr,En=dt.MutationObserver||dt.WebKitMutationObserver,$n=dt.document,kn=dt.process,ki=dt.Promise,Pn=Sm(dt,"queueMicrotask"),ks=Pn&&Pn.value,Tt,Yr,qr,Pi,An;if(!ks){var Ai=new bm,wi=function(){var i,e;for(Gr&&(i=kn.domain)&&i.exit();e=Ai.get();)try{e()}catch(t){throw Ai.head&&Tt(),t}i&&i.enter()};!gm&&!Gr&&!Tm&&En&&$n?(Yr=!0,qr=$n.createTextNode(""),new En(wi).observe(qr,{characterData:!0}),Tt=function(){qr.data=Yr=!Yr}):!ym&&ki&&ki.resolve?(Pi=ki.resolve(void 0),Pi.constructor=ki,An=Tn(Pi.then,Pi),Tt=function(){An(wi)}):Gr?Tt=function(){kn.nextTick(wi)}:(Hr=Tn(Hr,dt),Tt=function(){Hr(wi)}),ks=function(i){Ai.head||Tt(),Ai.add(i)}}var Em=ks,$m=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},ta=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},km=le,Dt=km.Promise,rl=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",Pm=rl,Am=lr,wm=!Pm&&!Am&&typeof window=="object"&&typeof document=="object",_m=le,Xt=Dt,Rm=se,Im=Ro,Nm=qo,Cm=pe,Dm=wm,Om=rl,zr=mo,wn=Xt&&Xt.prototype,Lm=Cm("species"),Ps=!1,sl=Rm(_m.PromiseRejectionEvent),xm=Im("Promise",function(){var i=Nm(Xt),e=i!==String(Xt);if(!e&&zr===66||!(wn.catch&&wn.finally))return!0;if(!zr||zr<51||!/native code/.test(i)){var t=new Xt(function(n){n(1)}),r=function(n){n(function(){},function(){})},s=t.constructor={};if(s[Lm]=r,Ps=t.then(function(){})instanceof r,!Ps)return!0}return!e&&(Dm||Om)&&!sl}),li={CONSTRUCTOR:xm,REJECTION_EVENT:sl,SUBCLASSING:Ps},Ot={},_n=ft,Bm=TypeError,Mm=function(i){var e,t;this.promise=new i(function(r,s){if(e!==void 0||t!==void 0)throw Bm("Bad Promise constructor");e=r,t=s}),this.resolve=_n(e),this.reject=_n(t)};Ot.f=function(i){return new Mm(i)};var Vm=De,zi=lr,Je=le,ui=ke,Fm=Ws,Um=Js,jm=_p,Hm=ft,As=se,Gm=Ke,Ym=Np,qm=Ko,al=el.set,ia=Em,zm=$m,Wm=ta,Qm=il,nl=Eo,ws=Dt,ra=li,ol=Ot,ur="Promise",ll=ra.CONSTRUCTOR,Jm=ra.REJECTION_EVENT;ra.SUBCLASSING;var Wr=nl.getterFor(ur),Km=nl.set,Xm=ws&&ws.prototype,$t=ws,Qr=Xm,ul=Je.TypeError,_s=Je.document,sa=Je.process,Rs=ol.f,Zm=Rs,ev=!!(_s&&_s.createEvent&&Je.dispatchEvent),dl="unhandledrejection",tv="rejectionhandled",Rn=0,cl=1,iv=2,aa=1,hl=2,_i,In,rv,fl=function(i){var e;return Gm(i)&&As(e=i.then)?e:!1},pl=function(i,e){var t=e.value,r=e.state==cl,s=r?i.ok:i.fail,n=i.resolve,o=i.reject,l=i.domain,d,u,c;try{s?(r||(e.rejection===hl&&av(e),e.rejection=aa),s===!0?d=t:(l&&l.enter(),d=s(t),l&&(l.exit(),c=!0)),d===i.promise?o(ul("Promise-chain cycle")):(u=fl(d))?ui(u,d,n,o):n(d)):o(t)}catch(h){l&&!c&&l.exit(),o(h)}},ml=function(i,e){i.notified||(i.notified=!0,ia(function(){for(var t=i.reactions,r;r=t.get();)pl(r,i);i.notified=!1,e&&!i.rejection&&sv(i)}))},vl=function(i,e,t){var r,s;ev?(r=_s.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),Je.dispatchEvent(r)):r={promise:e,reason:t},!Jm&&(s=Je["on"+i])?s(r):i===dl&&zm("Unhandled promise rejection",t)},sv=function(i){ui(al,Je,function(){var e=i.facade,t=i.value,r=Nn(i),s;if(r&&(s=Wm(function(){zi?sa.emit("unhandledRejection",t,e):vl(dl,e,t)}),i.rejection=zi||Nn(i)?hl:aa,s.error))throw s.value})},Nn=function(i){return i.rejection!==aa&&!i.parent},av=function(i){ui(al,Je,function(){var e=i.facade;zi?sa.emit("rejectionHandled",e):vl(tv,e,i.value)})},kt=function(i,e,t){return function(r){i(e,r,t)}},At=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=iv,ml(i,!0))},Is=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw ul("Promise can't be resolved itself");var r=fl(e);r?ia(function(){var s={done:!1};try{ui(r,e,kt(Is,s,i),kt(At,s,i))}catch(n){At(s,n,i)}}):(i.value=e,i.state=cl,ml(i,!1))}catch(s){At({done:!1},s,i)}}};ll&&($t=function(e){Ym(this,Qr),Hm(e),ui(_i,this);var t=Wr(this);try{e(kt(Is,t),kt(At,t))}catch(r){At(t,r)}},Qr=$t.prototype,_i=function(e){Km(this,{type:ur,done:!1,notified:!1,parent:!1,reactions:new Qm,rejection:!1,state:Rn,value:void 0})},_i.prototype=Fm(Qr,"then",function(e,t){var r=Wr(this),s=Rs(qm(this,$t));return r.parent=!0,s.ok=As(e)?e:!0,s.fail=As(t)&&t,s.domain=zi?sa.domain:void 0,r.state==Rn?r.reactions.add(s):ia(function(){pl(s,r)}),s.promise}),In=function(){var i=new _i,e=Wr(i);this.promise=i,this.resolve=kt(Is,e),this.reject=kt(At,e)},ol.f=Rs=function(i){return i===$t||i===rv?new In(i):Zm(i)});Vm({global:!0,constructor:!0,wrap:!0,forced:ll},{Promise:$t});Um($t,ur,!1,!0);jm(ur);var nv=pe,Sl=nv("iterator"),bl=!1;try{var ov=0,Cn={next:function(){return{done:!!ov++}},return:function(){bl=!0}};Cn[Sl]=function(){return this},Array.from(Cn,function(){throw 2})}catch(i){}var lv=function(i,e){if(!e&&!bl)return!1;var t=!1;try{var r={};r[Sl]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch(s){}return t},uv=Dt,dv=lv,cv=li.CONSTRUCTOR,gl=cv||!dv(function(i){uv.all(i).then(void 0,function(){})}),hv=De,fv=ke,pv=ft,mv=Ot,vv=ta,Sv=Xs,bv=gl;hv({target:"Promise",stat:!0,forced:bv},{all:function(e){var t=this,r=mv.f(t),s=r.resolve,n=r.reject,o=vv(function(){var l=pv(t.resolve),d=[],u=0,c=1;Sv(e,function(h){var f=u++,p=!1;c++,fv(l,t,h).then(function(v){p||(p=!0,d[f]=v,--c||s(d))},n)}),--c||s(d)});return o.error&&n(o.value),r.promise}});var gv=De,yv=li.CONSTRUCTOR,Dn=Dt;Dn&&Dn.prototype;gv({target:"Promise",proto:!0,forced:yv,real:!0},{catch:function(i){return this.then(void 0,i)}});var Tv=De,Ev=ke,$v=ft,kv=Ot,Pv=ta,Av=Xs,wv=gl;Tv({target:"Promise",stat:!0,forced:wv},{race:function(e){var t=this,r=kv.f(t),s=r.reject,n=Pv(function(){var o=$v(t.resolve);Av(e,function(l){Ev(o,t,l).then(r.resolve,s)})});return n.error&&s(n.value),r.promise}});var _v=De,Rv=ke,Iv=Ot,Nv=li.CONSTRUCTOR;_v({target:"Promise",stat:!0,forced:Nv},{reject:function(e){var t=Iv.f(this);return Rv(t.reject,void 0,e),t.promise}});var Cv=Xe,Dv=Ke,Ov=Ot,yl=function(i,e){if(Cv(i),Dv(e)&&e.constructor===i)return e;var t=Ov.f(i),r=t.resolve;return r(e),t.promise},Lv=De,xv=ht,Bv=go,Mv=Dt,Vv=li.CONSTRUCTOR,Fv=yl,Uv=xv("Promise"),jv=!Vv;Lv({target:"Promise",stat:!0,forced:Bv},{resolve:function(e){return Fv(jv&&this===Uv?Mv:this,e)}});var Hv=De,Ns=Dt,Gv=ye,Yv=ht,qv=se,zv=Ko,On=yl,Wv=Ns&&Ns.prototype,Qv=!!Ns&&Gv(function(){Wv.finally.call({then:function(){}},function(){})});Hv({target:"Promise",proto:!0,real:!0,forced:Qv},{finally:function(i){var e=zv(this,Yv("Promise")),t=qv(i);return this.then(t?function(r){return On(e,i()).then(function(){return r})}:i,t?function(r){return On(e,i()).then(function(){throw r})}:i)}});var Jv=ht,Tl=Jv,Kv=Tl,Xv=Kv("Promise","finally"),Zv=Xv,eS=Zv,tS=eS,iS=tS,dr=iS,wt;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(wt||(wt={}));var _t=(i,e=0,t=wt.OFFSET_P)=>{switch(t){case wt.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case wt.PLAYBACK_SHIFT:{if(e===0)return i;const r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}default:a.assertNever(t)}return i},k=(i,e,t=!1)=>{const r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};exports.VideoQuality=void 0;(function(i){i.INVARIANT="Invariant quality",i.Q_144P="144p",i.Q_240P="240p",i.Q_360P="360p",i.Q_480P="480p",i.Q_720P="720p",i.Q_1080P="1080p",i.Q_1440P="1440p",i.Q_2160P="2160p",i.Q_4320P="4320p"})(exports.VideoQuality||(exports.VideoQuality={}));const $e={[exports.VideoQuality.Q_144P]:{width:256,height:144},[exports.VideoQuality.Q_240P]:{width:428,height:240},[exports.VideoQuality.Q_360P]:{width:640,height:360},[exports.VideoQuality.Q_480P]:{width:856,height:480},[exports.VideoQuality.Q_720P]:{width:1280,height:720},[exports.VideoQuality.Q_1080P]:{width:1920,height:1080},[exports.VideoQuality.Q_1440P]:{width:2560,height:1440},[exports.VideoQuality.Q_2160P]:{width:3840,height:2160},[exports.VideoQuality.Q_4320P]:{width:7680,height:4320}},Ui=(i,e)=>$e[i].height>$e[e].height,rS=(i,e)=>$e[i].height>=$e[e].height,Zt=(i,e)=>$e[i].height<$e[e].height,sS=(i,e)=>$e[i].height<=$e[e].height,aS=i=>i.sort((e,t)=>e===t?0:e===exports.VideoQuality.INVARIANT?1:t===exports.VideoQuality.INVARIANT?-1:Zt(e,t)?1:-1)[0],nS=Object.keys($e).sort((i,e)=>Zt(i,e)?-1:1),pt=({width:i,height:e})=>{const t=Math.min(i,e),r=Math.max(i,e);return nS.find(s=>{const n=$e[s];return n.width>=r&&n.height>=t})},oS=i=>$e[i].height,Wi=i=>i===exports.VideoQuality.INVARIANT;class Q{constructor(e){this.transitionStarted$=new a.Subject,this.transitionEnded$=new a.Subject,this.transitionUpdated$=new a.Subject,this.forceChanged$=new a.Subject,this.stateChangeStarted$=a.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=a.merge(this.transitionEnded$,this.forceChanged$),this.state=e}setState(e){const t=this.transition,r=this.state;this.transition=void 0,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,r=this.state;r===e||a.isNonNullable(t)&&t.to===e||(this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}const lS=i=>{switch(i){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return a.assertNever(i)}};var L;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(L||(L={}));const uS=5,dS=5,cS=500,Ln=7e3;class hS{constructor(e){this.subscription=new a.Subscription,this.loadMediaTimeoutSubscription=new a.Subscription,this.videoState=new Q(L.STOPPED),this.syncPlayback=()=>{const r=this.videoState.getState(),s=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${r}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){r!==L.STOPPED&&(this.videoState.startTransitionTo(L.STOPPED),this.stop());return}if(!s){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===C.Requested&&r!==L.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(r){case L.PLAYING:case L.PAUSED:case L.READY:break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:a.assertNever(r)}break}case exports.PlaybackState.PLAYING:{switch(r){case L.PLAYING:break;case L.PAUSED:this.videoState.startTransitionTo(L.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case L.READY:this.videoState.startTransitionTo(L.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:a.assertNever(r)}break}case exports.PlaybackState.PAUSED:{switch(r){case L.PLAYING:this.videoState.startTransitionTo(L.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case L.PAUSED:break;case L.READY:this.videoState.startTransitionTo(L.PAUSED),this.videoState.setState(L.PAUSED);break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:a.assertNever(r)}break}default:a.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(lS(e.format)),this.params.output.isAudioTracksExist$.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 a.Subscription;this.subscription.add(e),this.subscription.add(a.merge(this.videoState.stateChangeStarted$.pipe(a.map(s=>`stateChangeStarted$ ${JSON.stringify(s)}`)),this.videoState.stateChangeEnded$.pipe(a.map(s=>`stateChangeEnded$ ${JSON.stringify(s)}`))).subscribe(s=>this.log({message:`[videoState] ${s}`})));const t=(s,n)=>this.subscription.add(s.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const s=new a.Subject;e.add(s.pipe(a.debounce(cS)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(o=>{this.logRemoteEvent(o);const l=o.value;this.params.output.position$.next(l),(this.params.desiredState.seekState.getState().state===C.Applying||Math.abs(l-n)>uS)&&s.next(l),n=l})),e.add(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemotePause():this.handleRemotePlay()}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),s=>{this.logRemoteEvent(s);const{remotePlayer:n}=this.params.connection,o=s.value,l=this.params.output.isBuffering$.getValue(),d=o===chrome.cast.media.PlayerState.BUFFERING;switch(l!==d&&this.params.output.isBuffering$.next(d),o){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&n.duration-n.currentTime<dS&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:a.assertNever(o)}}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({volume:s.value})}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({muted:s.value})});const r=a.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(L.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(L.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:C.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===L.PAUSED||e===L.PLAYING)&&(this.videoState.setState(L.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===L.PLAYING||e===L.PAUSED)&&(this.videoState.setState(L.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===L.READY&&this.videoState.setState(L.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===exports.PlaybackState.READY&&k(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==L.STOPPED&&this.videoState.setState(L.STOPPED)}handleRemoteVolumeChange(e){var t,r;const s=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:s.volume,muted:(r=e.muted)!==null&&r!==void 0?r:s.muted};(n.volume!==s.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const r=this.params.source;let s,n,o;switch(e){case exports.VideoFormat.MPEG:{const c=r[e];a.assertNonNullable(c);const h=aS(Object.keys(c));a.assertNonNullable(h);const f=c[h];a.assertNonNullable(f),s=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=r[e];a.assertNonNullable(c),s=c.url,n="application/x-mpegurl",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:{const c=r[e];a.assertNonNullable(c),s=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS_LIVE:{const c=r[e];a.assertNonNullable(c),s=_t(c.url),n="application/x-mpegurl",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const c="Unsupported format for Chromecast",h=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:a.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:h}),h}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}const l=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:s,n);l.contentUrl=s,l.streamType=o,l.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:d,subtitle:u}=this.params.meta;return a.isNonNullable(d)&&(l.metadata.title=d),a.isNonNullable(u)&&(l.metadata.subtitle=u),l}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const r=this.params.desiredState.seekState.getState();return r.state===C.Applying||r.state===C.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),r=new Promise((s,n)=>{this.loadMediaTimeoutSubscription.add(a.timeout(Ln).subscribe(()=>n(`timeout(${Ln})`)))});dr(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===C.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},s=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${s}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:a.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:s})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}function J(i,e,t,r){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function l(c){try{u(r.next(c))}catch(h){o(h)}}function d(c){try{u(r.throw(c))}catch(h){o(h)}}function u(c){c.done?n(c.value):s(c.value).then(l,d)}u((r=r.apply(i,e||[])).next())})}function R(i){return this instanceof R?(this.v=i,this):new R(i)}function Ee(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(i,e||[]),s,n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(f){r[f]&&(s[f]=function(p){return new Promise(function(v,m){n.push([f,p,v,m])>1||l(f,p)})})}function l(f,p){try{d(r[f](p))}catch(v){h(n[0][3],v)}}function d(f){f.value instanceof R?Promise.resolve(f.value.v).then(u,c):h(n[0][2],f)}function u(f){l("next",f)}function c(f){l("throw",f)}function h(f,p){f(p),n.shift(),n.length&&l(n[0][0],n[0][1])}}class xn{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;const r=this.listeners[e];for(let s=0,n=r.length;s<n;s++)if(r[s].callback===t){r.splice(s,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const r=this.listeners[e.type].slice();for(let s=0,n=r.length;s<n;s++){const o=r[s];try{o.callback.call(this,e)}catch(l){Promise.resolve().then(()=>{throw l})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class El extends xn{constructor(){super(),this.listeners||xn.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}let $l=class{constructor(){Object.defineProperty(this,"signal",{value:new El,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(s){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(s){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&($l.prototype[Symbol.toStringTag]="AbortController",El.prototype[Symbol.toStringTag]="AbortSignal");function kl(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function fS(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=i;if(!kl({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||s)&&(n=function(u,c){let h;c&&c.signal&&(h=c.signal,delete c.signal);const f=new t(u,c);return h&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),f},n.prototype=t.prototype);const o=e;return{fetch:(d,u)=>{const c=n&&n.prototype.isPrototypeOf(d)?d.signal:u?u.signal:void 0;if(c){let h;try{h=new DOMException("Aborted","AbortError")}catch(p){h=new Error("Aborted"),h.name="AbortError"}if(c.aborted)return Promise.reject(h);const f=new Promise((p,v)=>{c.addEventListener("abort",()=>v(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,o(d,u)])}return o(d,u)},Request:n}}const cr=kl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Pl=cr?fS({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Rt=cr?Pl.fetch:window.fetch;cr?Pl.Request:window.Request;const lt=cr?$l:window.AbortController,zt=i=>i.range?i.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class ei{constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){var t;const{url:r}=e.request,s=(t=this.dashJsRequestQueue.get(r))!==null&&t!==void 0?t:[];s.push(e),this.dashJsRequestQueue.set(r,s)}executeNextRequests(){return J(this,void 0,void 0,function*(){for(const[e,t]of this.dashJsRequestQueue.entries()){const r=this.activeRequests.get(e);if(r){t.length&&this.onBigRequestProgress(r);const s=t[0];if(!s||!s.request.range)continue;const[n,o]=zt(s.request);if(n>=r.from&&o<=r.to)continue;this.activeRequests.delete(e)}if(t.length){const s=this.sendBigRequest(e,t.map(({request:n})=>n));this.activeRequests.set(e,s)}}})}abort(e){var t;if(e){const{request:r}=e,s=((t=this.dashJsRequestQueue.get(r.url))!==null&&t!==void 0?t:[]).includes(e),n=this.activeRequests.get(r.url);s&&n&&n.abortController.abort()}else for(const{abortController:r}of this.activeRequests.values())r.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const r=t.map(zt),s=r[0][0];let n=r[0][1];for(let f=1;f<r.length&&n<this.params.minDataSize;f++){const p=r[f][1];p-s<=2*this.params.minDataSize&&(n=Math.max(n,p))}s===0?n=Math.max(n,s+this.params.minInitSize):n=Math.max(n,s+this.params.minDataSize);const o=new URL(e,location.href);o.searchParams.append("bytes",`${s}-${n}`);const l=o.toString(),d=new lt,u=d.signal,c={url:e,from:s,to:n,loaded:0,data:null,abortController:d};u.addEventListener("abort",()=>this.onBigRequestAbort(c));const h=f=>{var p,v;throw(v=(p=this.params).onError)===null||v===void 0||v.call(p,{id:"BigRequestParsing",category:a.ErrorCategory.PARSER,message:"Error parsing response data",thrown:f}),f};return Rt(l,{signal:u}).then(f=>{var p,v,m;if(c.response=f,!f.ok||!f.body){this.onBigRequestError(c);return}const[S,b]=f.body.tee();(v=(p=this.params).onDownloadStream)===null||v===void 0||v.call(p,b);const g=S.getReader(),P=parseInt((m=f.headers.get("Content-Length"))!==null&&m!==void 0?m:"",10)||n-s+1;c.data=new ArrayBuffer(P);const E=new Uint8Array(c.data),T=({done:w,value:F})=>J(this,void 0,void 0,function*(){w?this.onBigRequestProgress(c):F&&(E.set(F,c.loaded),c.loaded+=F.byteLength,this.onBigRequestProgress(c),yield g==null?void 0:g.read().then(T,ei.suppressStreamErrors).catch(h))});g==null||g.read().then(T,ei.suppressStreamErrors).catch(h)},ei.suppressAbort).catch(f=>this.onBigRequestError(c,f)),c}onBigRequestProgress({url:e,from:t,to:r,loaded:s,data:n,response:o}){var l,d,u,c,h,f,p,v;if(!this.activeRequests.has(e)||!n)return;const m=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const S of m){const{request:b}=S,[g,P]=zt(b),E=g>=t&&P<=t+s,T=t>=g&&t+s<P,w=n.slice(g-t,Math.min(P-t+1,s));if((E||T)&&(b.requestStartDate=(d=b.requestStartDate)!==null&&d!==void 0?d:new Date,b.firstByteDate=(u=b.firstByteDate)!==null&&u!==void 0?u:new Date,b.bytesLoaded=w.byteLength,b.bytesTotal=r-t),E){b.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((c=this.dashJsRequestQueue.get(e))!==null&&c!==void 0?c:[]).filter(O=>O!==S)),(h=S.success)===null||h===void 0||h.call(S,w,"",e);const F=o?Array.from(o.headers.entries()).map(([O,I])=>`${O}: ${I}`).join(`\r
7
+ `):"";(f=this.dashMetrics)===null||f===void 0||f.addHttpRequest(b,e,(p=o==null?void 0:o.status)!==null&&p!==void 0?p:200,F,[])}else T&&((v=S.progress)===null||v===void 0||v.call(S,{loaded:s,total:r-t,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:t,to:r},s){var n,o,l,d;if((o=(n=this.params).onError)===null||o===void 0||o.call(n,{id:"BigRequest",category:a.ErrorCategory.NETWORK,message:"Download error",thrown:s}),!this.activeRequests.has(e))return;const u=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const c of u){const[h,f]=zt(c.request);(h>=t&&h<r||f>t&&f<=r)&&((d=c==null?void 0:c.error)===null||d===void 0||d.call(c,c.request,String(s)))}if(this.activeRequests.delete(e),s)throw s}onBigRequestAbort({url:e,from:t,to:r}){var s,n;if(!this.activeRequests.has(e))return;const o=(s=this.dashJsRequestQueue.get(e))!==null&&s!==void 0?s:[];for(const l of o){const[d,u]=zt(l.request);(d>=t&&d<r||u>t&&u<=r)&&((n=l==null?void 0:l.abort)===null||n===void 0||n.call(l,l.request))}this.activeRequests.delete(e)}static suppressAbort(e){if(!(e instanceof DOMException)||!(e.name==="AbortError"||e.code===20))throw e}static suppressStreamErrors(){}}class Qi{constructor(e,t,r){this.baseLoader=e,this.config=r,this.bigRequest=t,t.setMetrics(r.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(Qi.shouldDelegateToBase(t))return this.baseLoader.load(e);this.bigRequest.queueDashJSRequest(e),this.bigRequest.executeNextRequests()}abort(e){if(!e){this.baseLoader.abort(),this.bigRequest.abort();return}const{request:t}=e;Qi.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const pS=(i,e)=>t=>({create:r=>{const s=i(t).create(r);return new Qi(s,e,r)}}),mS=(i,e)=>{const t=new ei(e);return i.extend("SchemeLoaderFactory",function(){const{parent:r}=this,s=r.getLoader;return{getLoader:n=>{const o=s(n);return pS(o,t)}}},!0),()=>t.destroy()};var vS=i=>{let e,t=!1,r=!1;i.on("playbackTimeUpdated",({timeToEnd:s})=>{r=s<=3,t&&r&&(e==null||e())}),i.extend("MediaSourceController",function(){const{parent:s}=this,n=s.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&r&&(e==null||e())}}},!0)},SS=i=>{const e=new a.ValueSubject(1/0),t=new a.Subject,r=new a.ValueSubject(void 0),s=new a.ValueSubject(void 0);let n=NaN,o=!1;const l=()=>{n=Date.now(),o=!1},d=c=>{var h,f,p,v,m;const S=oi(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(P=>P.split(": ")));if("x-playback-duration"in S||"x-playback-duration-millis"in S){const P=parseInt((h=c.getResponseHeader("X-Playback-Duration"))!==null&&h!==void 0?h:"",10),E=parseInt((f=c.getResponseHeader("X-Playback-Duration-Millis"))!==null&&f!==void 0?f:"",10),T=(p=E!=null?E:P*1e3)!==null&&p!==void 0?p:NaN;a.isNonNullable(T)&&!isNaN(T)&&e.next(T)}const b=(v=S["x-delivery-type"])!==null&&v!==void 0?v:exports.HttpConnectionType.HTTP1,g=(m={1:!0,0:!1}[S["x-reused"]])!==null&&m!==void 0?m:void 0;r.next(b),s.next(g)},u=c=>{c.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return i.extend("XHRLoader",function(){const{parent:c}=this,h=c.load.bind(c);return{load:function(f){if(f.request.type==="MPD"){const p=f.onload,v=f.progress;f.onload=function(...m){return d(this),p(...m)},f.progress=function(...m){return u(this),v(...m)},l()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:s,connectionType$:r}},It=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},bS=i=>i.extend("RequestModifier",()=>({modifyRequestURL:It}),!0),gS=i=>{i.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:r=>{if(r.request&&r.request.range){const[s,n]=r.request.range.split("-").map(l=>parseInt(l,10)),o=new URL(r.request.url,location.href);o.searchParams.append("bytes",`${s}-${n}`),r.request.url=o.toString(),r.request.range=void 0}t(r)}}},!0)};const Ne=(i,e,t,{equal:r=(o,l)=>o===l,changed$:s,onError:n}={})=>{const o=i.getState(),l=e(),d=a.isNullable(s),u=new a.Subscription;return s&&u.add(s.subscribe(c=>{const h=i.getState();r(c,h)&&i.setState(c)},n)),r(l,o)||(t(o),d&&i.setState(o)),u.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),d&&i.setState(c.to)},n)),u},mt=(i,e,t)=>Ne(e,()=>i.loop,r=>{a.isNonNullable(r)&&(i.loop=r)},{onError:t}),He=(i,e,t,r)=>Ne(e,()=>({muted:i.muted,volume:i.volume}),s=>{a.isNonNullable(s)&&(i.muted=s.muted,i.volume=s.volume)},{equal:(s,n)=>s===n||(s==null?void 0:s.muted)===(n==null?void 0:n.muted)&&(s==null?void 0:s.volume)===(n==null?void 0:n.volume),changed$:t,onError:r}),Ze=(i,e,t,r)=>Ne(e,()=>i.playbackRate,s=>{a.isNonNullable(s)&&(i.playbackRate=s)},{changed$:t,onError:r}),yS=i=>["__",i.language,i.label].join("|"),TS=(i,e)=>{if(i.id===e)return!0;const[t,r,s]=e.split("|");return i.language===r&&i.label===s};class Oe{constructor(){this.available$=new a.Subject,this.current$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.subscription=new a.Subscription,this.externalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const s=n=>{this.error$.next({id:"TextTracksManager",category:a.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Ne(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{a.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>a.isNonNullable(n)&&a.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},d)=>l===o[d].id),changed$:this.available$.pipe(a.map(n=>n.filter(({type:o})=>o==="external"))),onError:s})),this.subscription.add(Ne(t.currentTextTrack,()=>{if(this.video)return;const n=this.htmlTextTracksAsArray().find(({mode:o})=>o==="showing");return n&&this.htmlTextTrackToITextTrack(n).id},n=>this.select(n),{changed$:this.current$,onError:s})),this.subscription.add(Ne(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){a.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(a.fromEvent(e,"addtrack").subscribe(()=>{const r=this.current$.getValue();this.select(r)})),this.subscription.add(a.merge(a.fromEvent(e,"addtrack"),a.fromEvent(e,"removetrack"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),a.filterChanged((r,s)=>r.length===s.length&&r.every(({id:n},o)=>n===s[o].id))).subscribe(this.available$)),this.subscription.add(a.merge(a.fromEvent(e,"change"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),a.map(r=>r&&this.htmlTextTrackToITextTrack(r).id),a.filterChanged()).subscribe(this.current$));const t=r=>{var s,n;return this.applyCueSettings((n=(s=r.target)===null||s===void 0?void 0:s.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(a.fromEvent(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)===null||s===void 0||s.addEventListener("cuechange",t);const o=l=>{var d,u,c,h,f;const p=(u=(d=l.target)===null||d===void 0?void 0:d.cues)!==null&&u!==void 0?u:null;p&&p.length&&(this.applyCueSettings((h=(c=l.target)===null||c===void 0?void 0:c.cues)!==null&&h!==void 0?h:null),(f=l.target)===null||f===void 0||f.removeEventListener("cuechange",o))};(n=r.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(a.fromEvent(e,"removetrack").subscribe(r=>{var s;(s=r.track)===null||s===void 0||s.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const r of Array.from(e)){const s=r;a.isNonNullable(t.align)&&(s.align=t.align),a.isNonNullable(t.position)&&(s.position=t.position),a.isNonNullable(t.size)&&(s.size=t.size),a.isNonNullable(t.line)&&(s.line=t.line)}}htmlTextTracksAsArray(e=!1){a.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Oe.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:r}=e,s=e.id!==""?e.id:yS(e);return this.externalTracks.has(s)?{id:s,type:"external",language:t,label:r,url:this.externalTracks.get(s).url}:{id:s,type:"internal",language:t,label:r}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.id===""&&e.label===""&&e.language==="")}setExternal(e){e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks.keys()).filter(t=>!e.find(r=>r.id===t)).forEach(t=>this.detach(t))}select(e){a.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))a.isNonNullable(e)&&TS(t,e)?t.mode="showing":t.mode="disabled"}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){a.assertNonNullable(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),this.externalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){a.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e);t&&this.video.removeChild(t),this.externalTracks.delete(e)}}var Ge=i=>{const e=document.createElement("video");return e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i.appendChild(e),e};class na{constructor(){this.pausedTime=0,this.streamOffset=0,this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0}}var Al=()=>{const{userAgent:i}=window.navigator;return!/chrome/i.test(i)&&/webkit|safari|khtml/i.test(i)};const Cs=3;class ES{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,r=this._source.buffered.length;t<r;t++){let s=this._source.buffered.start(t);const n=this._source.buffered.end(t);s>e&&s-e<Cs&&(s=e),this._buffer.push({from:s,to:n,i:t})}return this._buffer.sort(function(t,r){return t.from-r.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const r=this.getNext(e);if(r&&r.from-e.to<(t||Cs))return r}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,r){this._buffer.forEach(({from:s,to:n})=>{const o=s>=e&&s<t,l=n>=e&&n<t;o&&l||(o?r(t,n):l?r(s,e):s<e&&n>t?(r(t,n),r(s,e)):r(s,n))})}destroy(){this._buffer=[]}}var wl=(i,e,t=Cs)=>{let r=0,s=0;for(let n=0;n<i.length;n++){const o=i.start(n),l=i.end(n);if(o<=e&&e<=l){if(r=o,s=l,!t)return{from:r,to:s};for(let d=n-1;d>=0;d--)i.end(d)+t>=r&&(r=i.start(d));for(let d=n+1;d<i.length;d++)i.start(d)-t<=s&&(s=i.end(d))}}return{from:r,to:s}};const Ye=i=>{const e=p=>a.fromEvent(i,p).pipe(a.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],r=a.merge(...t.map(p=>a.fromEvent(i,p))).pipe(a.map(p=>p.type==="ended"?i.readyState<2:i.readyState<3),a.filterChanged()),s=a.merge(a.fromEvent(i,"progress"),a.fromEvent(i,"timeupdate")).pipe(a.map(()=>wl(i.buffered,i.currentTime))),n=Al()?a.combine({play:e("play").pipe(a.once()),playing:e("playing")}).pipe(a.mapTo(void 0)):e("playing"),o=a.fromEvent(i,"volumechange").pipe(a.map(()=>({muted:i.muted,volume:i.volume}))),l=a.fromEvent(i,"ratechange").pipe(a.map(()=>i.playbackRate)),d=a.fromEvent(i,"error").pipe(a.filter(()=>Boolean(i.error||i.played.length)),a.map(()=>{var p;const v=i.error;return{id:v?`MediaError#${v.code}`:"HtmlVideoError",category:a.ErrorCategory.VIDEO_PIPELINE,message:v?v.message:"Error event from HTML video element",thrown:(p=i.error)!==null&&p!==void 0?p:void 0}})),u=a.fromEvent(i,"timeupdate").pipe(a.map(()=>i.currentTime)),c=new a.Subject,h=.3;let f;return u.subscribe(p=>{i.loop&&a.isNonNullable(f)&&a.isNonNullable(p)&&f>=i.duration-h&&p<=h&&c.next(f),f=p}),{playing$:n,pause$:e("pause").pipe(a.filter(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:u,durationChange$:a.fromEvent(i,"durationchange").pipe(a.map(()=>i.duration)),isBuffering$:r,currentBuffer$:s,volumeState$:o,playbackRateState$:l}},oa=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var $S=De,kS=Fs,PS=zs,AS=qs;$S({target:"Array",proto:!0},{at:function(e){var t=kS(this),r=PS(t),s=AS(e),n=s>=0?s:r+s;return n<0||n>=r?void 0:t[n]}});var wS=Tl,_S=wS("Array","at"),RS=_S,IS=RS,NS=IS,CS=NS,xe=CS;let la=!1,Be={};const DS=i=>{la=i},OS=()=>{Be={}},LS=i=>{i(Be)},Ri=(i,e)=>{var t;la&&(Be.meta=(t=Be.meta)!==null&&t!==void 0?t:{},Be.meta[i]=e)};class Ie{constructor(e){this.name=e}next(e){var t,r;if(!la)return;Be.series=(t=Be.series)!==null&&t!==void 0?t:{};const s=(r=Be.series[this.name])!==null&&r!==void 0?r:[];s.push([Date.now(),e]),Be.series[this.name]=s}}const xS=new Ie("best_bitrate"),BS=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class MS{constructor(){this.history={}}recordSelection(e){this.history[e.id]=a.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const di=(i,{container:e,throughput:t,tuning:r,limits:s,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:d,history:u})=>{var c,h,f,p;const v=r.usePixelRatio&&(c=window.devicePixelRatio)!==null&&c!==void 0?c:1,m=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*v*r.containerSizeFactor,height:e.height*v*r.containerSizeFactor},S=m&&pt(m),b=r.considerPlaybackRate&&a.isNonNullable(l)?l:1,g=i.filter(N=>!Wi(N.quality)).sort((N,_)=>Ui(N.quality,_.quality)?-1:1),P=(h=xe(g,-1))===null||h===void 0?void 0:h.quality,E=(f=xe(g,0))===null||f===void 0?void 0:f.quality,T=a.isNullable(s)||a.isNonNullable(s.min)&&a.isNonNullable(s.max)&&Zt(s.max,s.min)||a.isNonNullable(s.min)&&E&&Ui(s.min,E)||a.isNonNullable(s.max)&&P&&Zt(s.max,P),w=b*BS(o!=null?o:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),O=g.filter(N=>{const _=S?Zt(N.quality,S):!0,G=a.isNonNullable(t)&&isFinite(t)&&a.isNonNullable(N.bitrate)?t-n>=N.bitrate*w:!0,K=r.lazyQualitySwitch&&a.isNonNullable(r.minBufferToSwitchUp)&&d&&!Wi(d.quality)&&(o!=null?o:0)<r.minBufferToSwitchUp&&Ui(N.quality,d.quality),te=T||(a.isNullable(s.max)||sS(N.quality,s.max))&&(a.isNullable(s.min)||rS(N.quality,s.min));return _&&G&&!K&&te})[0];O&&O.bitrate&&xS.next(O.bitrate);const I=(p=O!=null?O:g[Math.ceil((g.length-1)/2)])!==null&&p!==void 0?p:i[0],U=I&&u&&u.history[I.id]&&a.now()-u.history[I.id]<=r.trackCooldown&&(!u.last||I.id!==u.last.id);if(I!=null&&I.id&&u&&!U&&u.recordSelection(I),U&&(u!=null&&u.last)){const N=u.last;return u==null||u.recordSwitch(N),N}return u==null||u.recordSwitch(I),I};var de=i=>new URL(i).hostname;const VS=300,Ji=(i,e=VS)=>new a.Observable(t=>{const{width:r,height:s}=i.getBoundingClientRect();if(t.next({width:r,height:s}),!window.ResizeObserver)return;const n=new ResizeObserver(cu(o=>{const l=o[0];if(!l)return;let d,u;l.contentBoxSize&&l.contentBoxSize[0]?(u=l.contentBoxSize[0].blockSize,d=l.contentBoxSize[0].inlineSize):l.contentRect&&(d=l.contentRect.width,u=l.contentRect.height),a.isNonNullable(d)&&a.isNonNullable(u)&&t.next({width:d,height:u})},e));return n.observe(i),()=>n.disconnect()}),FS=5e3,Wt={};var x;(function(i){i.DOWNLOADING_LIB="downloading_lib",i.STOPPED="stopped",i.STREAM_INITIALIZED="stream_initialized",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(x||(x={}));const re=(i,e)=>new a.Observable(t=>{const r=s=>t.next(s);return i.on(e,r),()=>i.off(e,r)});class US{constructor(e){this.subscription=new a.Subscription,this.videoState=new Q(x.DOWNLOADING_LIB),this.textTracksManager=new Oe,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new a.ValueSubject(void 0),this.maxSeekBackTime$=new a.ValueSubject(1/0),this.availableFrom$=new a.ValueSubject(void 0),this.elementSize$=new a.ValueSubject(void 0),this.liveOffset=new na,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState(),o=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===x.DOWNLOADING_LIB||t===x.STREAM_INITIALIZED))switch((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===C.Requested&&t!==x.STOPPED&&r!==exports.PlaybackState.STOPPED&&(o?this.seek(n.position-this.liveOffset.getTotalPausedTime()):this.seek(n.position)),r){case exports.PlaybackState.STOPPED:{switch(t){case x.STOPPED:break;case x.PLAYING:case x.PAUSED:case x.READY:this.stop();break;default:a.assertNever(t)}break}case exports.PlaybackState.READY:{switch(t){case x.STOPPED:this.prepare();break;case x.PLAYING:case x.PAUSED:case x.READY:break;default:a.assertNever(t)}break}case exports.PlaybackState.PLAYING:{switch(t){case x.PLAYING:break;case x.PAUSED:o&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case x.READY:this.play();break;case x.STOPPED:this.prepare();break;default:a.assertNever(t)}break}case exports.PlaybackState.PAUSED:{switch(t){case x.PLAYING:this.pause(),this.liveOffset.pause();break;case x.PAUSED:break;case x.READY:this.videoState.setState(x.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case x.STOPPED:this.prepare();break;default:a.assertNever(t)}break}default:a.assertNever(r)}},this.video=Ge(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioTracksExist$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=s=>{var n;e||this.params.output.error$.next({id:s==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:a.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${(n=s==null?void 0:s.toString)===null||n===void 0?void 0:n.call(s)}`,thrown:s}),e=!0},r=window.setTimeout(()=>t("timeout"),FS);dr(import("dashjs/dist/dash.mediaplayer.min.js").then(s=>{e||(Wt.MediaPlayer=s.MediaPlayer,Wt.Debug=s.Debug,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){a.assertNonNullable(Wt.MediaPlayer,"dashjs not loaded"),a.assertNonNullable(Wt.Debug,"dashjs not loaded"),this.player=Wt.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter(t=>(t.height&&(this.frameRatesByFrameHeight[t.height]=t.frameRate?oa(t.frameRate+""):void 0),!0)),(this.params.format===exports.VideoFormat.DASH_WEBM||this.params.format===exports.VideoFormat.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=mS(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&&gS(this.player),vS(this.player),this.params.tuning.requestQuick&&bS(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(x.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,r=m=>{e.error$.next({id:"DashIFProvider",category:a.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:m})},s=(m,S)=>this.subscription.add(m.subscribe(S,r));s(Ji(this.video),this.elementSize$),s(re(this.player,"error").pipe(a.map(m=>{const S=typeof m.error=="object"?m.error.code:m.error,b=typeof m.error=="object"?m.error.message:void 0;return{id:`DashJS#${S}`,message:b}})),e.error$),s(re(this.player,"playbackError").pipe(a.map(m=>({id:"DashJSPlayback",message:m.error}))),e.error$);const n=re(this.player,"qualityChangeRendered").pipe(a.filter(({mediaType:m})=>m==="video"),a.map(({newQuality:m})=>{var S;return(S=this.videoTracks.find(({bitrateInfo:b})=>b.qualityIndex===m))===null||S===void 0?void 0:S.track}));n.pipe(a.filter(a.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(a.filter(({to:m})=>m===x.STREAM_INITIALIZED),a.once()).subscribe(()=>{this.subscription.add(Ne(t.videoTrack,()=>{var m,S;const b=this.player.getQualityFor("video");return(S=(m=this.videoTracks.find(({bitrateInfo:g})=>g.qualityIndex===b))===null||m===void 0?void 0:m.track)===null||S===void 0?void 0:S.id},m=>{var S;if(a.isNullable(m))return;const b=(S=this.videoTracks.find(({track:g})=>g.id===m))===null||S===void 0?void 0:S.bitrateInfo;b&&this.player.setQualityFor("video",b.qualityIndex)},{changed$:n.pipe(a.map(m=>m==null?void 0:m.id)),onError:r}))},r)),this.subscription.add(Ne(t.autoVideoTrackSwitching,()=>{var m,S,b;return(b=(S=(m=this.player.getSettings().streaming)===null||m===void 0?void 0:m.abr)===null||S===void 0?void 0:S.autoSwitchBitrate)===null||b===void 0?void 0:b.video},m=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:m}}}}),{onError:r})),s(re(this.player,"bufferStateChanged").pipe(a.filter(({mediaType:m})=>m==="video"),a.map(({state:m})=>m==="bufferStalled")),e.isBuffering$),s(re(this.player,"fragmentLoadingStarted"),({mediaType:m,request:{url:S}})=>{var b,g;const P=this.player.getDashMetrics(),E=P.getLatestFragmentRequestHeaderValueByID(m,"X-Reused"),T=(b=P.getLatestFragmentRequestHeaderValueByID(m,"X-Delivery-Type"))!==null&&b!==void 0?b:exports.HttpConnectionType.HTTP1,w=(g={1:!0,0:!1}[E])!==null&&g!==void 0?g:void 0;this.params.output.httpConnectionType$.next(T),this.params.output.httpConnectionReused$.next(w),e.hostname$.next(de(S))}),s(re(this.player,"streamInitialized"),({streamInfo:{duration:m,manifestInfo:{isDynamic:S,availableFrom:b}}})=>{this.isLive$.next(S),this.availableFrom$.next(b.getTime()),S||e.duration$.next(m),this.videoTracks=[];const g=this.player.getQualityFor("video");let P;for(const E of this.player.getBitrateInfoListFor("video")){const T=E.qualityIndex.toString(10),w=pt(E),F=E.bitrate/1e3,O={width:E.width,height:E.height},I=this.frameRatesByFrameHeight[E.height];if(w){const U={id:T,quality:w,bitrate:F,size:O,fps:I};this.videoTracks.push({track:U,bitrateInfo:E}),E.qualityIndex===g&&(P=U)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:E})=>E)),P&&e.currentVideoTrack$.next(P),this.videoState.setState(x.STREAM_INITIALIZED),this.videoState.startTransitionTo(x.READY)}),s(re(this.player,"fragmentLoadingCompleted"),({request:m})=>{if(!m.requestEndDate||!m.firstByteDate||!m.bytesLoaded)return;const S=m.requestEndDate.getTime()-m.firstByteDate.getTime(),b=m.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(b,S)}),s(a.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const m=this.params.dependencies.throughputEstimator.throughput$.getValue(),S=di(this.videoTracks.map(({track:g})=>g),{container:this.elementSize$.getValue(),throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),b=this.videoTracks.find(({track:g})=>g===S);b!=null&&b.bitrateInfo&&this.player.setQualityFor("video",b==null?void 0:b.bitrateInfo.qualityIndex,!1)}),s(a.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(a.filter(a.isNonNullable))}).pipe(a.filter(({isLive:m})=>m),a.map(({maxSeekBackTime:m})=>-m/1e3)),this.params.output.duration$);const o=re(this.player,"playbackTimeUpdated").pipe(a.map(({time:m})=>m!=null?m:0));s(a.combine({availableFrom:this.availableFrom$.pipe(a.filter(a.isNonNullable)),currentTime:o}),({availableFrom:m,currentTime:S})=>this.params.output.liveTime$.next(m+S*1e3)),s(o.pipe(a.filter(()=>this.isLive$.getValue()===!1)),e.position$),s(re(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),s(re(this.player,"playbackEnded"),e.endedEvent$),s(re(this.player,"playbackProgress").pipe(a.map(()=>wl(this.video.buffered,this.video.currentTime))),e.currentBuffer$),s(re(this.player,"playbackPlaying"),()=>{this.videoState.setState(x.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)}),s(re(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(x.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),s(re(this.player,"playbackPaused"),()=>{this.videoState.setState(x.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)}),s(re(this.player,"canPlay"),()=>{var m;((m=this.videoState.getTransition())===null||m===void 0?void 0:m.to)===x.READY&&this.videoState.setState(x.READY)}),s(this.isLive$,e.isLive$),s(Ji(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const l=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));s(l,this.syncPlayback);const{playbackDuration$:d,ping$:u,connectionType$:c,connectionReused$:h}=SS(this.player);s(c,this.params.output.httpConnectionType$),s(h,this.params.output.httpConnectionReused$),s(d,this.maxSeekBackTime$),s(u.pipe(a.once()),e.firstBytesEvent$),s(re(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&s(a.combine({isLive:this.isLive$,isShort:e.duration$.pipe(a.map(m=>m<60))}),({isLive:m,isShort:S})=>{const b=!m&&S;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:b}}})}),s(o.pipe(a.filter(m=>m>this.params.tuning.insufficientBufferRuleMargin),a.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(re(this.player,"manifestLoaded").pipe(a.once()).subscribe(()=>{this.subscription.add(re(this.player,"playbackPlaying").pipe(a.once(),a.mapTo(void 0)).subscribe(e.firstFrameEvent$,r))},r)),this.subscription.add(mt(this.video,t.isLooped,r));const{volumeState$:f,looped$:p,playbackRateState$:v}=Ye(this.video);this.subscription.add(He(this.video,t.volume,f,r)),this.subscription.add(f.subscribe(e.volume$,r)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(Ze(this.video,t.playbackRate,v,r))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(x.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(x.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3);const s=_t(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,wt.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(x.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(x.PAUSED),this.video.pause()}destroy(){var e,t;this.subscription.unsubscribe(),this.textTracksManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(r){}this.video.remove(),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var ci=i=>{switch(i){case"mobile":return exports.VideoQuality.Q_144P;case"lowest":return exports.VideoQuality.Q_240P;case"low":return exports.VideoQuality.Q_360P;case"sd":case"medium":return exports.VideoQuality.Q_480P;case"hd":case"high":return exports.VideoQuality.Q_720P;case"fullhd":case"full":return exports.VideoQuality.Q_1080P;case"quadhd":case"quad":return exports.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return exports.VideoQuality.Q_2160P}},et=i=>J(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(t instanceof DOMException&&(t.code===20||t.name==="AbortError"))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(r){return i.muted=!1,console.warn(r),!1}}return!0});function oe(){return a.now()}function _l(i){return oe()-i}function Bn(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,s=o=>r.test(o);return{resolve:(o,l,d=!1)=>{s(o)||(o.startsWith("/")||(o="/"+o),o=t+o);let u=o.indexOf("?")>-1?"&":"?";return d&&(o+=u+"lowLat=1",u="&"),l&&(o+=u+"_rnd="+Math.floor(999999999*Math.random())),o}}}function jS(i,e,t){const r=(...s)=>{t.apply(null,s),i.removeEventListener(e,r)};i.addEventListener(e,r)}function ji(i,e,t,r){const s=window.XMLHttpRequest;let n,o,l,d=!1,u=0,c,h,f=!1,p="arraybuffer",v=7e3,m=2e3,S=()=>{if(d)return;a.assertNonNullable(c);const _=_l(c);let G;if(_<m){G=m-_,setTimeout(S,G);return}m*=2,m>v&&(m=v),o&&o.abort(),o=new s,w()};const b=_=>(n=_,N),g=_=>(h=_,N),P=()=>(p="json",N),E=()=>{if(!d){if(--u>=0){S(),r&&r();return}d=!0,h&&h(),t&&t()}},T=_=>(f=_,N),w=()=>{c=oe(),o=new s,o.open("get",i);let _=0,G,K=0;const te=()=>(a.assertNonNullable(c),Math.max(c,Math.max(G||0,K||0)));if(n&&o.addEventListener("progress",$=>{const D=oe();n.updateChunk&&$.loaded>_&&(n.updateChunk(te(),$.loaded-_),_=$.loaded,G=D)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>E())),o.addEventListener("load",()=>{if(d)return;a.assertNonNullable(o);const $=o.status;if($>=200&&$<300){if(o.response.byteLength&&n){const D=o.response.byteLength-_;D&&n.updateChunk&&n.updateChunk(te(),D)}h&&h(),o&&e(o.response)}else E()}),o.addEventListener("error",()=>{E()}),f){const $=()=>{a.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(K=oe(),o.removeEventListener("readystatechange",$))};o.addEventListener("readystatechange",$)}return o.responseType=p,o.send(),N},N={withBitrateReporting:b,withParallel:T,withJSONResponse:P,withRetryCount:_=>(u=_,N),withRetryInterval:(_,G)=>(a.isNonNullable(_)&&(m=_),a.isNonNullable(G)&&(v=G),N),withTimeout:_=>(l=_,N),withFinally:g,send:w,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return N}const HS=100,GS=2e3,YS=500;let qS=class{constructor(e){this.intervals=[],this.currentRate=0,this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-YS;if(t-e>GS){let r=0,s=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)r+=n.end-n.start,s+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,l=n.end-n.start;r+=o;const d=n.bytes*o/l;s+=d,n.start=t,n.bytes-=d}}}if(s>0&&r>0){const n=s*8/(r/1e3);return this._updateRate(n),this.logger(`rate updated, new=${Math.round(n/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(s)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>HS&&(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 zS{constructor(e,t,r,s,n){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=s,this.logger=n}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const r=oe(),s=d=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=d,e._errorCB?e._errorCB(d):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=d=>{e._complete=1,e._responseData=d,e._downloadTime=oe()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(d,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},o=()=>{e._finallyCB&&e._finallyCB()},l=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=ji(t,n,()=>s("error"),l),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(o),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=oe()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=oe();if(Object.keys(this.activeRequests).length>=e)return!1;const r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,s){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=r,o._retryCB=s,o._finallyCB=n._finallyCB,o._error||o._complete?(this._removeFromActive(e),setTimeout(()=>{o._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(o._responseData,o._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(o._errorMsg)),n._finallyCB&&n._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const l=this.pendingQueue.indexOf(e);l!==-1&&this.pendingQueue.splice(l,1),this.logger(`Request not prefetched, starting new request, url=${e}${l===-1?"":"; removed pending"}`),this._sendRequest(n,e)}},n._cb=t,n._errorCB=r,n._retryCB=s,n.abort=function(){n.request&&n.request.abort()},n.withFinally=o=>(n._finallyCB=o,n),n}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Ii=1e4,Ni=3,WS=300,QS=2e3,JS=6e4,KS=10,XS=1,ZS=500;class eb{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 qS(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Bn(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Bn(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r;Boolean(e.error)&&!this.destroyed&&(t(`Video element error: ${(r=e.error)===null||r===void 0?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,r=t.buffered.length;let s;r!==0&&(s=t.buffered.start(r-1),t.currentTime<s&&(e("Fixup stall"),t.currentTime=s))}_selectQuality(e){const{videoElement:t}=this.params;let r,s,n;const o=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let l=0;l<this.manifest.length;++l)n=this.manifest[l],!(this.maxAutoQuality&&n.video.height>this.maxAutoQuality)&&(n.bitrate<e&&o>Math.min(n.video.height,n.video.width)?(!s||n.bitrate>s.bitrate)&&(s=n):(!r||r.bitrate>n.bitrate)&&(r=n));return s||r}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||a.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:r,videoElement:s,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,s.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{jS(s,"progress",()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),n({name:"playing"})):o()})};o()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new zS(Ni,Ii,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:r,playerCallback:s}=this.params;let n=!1,o=null,l=null,d=null,u=null,c=!1;const h=()=>{const E=n&&(!c||c===this.rep);return E||t("Not running!"),E},f=(E,T,w)=>{d&&d.abort(),d=ji(this.urlResolver.resolve(E,!1),T,w,()=>this._retryCallback()).withTimeout(Ii).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ni).withFinally(()=>{d=null}).send()},p=(E,T,w)=>{a.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),T,w,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},v=E=>{const T=r.playbackRate;r.playbackRate!==E&&(t(`Playback rate switch: ${T}=>${E}`),r.playbackRate=E)},m=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)v(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){v(1);return}const w=oe()-1e4;let F=0;for(let I=0;I<this.bufferStates.length;I++){const U=this.bufferStates[I];E=Math.min(E,U.buf),U.ts<w&&F++}this.bufferStates.splice(0,F),t(`update playback rate; minBuffer=${E} drop=${F} jitter=${this.sourceJitter}`);let O=E-XS;this.sourceJitter>=0?O-=this.sourceJitter/2:this.sourceJitter-=1,O>3?v(1.15):O>1?v(1.1):O>.3?v(1.05):v(1)}},b=E=>{let T;const w=()=>T&&T.start?T.start.length:0,F=$=>T.start[$]/1e3,O=$=>T.dur[$]/1e3,I=$=>T.fragIndex+$,U=($,D)=>({chunkIdx:I($),startTS:F($),dur:O($),discontinuity:D}),N=()=>{let $=0;if(T&&T.dur){let D=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,z=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ee=D;this.sourceJitter>1&&(ee+=this.sourceJitter-1);let ie=T.dur.length-1;for(;ie>=0&&(ee-=T.dur[ie],!(ee<=0));--ie);$=Math.min(ie,T.dur.length-1-z),$=Math.max($,0)}return U($,!0)},_=$=>{const D=w();if(!(D<=0)){if(a.isNonNullable($)){for(let z=0;z<D;z++)if(F(z)>$)return U(z)}return N()}},G=$=>{const D=w(),z=$?$.chunkIdx+1:0,ee=z-T.fragIndex;if(!(D<=0)){if(!$||ee<0||ee-D>KS)return t(`Resync: offset=${ee} bChunks=${D} chunk=`+JSON.stringify($)),N();if(!(ee>=D))return U(z-T.fragIndex,!1)}},K=($,D,z)=>{u&&u.abort(),u=ji(this.urlResolver.resolve($,!0,this.lowLatency),D,z,()=>this._retryCallback()).withTimeout(Ii).withRetryCount(Ni).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:($,D)=>{K(E,z=>{if(!h())return;T=z;const ee=Boolean(T.lowLatency);ee!==this.lowLatency&&m(ee);let ie=0;for(let ce=0;ce<T.dur.length;++ce)ie+=T.dur[ce];ie>0&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ie/T.dur.length)),s({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,$(_(D))},()=>this._handleNetworkError())},nextChunk:G}},g=()=>{n=!1,l&&l.abort(),d&&d.abort(),u&&u.abort(),a.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:E=>{const{videoElement:T,logger:w}=this.params;let F=b(e.jidxUrl),O,I,U,N,_=0,G,K,te;const $=()=>{G&&(clearTimeout(G),G=void 0);const j=Math.max(ZS,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ae=_+j,ue=oe(),me=Math.min(1e4,ae-ue);_=ue;const tt=()=>{u||h()&&F.seek(()=>{h()&&(_=oe(),D(),$())})};me>0?G=window.setTimeout(()=>{this.paused?$():tt()},me):tt()},D=()=>{let j;for(;j=F.nextChunk(N);)N=j,Pe(j);const ae=F.nextChunk(U);if(ae){if(U&&ae.discontinuity){w("Detected discontinuity; restarting playback"),this.paused?$():(g(),this._initPlayerWith(e));return}ce(ae)}else $()},z=(j,ae)=>{if(!h()||!this.sourceBuffer)return;let ue,me,tt;const Ae=qe=>{window.setTimeout(()=>{h()&&z(j,ae)},qe)};if(this.sourceBuffer.updating)w("Source buffer is updating; delaying appendBuffer"),Ae(100);else{const qe=oe(),it=T.currentTime;!this.paused&&T.buffered.length>1&&K===it&&qe-te>500&&(w("Stall suspected; trying to fix"),this._fixupStall()),K!==it&&(K=it,te=qe);const xt=this._getBufferSizeSec();if(xt>30)w(`Buffered ${xt} seconds; delaying appendBuffer`),Ae(2e3);else try{this.sourceBuffer.appendBuffer(j),this.videoPlayStarted?(this.bufferStates.push({ts:qe,buf:xt}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ae&&ae()}catch(vt){if(vt.name==="QuotaExceededError")w("QuotaExceededError; delaying appendBuffer"),tt=this.sourceBuffer.buffered.length,tt!==0&&(ue=this.sourceBuffer.buffered.start(0),me=it,me-ue>4&&this.sourceBuffer.remove(ue,me-3)),Ae(1e3);else throw vt}}},ee=()=>{I&&O&&(w([`Appending chunk, sz=${I.byteLength}:`,JSON.stringify(U)]),z(I,function(){I=null,D()}))},ie=j=>e.fragUrlTemplate.replace("%%id%%",j.chunkIdx),ce=j=>{h()&&p(ie(j),(ae,ue)=>{if(h()){if(ue/=1e3,I=ae,U=j,o=j.startTS,ue){const me=Math.min(10,j.dur/ue);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*me:me}ee()}},()=>this._handleNetworkError())},Pe=j=>{h()&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ie(j),!1)))},Lt=j=>{h()&&(e.cachedHeader=j,z(j,()=>{O=!0,ee()}))};n=!0,F.seek(j=>{if(h()){if(_=oe(),!j){$();return}N=j,!a.isNullable(E)||j.startTS>E?ce(j):(U=j,D())}},E),e.cachedHeader?Lt(e.cachedHeader):f(e.headerUrl,Lt,()=>this._handleNetworkError())},stop:g,getTimestampSec:()=>o},c}_switchToQuality(e){const{logger:t,playerCallback:r}=this.params;let s;e.bitrate!==this.bitrate&&(this.rep&&(s=this.rep.getTimestampSec(),a.isNonNullable(s)&&(s+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,a.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(s),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return a.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,r=h=>{if(!this.autoQuality)return;let f,p,v;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(p=this._getBufferSizeSec(),v=h/this.bitrate,p>10&&v>.8||p>15&&v>.5||p>20&&v>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}f=this._selectQuality(h),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${h}`)},n=(()=>({updateChunk:(f,p)=>{const v=oe();if(this.chunkRateEstimator.addInterval(f,v,p)){const S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:v-f,speed:S}),!0}},get:()=>{const f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}}))();let o=-1/0,l,d=!0;const u=()=>{let h=n.get();if(h&&l&&this.autoQuality){if(d&&h>l&&_l(o)<3e4)return;r(h)}d=this.autoQuality};return{updateChunk:(h,f)=>{const p=n.updateChunk(h,f);return p&&u(),p},notifySwitch:h=>{const f=oe();h<l&&(o=f),l=h}}}_fetchManifest(e,t,r){this.manifestRequest=ji(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Ii).withRetryCount(Ni).withRetryInterval(WS,QS).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;et(t).then(r=>{r||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:r,videoElement:s}=this.params,n=o=>{const l=[];return o!=null&&o.length?(o.forEach((d,u)=>{d.video&&s.canPlayType(d.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(d.codecs)&&(d.index=u,l.push(d))}),l.sort(function(d,u){return d.video&&u.video?u.video.height-d.video.height:u.bitrate-d.bitrate}),l):(this.params.playerCallback({name:"error",type:"partial_metadata"}),[])};this.manifest=n(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},JS))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var B;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(B||(B={}));const tb=[B.PAUSED,B.PLAYING,B.READY],ib=[B.PAUSED,B.PLAYING,B.READY];class rb{constructor(e){this.subscription=new a.Subscription,this.videoState=new Q(B.STOPPED),this.representations$=new a.ValueSubject([]),this.textTracksManager=new Oe,this.maxSeekBackTime$=new a.ValueSubject(1/0),this.zeroTime$=new a.ValueSubject(void 0),this.liveOffset=new na,this._dashCb=s=>{var n,o,l,d;switch(s.name){case"buffering":{const u=s.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${s.type}`,category:a.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=s.manifest,c=[];for(const h of u){const f=(n=h.name)!==null&&n!==void 0?n:h.index.toString(10),p=(o=ci(h.name))!==null&&o!==void 0?o:pt(h.video),v=h.bitrate/1e3,m=Object.assign({},h.video);if(!p)continue;const S={id:f,quality:p,bitrate:v,size:m};c.push({track:S,representation:h})}this.representations$.next(c),this.params.output.availableVideoTracks$.next(c.map(({track:h})=>h)),((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===B.MANIFEST_READY&&this.videoState.setState(B.MANIFEST_READY);break}case"qualitySwitch":{const u=s.quality,c=(d=this.representations$.getValue().find(({representation:h})=>h===u))===null||d===void 0?void 0:d.track;this.params.output.hostname$.next(new URL(u.headerUrl,this.params.source.url).hostname),a.isNonNullable(c)&&this.params.output.currentVideoTrack$.next(c);break}case"bandwidth":{const{size:u,duration:c}=s;this.params.dependencies.throughputEstimator.addRawSpeed(u,c);break}case"index":{this.maxSeekBackTime$.next(s.shiftDuration),this.zeroTime$.next(s.zeroTime);break}}},this.syncPlayback=()=>{var s;const n=this.videoState.getState(),o=this.videoState.getTransition(),l=this.params.desiredState.playbackState.getState(),d=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${n}; videoTransition: ${JSON.stringify(o)}; desiredPlaybackState: ${l}; seekState: ${JSON.stringify(u)};`}),l===exports.PlaybackState.STOPPED){n!==B.STOPPED&&(this.videoState.startTransitionTo(B.STOPPED),this.dash.destroy(),this.video.setAttribute("src",""),this.video.load(),this.videoState.setState(B.STOPPED));return}if(!o){if(ib.includes(n)){const c=(s=this.params.desiredState.videoTrack.getTransition())===null||s===void 0?void 0:s.to;a.isNonNullable(c)&&this.setVideoTrack(c);const h=this.params.desiredState.autoVideoTrackSwitching.getTransition();h&&this.setAutoQuality(h.to)}if((d==null?void 0:d.to)!==exports.PlaybackState.PAUSED&&u.state===C.Requested&&tb.includes(n)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(n){case B.STOPPED:this.videoState.startTransitionTo(B.MANIFEST_READY),this.dash.attachSource(_t(this.params.source.url));return;case B.MANIFEST_READY:this.videoState.startTransitionTo(B.READY),this.prepare();break;case B.READY:if(l===exports.PlaybackState.PAUSED)this.videoState.setState(B.PAUSED);else if(l===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(B.PLAYING);const c=d==null?void 0:d.from;c&&c===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(B.PAUSED)})}return;case B.PLAYING:l===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(B.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case B.PAUSED:l===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(B.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(B.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return a.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=s=>{e.output.error$.next({id:"DashLiveProvider",category:a.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:s})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(s)}`})}),this.video=Ge(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioTracksExist$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const r=Ye(this.video);this.subscription.add(r.canplay$.subscribe(()=>{var s;((s=this.videoState.getTransition())===null||s===void 0?void 0:s.to)===B.READY&&this.videoState.setState(B.READY)},t)).add(r.pause$.subscribe(()=>{this.videoState.setState(B.PAUSED)},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===C.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(B.PLAYING)},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(s=>-s/1e3)).subscribe(this.params.output.duration$)).add(a.combine({zeroTime:this.zeroTime$.pipe(a.filter(a.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:s,position:n})=>this.params.output.liveTime$.next(s+n*1e3),t)).add(mt(this.video,this.params.desiredState.isLooped,t)).add(He(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(Ze(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:s}})=>{const n=s&&oS(s);this.dash.setMaxAutoQuality(n)})).add(this.videoState.stateChangeEnded$.subscribe(s=>{var n;switch(s.to){case B.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case B.MANIFEST_READY:case B.READY:((n=this.params.desiredState.playbackState.getTransition())===null||n===void 0?void 0:n.to)===exports.PlaybackState.READY&&this.params.desiredState.playbackState.setState(exports.PlaybackState.READY);break;case B.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case B.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(s.to)}},t)).add(a.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const e=new eb({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,r,s,n,o;const l=this.representations$.getValue(),d=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),u=(s=(r=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||r===void 0?void 0:r.to)!==null&&s!==void 0?s:this.params.desiredState.autoVideoTrackSwitching.getState(),c=!u&&a.isNonNullable(d)?d:(n=di(l.map(({track:f})=>f),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState()}))===null||n===void 0?void 0:n.id,h=(o=l.find(({track:f})=>f.id===c))===null||o===void 0?void 0:o.representation;a.assertNonNullable(h,"Representations missing"),this.dash.startPlay(h,u),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(c),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(u)}setVideoTrack(e){var t;const r=(t=this.representations$.getValue().find(({track:s})=>s.id===e))===null||t===void 0?void 0:t.representation;a.assertNonNullable(r,`No such representation ${e}`),this.dash.switchByName(r.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=-e,r=t<=this.maxSeekBackTime$.getValue()?t:0;this.params.output.position$.next(e/1e3),this.liveOffset.resetTo(r),this.dash.reinit(_t(this.params.source.url,r))}}var Rl=i=>{var e,t;const r=i.get("X-Delivery-Type"),s=i.get("X-Reused"),n=r===null?exports.HttpConnectionType.HTTP1:(e=r)!==null&&e!==void 0?e:void 0,o=s===null?void 0:(t={1:!0,0:!1}[s])!==null&&t!==void 0?t:void 0;return{type:n,reused:o}},ot=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){const s=i.start(r)*1e3,n=i.end(r)*1e3;s<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const sb=i=>{const e=document.createElement("a");return e.href=i,e.origin},ab=i=>{const e=document.createElement("a");return e.href=i,e.host};class Il{constructor(e,t=[],r,s,n,o){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=r,this._progressCb=s,this._headersCb=n,this._errorCb=o,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{var t,r,s,n,o,l,d,u;if(a.assertNonNullable(this._xhr),((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(r=this._errorCb)===null||r===void 0||r.call(this,`Http${(s=this._xhr)===null||s===void 0?void 0:s.status}`,`XHR response code ${(n=this._xhr)===null||n===void 0?void 0:n.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const c=oi(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(h=>h.split(":").map(f=>f.trim())));(o=this._headersCb)===null||o===void 0||o.call(this,new Headers(c))}else this._xhr.readyState===4?(l=this._completeCb)===null||l===void 0||l.call(this,this._xhr.response):this._xhr.readyState===3&&((d=this._progressCb)===null||d===void 0||d.call(this,this._xhr.response))}catch(c){throw(u=this._errorCb)===null||u===void 0||u.call(this,"XHR2CallbackError",`xhr2 callback threw ${String(c)}`,c),c}},this._xhr.onerror=()=>{var t;(t=this._xhr)===null||t===void 0||t.abort(),this._retryTimeout=window.setTimeout(()=>{var r;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(r=this._errorCb)===null||r===void 0||r.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let s;this._failoverIndex>=this._failoverHosts.length?(s=this._url,this._failoverIndex=0):(s=this._url.replace(ab(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",s,!0),this._xhr.send(null)}},500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class Ki{constructor(e){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t==null||t()}catch(r){if(r.name==="QuotaExceededError"){this._isFull=!0;const s=this._sourceBuffer.buffered;let n=0;for(let o=0,l=s.length;o<l;o++)n+=s.end(o)-s.start(o);n&&(this._maxBufferDuration=Math.round(n))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",r),r}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,r,s,n,o,l){this.abort(()=>{let d=0;const u=Date.now();let c=0,h=0,f=0;const p=m=>{s(Ki._str2ua(m.substr(d))),d=m.length};let v=e.baseURL+"&bytes="+t+"-"+r;this._params.requestQuic&&(v=It(v)),this._lastXhr=new Il(v,e.failoverHosts,m=>{this._lastXhr=void 0,p(m);const S=Date.now()-u;this._params.onBandwidthChange({size:m.length,duration:S,speed:8*m.length/(S/1e3)}),this._onDashCallback("loading",{size:m.length,done:!0}),n==null||n()},m=>{if(m.length-d>l&&p(m),h===0){h=Date.now();return}f=m.length-c;const S=Date.now()-h;f>=100*1024&&S>=1e3&&(this._params.onBandwidthChange({size:f,duration:S,speed:8*f/(S/1e3)}),f=0,c=m.length,h=Date.now()),this._onDashCallback("loading",{size:m.length,done:!1})},o,(m,S,b)=>this._params.onError(m,S,b))})}abort(e){var t;(t=this._lastXhr)===null||t===void 0||t.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e==null||e()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(r){throw this._params.onError("SourceBuffer","Source Buffer update error",r),r}};return this._sourceBuffer.addEventListener("updateend",t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener("updateend",e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=Ki._concatUint8(this._appendPromiseUint8Array,e):(this._appendPromiseUint8Array=e,this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,()=>{this._appendPromiseUint8Array=void 0,t&&this._sbUpdatingWatch(t)})}))}endOfStream(){this._mediaSource.readyState==="open"&&this._sbUpdatingWatch(()=>this._mediaSource.endOfStream())}static _concatUint8(e,t){const r=new Uint8Array(e.byteLength+t.byteLength);return r.set(e,0),r.set(t,e.byteLength),r}static _str2ua(e){const t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}remove(e,t){this._sbUpdatingWatch(()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(e,t),this._maxBufferDuration=Number.POSITIVE_INFINITY})}destroy(){var e;(e=this._lastXhr)===null||e===void 0||e.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._mediaSource.readyState==="open"&&this._sourceBuffer.abort()}}class nb{constructor(e){var t;this._representations=[],this._appendVector={},this._cachingPaused=!1,this._duration=0,this.STREAM_END_THRESHOLD=1,this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=(t=e.onDashCallback)!==null&&t!==void 0?t:()=>{},this._config=e.config}_parseDurationFromISO8601(e){const t=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/,r=(l,d)=>{const u=l?parseFloat(l.replace(",",".")):NaN;return(isNaN(u)?0:u)*d},s=t.exec(e),n=(s==null?void 0:s[1])==="-"?-1:1,o={years:r(s==null?void 0:s[2],n),months:r(s==null?void 0:s[3],n),weeks:r(s==null?void 0:s[4],n),days:r(s==null?void 0:s[5],n),hours:r(s==null?void 0:s[6],n),minutes:r(s==null?void 0:s[7],n),seconds:r(s==null?void 0:s[8],n)};return o.hours*3600+o.minutes*60+o.seconds}getRepresentations(){return this._representations}attachSource(e,t){let r=e;this._config.REQUEST_QUIC&&(r=It(r)),new Il(r,t,s=>{this.attachManifest(s,t,sb(r))},void 0,s=>{this._params.onResponseHeaders(s)},(s,n,o)=>this._params.onError(s,n,o))}attachManifest(e,t,r){const n=new DOMParser().parseFromString(e,"text/xml").documentElement,o=(u,c)=>{const h=u.attributes.getNamedItem(c);return h?h.value:null};this._duration=this._parseDurationFromISO8601(String(o(n,"mediaPresentationDuration")));const l=[],d=[];if(Array.prototype.forEach.call(n.getElementsByTagName("Representation"),u=>{var c,h,f,p,v,m,S,b,g,P,E,T,w,F,O,I,U,N,_;const G=u.getElementsByTagName("SegmentBase")[0],K=G&&o(G,"indexRange").split("-"),te=G&&G.getElementsByTagName("Initialization")[0],$=te&&o(te,"range").split("-");if(!$||!K){const Pe=u.parentElement;if((Pe==null?void 0:Pe.getAttribute("contentType"))==="text"){const Lt=(c=u.getAttribute("id"))!==null&&c!==void 0?c:void 0,j=(r?r+"/":"")+((v=(p=(f=(h=u.getElementsByTagName("BaseURL"))===null||h===void 0?void 0:h[0])===null||f===void 0?void 0:f.childNodes)===null||p===void 0?void 0:p[0])===null||v===void 0?void 0:v.data),ae=(m=Pe.getAttribute("lang"))!==null&&m!==void 0?m:void 0;j&&d.push({id:Lt,url:j,language:ae})}return}const D=.1,z=Number((S=u.attributes.getNamedItem("bandwidth"))===null||S===void 0?void 0:S.value),ee=(r?r+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ie;const ce=(g=(b=u.attributes.getNamedItem("frameRate"))===null||b===void 0?void 0:b.value)!==null&&g!==void 0?g:void 0;ie=ce?oa(ce):void 0,l.push({width:Number((P=u.attributes.getNamedItem("width"))===null||P===void 0?void 0:P.value),height:Number((E=u.attributes.getNamedItem("height"))===null||E===void 0?void 0:E.value),bandwidth:z,baseURL:ee,failoverHosts:t,indexFrom:Number(K[0]),indexTo:Number(K[1]),initFrom:Number($[0]),initTo:Number($[1]),codecs:(w=(T=u.attributes.getNamedItem("codecs"))===null||T===void 0?void 0:T.value)!==null&&w!==void 0?w:void 0,mimeType:(O=(F=u.attributes.getNamedItem("mimeType"))===null||F===void 0?void 0:F.value)!==null&&O!==void 0?O:void 0,fps:ie,bufferSize:D*z/8,bufferLength:D,name:(U=(I=u.attributes.getNamedItem("okQuality"))===null||I===void 0?void 0:I.value)!==null&&U!==void 0?U:void 0,id:(_=(N=u.attributes.getNamedItem("id"))===null||N===void 0?void 0:N.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");f.setAttribute("src",h),u&&f.setAttribute("id",u),c&&f.setAttribute("srclang",c),this._video.appendChild(f)}),this._representations.sort((u,c)=>c.bandwidth-u.bandwidth),this._params.onManifestReady(this._representations)}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const r=Date.now();this._stream.load(e,e.initFrom,e.indexTo,s=>{let n=e.initTo-e.initFrom+1;if(!s.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(s.buffer,0,n);const o=new DataView(s.buffer);n+=12;const l=o.getUint32(n+4,!1);n+=8;let d=o.getUint32(n,!1),u=o.getUint32(n+4,!1)+(e.indexTo+1);n+=8;const c=o.getUint16(n+2,!1);n+=4,e.refs=[];for(let f=0;f<c;f+=1){const p=u+(o.getUint32(n,!1)&2147483647),v=d+o.getUint32(n+4,!1);n+=12,e.refs.push({fromTime:d/l,toTime:v/l,fromOffset:u,toOffset:p-1}),u=p,d=v}const h=e.refs[e.refs.length-1];h.toTime-h.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,s=>{this._params.onResponseHeaders(s),this._params.onIdxRequestPing(Date.now()-r)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const r=new t;let s,n;const o=()=>{const u=this._findRef(this._video.currentTime);if(!u||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const p=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),p)}const c=this._appendVector[String(u.fromTime)];c!==s&&(s=c,this._params.onRepresentationPlay(c));let h;if(this._findRef(u.toTime)){const p=this._buffer.getByTime(this._video.currentTime);if(!p){this._onDashCallback("buffering");return}h=p.to-this._video.currentTime,h<e.bufferLength&&(this._onDashCallback("buffering"),n!==p.to&&(n=p.to,window.setTimeout(()=>{try{const v=this._buffer.getNextWithGap(p);v&&(this._video.currentTime=v.from)}catch(v){throw this._params.onError("GapSyncError",`Seek Error ${String(v)}`,v),v}},h*1e3)))}},l=()=>{this._loopTimeout=window.setTimeout(()=>{try{o()}catch(u){throw this._params.onError("LoopError",`Dash Loop exception ${String(u)}`,u),u}l()},250)},d=()=>{if(!this._stream)try{const u=r.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Ki({mediaSource:r,sourceBuffer:u,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(u){throw this._params.onError("DashSourceOpen",`Source open exception ${String(u)}`,u),u}this._loadInitAndSidx(e),r.duration||(r.duration=this._duration),this._loopTimeout||l(),r.removeEventListener("sourceopen",d),r.removeEventListener("webkitsourceopen",d)};r.addEventListener("sourceopen",d,!1),r.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(r),this._video.addEventListener("waiting",()=>{const u=this._video&&this._video.played.length;u&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(u-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,r=!1,s=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const n=this._findRef(t);if(n){if(r){this._isLastRef(n)&&t>=n.toTime&&(t=n.fromTime);const o=this._findRef(this._video.currentTime),l=Math.abs(this._video.currentTime-t),d=s||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||n===o||l<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=d?t:n.fromTime}this._appendVector[String(n.fromTime)]=e,this._stream.load(e,n.fromOffset,n.toOffset,(o,l)=>this._stream.append(o,l),()=>{this._lastLoadOffset=n.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},o=>this._params.onResponseHeaders(o),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const r=this._buffer.getByTime(this._video.currentTime),s=this._findRef(this._video.currentTime);if(!r||!s){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(s.toTime<r.to+n){const o=this._findRef(s.toTime);o&&o.toTime<r.to+n?(this._buffer.smartRemove(s.fromTime-n,o.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(s.fromTime-n,s.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,s.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t){this._stream&&this._buffer.getByTime(e)?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0,t)}updateRefsForCurrentTime(){const e=this._video.currentTime;(!this._stream||a.isNullable(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const r=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!r)return;if(Array.isArray(r)&&r.length===0){this._params.onError("emptyrefs","Empty refs");return}let s;for(let n=0;n<r.length;n++){const o=r[n];if(o.fromTime<=e&&o.toTime>e)return o;o.fromTime>e&&(!s||o.fromTime<s.fromTime)&&(s=o)}if(!s){const n=r[r.length-1];if(e>n.toTime)return n}return s}_isLastRef(e){var t;const r=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!r)return!1;const s=r[r.length-1];return e.fromTime===s.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const r=this._video.buffered.start(t),s=this._video.buffered.end(t);if(e>r&&e<s)return Math.round(s*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var M;(function(i){i.STOPPED="stopped",i.MANIFEST_LOADED="manifest-loaded",i.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",i.METADATA_LOADED="metadata-loaded",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(M||(M={}));const ob=[M.PAUSED,M.PLAYING];class lb{constructor(e){this.videoState=new Q(M.STOPPED),this.subscription=new a.Subscription,this.representations$=new a.ValueSubject([]),this.currentRepresentation$=new a.ValueSubject(void 0),this.textTracksManager=new Oe,this.elementSize$=new a.ValueSubject(void 0),this.dashLiteEvents={idxRequestPing$:new a.Subject,responseHeaders$:new a.Subject,manifestReady$:new a.Subject,representationPlay$:new a.Subject,error$:new a.Subject},this.handleManifestReady=t=>{var r,s,n;const o=[];for(const l of t){const d=(s=(r=l.name)!==null&&r!==void 0?r:l.id)!==null&&s!==void 0?s:l.height.toString(10),u=(n=l.name&&ci(l.name))!==null&&n!==void 0?n:pt(l),c=l.bandwidth/1e3,h={width:l.width,height:l.height},f=l.fps;if(!u)continue;const p={id:d,quality:u,bitrate:c,size:h,fps:f};o.push({track:p,representation:l})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:l})=>l)),this.videoState.setState(M.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var r;const s=(r=this.representations$.getValue().find(({representation:n})=>n===t))===null||r===void 0?void 0:r.track;s&&(this.params.output.currentVideoTrack$.next(s),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(s.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return a.assertNonNullable(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${s}; seekState: ${JSON.stringify(o)};`}),s===exports.PlaybackState.STOPPED){t!==M.STOPPED&&(this.videoState.startTransitionTo(M.STOPPED),this.dash.destroy(),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(M.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!r)switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&o.state===C.Requested&&ob.includes(t)&&this.seek(o.position,o.forcePrecise),t){case M.STOPPED:this.videoState.startTransitionTo(M.MANIFEST_LOADED),this.prepare();return;case M.MANIFEST_LOADED:this.videoState.startTransitionTo(M.INITIAL_REPRESENTATION_SELECTED);return;case M.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(M.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case M.METADATA_LOADED:this.videoState.startTransitionTo(M.READY),this.dash.updateRefsForCurrentTime();return;case M.READY:s===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):s===exports.PlaybackState.PAUSED?(this.videoState.setState(M.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(M.PLAYING),this.playIfAllowed());return;case M.PLAYING:s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(M.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case M.PAUSED:s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(M.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),a.merge(this.videoState.stateChangeStarted$.pipe(a.map(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:r})=>{this.log({message:`[videoState change] ${r}: ${JSON.stringify(t)}`})}),this.video=Ge(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioTracksExist$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new ES(this.video),this.dash=new nb({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:t=>this.dashLiteEvents.manifestReady$.next(t),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,r,s)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:r,thrown:s,category:a.ErrorCategory.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,r=l=>{e.error$.next({id:"DashProvider",category:a.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:l})},s=()=>{const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:l},n=Ye(this.video),o=(l,d)=>this.subscription.add(l.subscribe(d,r));o(n.timeUpdate$,e.position$),o(n.durationChange$,e.duration$),o(n.ended$,e.endedEvent$),o(n.looped$,e.loopedEvent$),o(n.error$,e.error$),o(n.isBuffering$,e.isBuffering$),o(n.playing$,e.firstFrameEvent$),o(n.canplay$,e.canplay$),this.subscription.add(n.seeking$.subscribe(()=>{a.isNullable(this.params.desiredState.seekState.getState().state!==C.Applying)&&(this.videoState.getState()===M.PLAYING||this.videoState.getState()===M.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(mt(this.video,t.isLooped,r)),this.subscription.add(He(this.video,t.volume,n.volumeState$,r)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ze(this.video,t.playbackRate,n.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),o(Ji(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===M.READY&&this.videoState.setState(M.READY)},r)).add(n.pause$.subscribe(()=>{this.videoState.setState(M.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(M.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},r)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(M.METADATA_LOADED)},r)).add(n.currentBuffer$.subscribe(l=>{this.buffer.fill(),e.currentBuffer$.next(l)},r)).add(this.dashLiteEvents.error$.pipe(a.map(({id:l,message:d,thrown:u})=>({id:`DashLite_${l}`,category:a.ErrorCategory.WTF,message:d,thrown:u}))).subscribe(this.params.output.error$)).add(a.merge(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$,this.params.output.element$,this.elementSize$,a.fromEvent(this.video,"progress")).pipe(a.map(()=>{var l,d,u;const c=this.currentRepresentation$.getValue(),h=this.representations$.getValue(),f=this.params.desiredState.autoVideoTrackSwitching.getTransition(),p=this.params.desiredState.videoTrack.getState(),v=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),m=this.elementSize$.getValue(),S=s();f&&this.params.desiredState.autoVideoTrackSwitching.setState(f.to);let b;if(!S&&a.isNonNullable(p))b=p;else{const g=ot(this.video.buffered,this.video.currentTime*1e3),P=S?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,E=Math.min(g/P,1);b=(d=di(h.map(({track:T})=>T),{container:m,throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:E,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 a.isNonNullable(b)?(u=h.find(({track:g})=>g.id===b))===null||u===void 0?void 0:u.representation:void 0}),a.filterChanged()).subscribe(this.currentRepresentation$,r)).add(a.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(a.filter(l=>l.to===M.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(a.filter(a.isNonNullable))}).pipe(a.once()).subscribe(()=>this.videoState.setState(M.INITIAL_REPRESENTATION_SELECTED),r)).add(this.currentRepresentation$.pipe(a.filter(a.isNonNullable),a.filterChanged((l,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&s()?l.height<=d.height:l===d)).subscribe(l=>{const d=ot(this.video.buffered,this.video.currentTime*1e3),u=Math.min(d/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||u<=.5||!s())&&(this.dash.setQualityByRepresentation(l,!0),this.params.output.hostname$.next(de(l.baseURL)))},r)).add(this.dashLiteEvents.responseHeaders$.subscribe(l=>{const{type:d,reused:u}=Rl(l);this.params.output.httpConnectionType$.next(d),this.params.output.httpConnectionReused$.next(u)})).add(this.dashLiteEvents.idxRequestPing$.pipe(a.once(),a.mapTo(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(l=>this.params.dependencies.throughputEstimator.addRawRtt(l))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,r)).add(this.dashLiteEvents.representationPlay$.pipe(a.filter(a.isNonNullable)).subscribe(this.handleRepresentationPlay,r)).add(a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return a.assertNever(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){et(this.video).then(e=>{e||(this.videoState.setState(M.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}}var Se;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(Se||(Se={}));var Xi;(function(i){i.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",i.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Xi||(Xi={}));var be;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(be||(be={}));var H;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(H||(H={}));var Nt;(function(i){i.MP4="mp4",i.WEBM="webm"})(Nt||(Nt={}));var Ds=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};const ub=(i,e={})=>{const r=e.timeout||1,s=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-s-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-s))}})},1)},db=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Mn=db?ub:window.requestIdleCallback;var Jr,Kr;let Nl=!1;try{Nl=Al()&&parseInt((Kr=(Jr=navigator.userAgent.match(/Version\/(\d+)/))===null||Jr===void 0?void 0:Jr[1])!==null&&Kr!==void 0?Kr:"",10)<16}catch(i){console.error(i)}class cb{constructor(e){this.bufferFull$=new a.Subject,this.error$=new a.Subject,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const r=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!r),this.currentTask=null}this.queue.length&&this.pull()}catch(r){this.error$.next({id:"BufferTaskQueueUnknown",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:r})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return J(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(r=>{const s={operation:"append",data:e,signal:t,callback:r};this.queue.push(s),this.pull()})})}remove(e,t,r){return J(this,void 0,void 0,function*(){return r&&r.aborted?!1:new Promise(s=>{const n={operation:"remove",from:e,to:t,signal:r,callback:s};this.queue.unshift(n),this.pull()})})}abort(e){return J(this,void 0,void 0,function*(){return new Promise(t=>{let r;Nl&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(const{callback:s}of this.queue)s(!1);r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask)}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:r}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&r==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"&&r==="remove"||this.error$.next({id:`BufferTaskQueue:${r}`,category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:n}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:a.assertNever(t)}}}var Vn=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};const Cl=new TextDecoder("ascii"),Dl=i=>{let e=0,t=i.getUint32(e);e+=4;const r=new DataView(i.buffer,i.byteOffset+e,4),s=Cl.decode(r);e+=4,t===0?t=1/0:t===1&&(e+=8,t=1/0);const n=Math.min(t,i.byteLength)-e,o=new DataView(i.buffer,i.byteOffset+e,n);return{id:s,size:t,contents:o}},hb=i=>Cl.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",fb=(i,e,t)=>{const r=Dl(i),s=[];let n=0;const o=()=>{const m=r.contents.getUint32(n);return n+=4,m};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,v=(t?t.to+1:i.byteOffset+i.byteLength)+h;for(let m=0;m<f;m++){const S=o(),b=S>>>31,g=S<<1>>>1,P=o();if(o(),b!==0)throw new Error("Unsupported multilevel sidx");const E=P/u*1e3;s.push({status:H.NONE,time:{from:p,to:p+E},byte:{from:v,to:v+g-1}}),p+=E,v+=g}return s},pb=i=>{let e=0,t=!1,r=!1;for(;e<=i.byteLength&&!t;){const s=new DataView(i.buffer,i.byteOffset+e);try{const n=Dl(s);if(r||(r=n.id==="mdat"),e+n.size<=i.byteLength)e+=n.size;else break}catch(n){t=!0}}return e>0&&e<=i.byteLength&&r?new DataView(i.buffer,i.byteOffset,e):null},mb={validateData:hb,parseInit:()=>null,getIndexRange:()=>{},parseSegments:fb,parseFeedableSegmentChunk:pb};var y;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.Chapters=272869232]="Chapters",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.SilentTracks=22612]="SilentTracks",i[i.SilentTrackNumber=22743]="SilentTrackNumber",i[i.Position=167]="Position",i[i.PrevSize=171]="PrevSize",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.EncryptedBlock=175]="EncryptedBlock",i[i.Attachments=423732329]="Attachments",i[i.Tags=307544935]="Tags",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.CueRelativePosition=240]="CueRelativePosition",i[i.CueDuration=178]="CueDuration",i[i.CueBlockNumber=21368]="CueBlockNumber",i[i.CueCodecState=234]="CueCodecState",i[i.CueReference=219]="CueReference",i[i.CueRefTime=150]="CueRefTime"})(y||(y={}));var A;(function(i){i.SignedInteger="int",i.UnsignedInteger="uint",i.Float="float",i.String="string",i.UTF8="utf8",i.Date="date",i.Master="master",i.Binary="binary"})(A||(A={}));const Fn={[y.EBML]:{type:A.Master},[y.EBMLVersion]:{type:A.UnsignedInteger},[y.EBMLReadVersion]:{type:A.UnsignedInteger},[y.EBMLMaxIDLength]:{type:A.UnsignedInteger},[y.EBMLMaxSizeLength]:{type:A.UnsignedInteger},[y.DocType]:{type:A.String},[y.DocTypeVersion]:{type:A.UnsignedInteger},[y.DocTypeReadVersion]:{type:A.UnsignedInteger},[y.Void]:{type:A.Binary},[y.Segment]:{type:A.Master},[y.SeekHead]:{type:A.Master},[y.Seek]:{type:A.Master},[y.SeekID]:{type:A.Binary},[y.SeekPosition]:{type:A.UnsignedInteger},[y.Info]:{type:A.Master},[y.TimestampScale]:{type:A.UnsignedInteger},[y.Duration]:{type:A.Float},[y.Tracks]:{type:A.Master},[y.Chapters]:{type:A.Master},[y.Cluster]:{type:A.Master},[y.Timestamp]:{type:A.UnsignedInteger},[y.SilentTracks]:{type:A.Master},[y.SilentTrackNumber]:{type:A.UnsignedInteger},[y.Position]:{type:A.UnsignedInteger},[y.PrevSize]:{type:A.UnsignedInteger},[y.SimpleBlock]:{type:A.Binary},[y.BlockGroup]:{type:A.Master},[y.EncryptedBlock]:{type:A.Binary},[y.Attachments]:{type:A.Master},[y.Tags]:{type:A.Master},[y.Cues]:{type:A.Master},[y.CuePoint]:{type:A.Master},[y.CueTime]:{type:A.UnsignedInteger},[y.CueTrackPositions]:{type:A.Master},[y.CueTrack]:{type:A.UnsignedInteger},[y.CueClusterPosition]:{type:A.UnsignedInteger},[y.CueRelativePosition]:{type:A.UnsignedInteger},[y.CueDuration]:{type:A.UnsignedInteger},[y.CueBlockNumber]:{type:A.UnsignedInteger},[y.CueCodecState]:{type:A.UnsignedInteger},[y.CueReference]:{type:A.Master},[y.CueRefTime]:{type:A.UnsignedInteger}},Ol=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const r=Zi(i,t),s=r in Fn,n=s?Fn[r].type:A.Binary,o=i.getUint8(t);let l=0;o&128?l=1:o&64?l=2:o&32?l=3:o&16?l=4:o&8?l=5:o&4?l=6:o&2?l=7:o&1&&(l=8);const d=new DataView(i.buffer,i.byteOffset+t+1,l-1),u=((o&255>>l)<<(l-1)*8)+Zi(d),c=t+l;let h;return c+u>i.byteLength?h=new DataView(i.buffer,i.byteOffset+c):h=new DataView(i.buffer,i.byteOffset+c,u),{tag:s?r:"0x"+r.toString(16).toUpperCase(),type:n,tagHeaderSize:c,tagSize:c+u,value:h,valueSize:u}},Zi=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint16(0)<<8|i.getUint8(2);case 4:return i.getUint32(0);case 5:return i.getUint32(0)<<8|i.getUint8(4);case 6:return i.getUint32(0)<<16|i.getUint16(4);case 7:return i.getUint32(0)<<32|i.getUint16(4)<<8|i.getUint8(6);case 8:return i.getUint32(0)<<32|i.getUint32(4)}return 0},Me=(i,e)=>{switch(e){case A.SignedInteger:return i.getInt8(0);case A.UnsignedInteger:return Zi(i);case A.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case A.String:return new TextDecoder("ascii").decode(i);case A.UTF8:return new TextDecoder("utf-8").decode(i);case A.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case A.Master:return i;case A.Binary:return i;default:a.assertNever(e)}},hi=(i,e)=>{let t=0;for(;t<i.byteLength;){const r=new DataView(i.buffer,i.byteOffset+t),s=Ol(r);if(!e(s))return;s.type===A.Master&&hi(s.value,e),t=s.value.byteOffset-i.byteOffset+s.valueSize}},vb=i=>{if(i.getUint32(0)!==y.EBML)return!1;let e,t,r;const s=Ol(i);return hi(s.value,({tag:n,type:o,value:l})=>(n===y.EBMLReadVersion?e=Me(l,o):n===y.DocType?t=Me(l,o):n===y.DocTypeReadVersion&&(r=Me(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)},Ll=[y.Info,y.SeekHead,y.Tracks,y.Chapters,y.Cluster,y.Cues,y.Attachments,y.Tags],Sb=[y.Timestamp,y.SilentTracks,y.SilentTrackNumber,y.Position,y.PrevSize,y.SimpleBlock,y.BlockGroup,y.EncryptedBlock],bb=i=>{let e,t,r,s,n=!1,o=!1,l=!1,d,u;return hi(i,({tag:c,type:h,value:f,valueSize:p})=>{if(c===y.SeekID){const v=Me(f,h);u=Zi(v)}else c!==y.SeekPosition&&(u=void 0);return c===y.Segment?(e=f.byteOffset,t=f.byteOffset+p):c===y.Info?n=!0:c===y.SeekHead?o=!0:c===y.TimestampScale?r=Me(f,h):c===y.Duration?s=Me(f,h):c===y.SeekPosition&&u===y.Cues?d=Me(f,h):n&&o&&Ll.includes(c)&&(l=!0),!l}),a.assertNonNullable(e,"Failed to parse webm Segment start"),a.assertNonNullable(t,"Failed to parse webm Segment end"),a.assertNonNullable(s,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(s/1e9*r*1e3),cuesSeekPosition:d}},gb=i=>{if(a.isNullable(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},yb=(i,e)=>{let t=!1,r=!1;const s=l=>a.isNonNullable(l.time)&&a.isNonNullable(l.position),n=[];let o;return hi(i,({tag:l,type:d,value:u})=>{switch(l){case y.Cues:t=!0;break;case y.CuePoint:o&&s(o)&&n.push(o),o={};break;case y.CueTime:o&&(o.time=Me(u,d));break;case y.CueTrackPositions:break;case y.CueClusterPosition:o&&(o.position=Me(u,d));break;default:t&&Ll.includes(l)&&(r=!0)}return!(t&&r)}),o&&s(o)&&n.push(o),n.map((l,d)=>{const{time:u,position:c}=l,h=n[d+1];return{status: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}}})},Tb=i=>{let e=0,t=!1;try{hi(i,r=>r.tag===y.Cluster?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):Sb.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||(t=[y.SimpleBlock,y.BlockGroup,y.EncryptedBlock].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},Eb={validateData:vb,parseInit:bb,getIndexRange:gb,parseSegments:yb,parseFeedableSegmentChunk:Tb};class Un{constructor(e,t,r,s,{fetcher:n,tuning:o,getCurrentPosition:l,compatibilityMode:d=!1}){switch(this.onLastSegment$=new a.ValueSubject(!1),this.fullyBuffered$=new a.ValueSubject(!1),this.playingRepresentation$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.gaps=[],this.subscription=new a.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new lt,this.destroyAbortController=new lt,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=a.abortable(this.destroyAbortController.signal,function(u){return Ee(this,arguments,function*(){const c=this.representations.get(u);a.assertNonNullable(c,`Cannot find representation ${u}`),this.playingRepresentationId=u,this.downloadingRepresentationId=u,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${c.mime}; codecs="${c.codecs}"`),this.sourceBufferTaskQueue=new cb(this.sourceBuffer),this.subscription.add(a.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},v=>this.error$.next({id:"SegmentEjection",category:a.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:v}))),this.subscription.add(a.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:a.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(v=>{if(!this.sourceBuffer)return;const m=Math.min(this.bufferLimit,Vn(this.sourceBuffer.buffered)*.8);this.bufferLimit=m,this.pruneBuffer(this.getCurrentPosition(),v)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(v=>this.error$.next(v))),yield yield R(this.loadInit(c,"high",!0));const h=this.initData.get(c.id),f=this.segments.get(c.id);if(a.assertNonNullable(h,"No init buffer for starting representation"),a.assertNonNullable(f,"No segments for starting representation"),!(h instanceof ArrayBuffer))return yield R(void 0);let p=0;for(const v of f)v.time.from-p>0&&this.gaps.push({representation:c.id,from:p,to:v.time.from}),p=v.time.to;a.isNonNullable(c.duration)&&c.duration-p>0&&this.gaps.push({representation:c.id,from:p,to:c.duration}),yield yield R(this.sourceBufferTaskQueue.append(h,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId)})}.bind(this)),this.switchTo=a.abortable(this.destroyAbortController.signal,function(u){return Ee(this,arguments,function*(){if(u===this.downloadingRepresentationId||u===this.switchingToRepresentationId)return yield R(void 0);this.switchingToRepresentationId=u;const c=this.representations.get(u);a.assertNonNullable(c,`No such representation ${u}`);let h=this.initData.get(u);if(a.isNullable(h)?yield yield R(this.loadInit(c,"high",!1)):h instanceof Promise&&(yield yield R(h)),h=this.initData.get(u),!h||!(h instanceof ArrayBuffer)||!this.sourceBuffer)return yield R(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=u,this.abort(),yield yield R(this.sourceBufferTaskQueue.append(h,this.downloadAbortController.signal));const f=this.getCurrentPosition();a.isNonNullable(f)&&this.maintain(f)})}.bind(this)),this.fetcher=n,this.tuning=o,this.compatibilityMode=d,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=l,this.container=r,r){case Nt.MP4:this.containerParser=mb;break;case Nt.WEBM:this.containerParser=Eb;break;default:a.assertNever(r)}this.initData=new Map(s.map(u=>[u.id,null])),this.segments=new Map,this.representations=new Map(s.map(u=>[u.id,u])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new lt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(a.isNullable(e)||a.isNullable(this.downloadingRepresentationId)||a.isNullable(this.playingRepresentationId)||a.isNullable(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(a.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;const s=r.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=ot(this.sourceBuffer.buffered,e),h=s?s.time.to+100:-1/0;s&&c>=s.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&Vn(this.sourceBuffer.buffered)>=this.bufferLimit){const u=ot(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<c);return}let l=[];if(!this.activeSegments.size&&(l=this.selectForwardBufferSegments(r,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&s)if(l.includes(s))u="high";else{const c=xe(l,0);c&&c.time.from-s.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}!this.preloadOnly&&!this.allInitsLoaded&&s&&s.status===H.FED&&!l.length&&ot(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=xe(r,-1);d&&d.status===H.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===d))}findSegmentStartTime(e){var t,r,s;const n=(r=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&r!==void 0?r:this.playingRepresentationId;if(!n)return;const o=this.segments.get(n);if(!o)return;const l=o.find(d=>d.time.from<=e&&d.time.to>=e);return(s=l==null?void 0:l.time.from)!==null&&s!==void 0?s:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;this.initData.clear(),this.segments.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer&&this.mediaSource.readyState==="open"&&(this.abortBuffer(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,r){const s=e.findIndex(({status:h,time:{from:f,to:p}},v)=>{const m=f<=r&&p>=r,S=f>r||m||v===0&&r===0,b=Math.min(this.forwardBufferTarget,this.bufferLimit),g=this.preloadOnly&&f<=r+b||p<=r+b;return(h===H.NONE||h===H.PARTIALLY_EJECTED&&S&&g&&this.sourceBuffer&&!Ds(this.sourceBuffer.buffered,r))&&S&&g});if(s===-1)return[];if(t!==be.BYTE_RANGE)return e.slice(s,s+1);const n=e;let o=0,l=0;const d=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let h=s;h<n.length&&(o<=u||l<=c);h++){const f=n[h];if(o+=f.byte.to+1-f.byte.from,l+=f.time.to+1-f.time.from,f.status===H.NONE||f.status===H.PARTIALLY_EJECTED)d.push(f);else break}return d}loadSegments(e,t,r="auto"){return J(this,void 0,void 0,function*(){if(!e.length)return;let s,n,o=e;const{type:l}=t.segmentReference;switch(l){case be.BYTE_RANGE:{s=t.segmentReference.url,n={from:xe(e,0).byte.from,to:xe(e,-1).byte.to};break}case be.TEMPLATE:{const u=xe(e,0);s=new URL(u.url,t.segmentReference.baseUrl).toString(),o=[u];break}default:a.assertNever(l)}for(const u of o)u.status=H.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(yield a.abortable(d,function(){return Ee(this,arguments,function*(){const u=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield R(new Promise(c=>setTimeout(c,u)))})}.bind(this))(),d.aborted))for(const u of this.activeSegments)e.includes(u.segment)&&this.abortSegment(u.segment);return void this.fetcher.fetch(s,{range:n,onProgress:(u,c)=>{if(!d.aborted)try{this.onSomeDataLoaded(u,t.id,n?n.from:0,c,d)}catch(h){this.error$.next({id:"SegmentFeeding",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}},signal:d,priority:r}).then(()=>this.failedDownloads=0,u=>{for(const c of this.activeSegments)e.includes(c.segment)&&this.abortSegment(c.segment);this.onSegmentDownloadError(u)})})}onSegmentDownloadError(e){var t;let r=!1;const s=this.getCurrentPosition();this.sourceBuffer&&a.isNonNullable(s)&&(r=ot((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,s)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,r||this.error$.next({id:"SegmentDownload",category:a.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,r,s,n){if(!this.activeSegments.size)return;const o=()=>{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 v of(f=this.segments.get(p.id))!==null&&f!==void 0?f:[])v.status===H.FED&&v.time.from===h.segment.time.from&&v.time.to===h.segment.time.to&&(v.status=H.NONE);this.activeSegments.delete(h),this.detectGapsWhenIdle(t,[h.segment])},d=this.representations.get(t);if(!d)return;const u=d.segmentReference.type,c=e.byteLength;for(const h of this.activeSegments){const{segment:f}=h,p=u===be.BYTE_RANGE,v=p?f.byte.to-f.byte.from+1:c;if(h.representationId!==t||!(!p||f.byte.from>=r&&f.byte.to<r+e.byteLength))continue;if(n.aborted){o();continue}const S=p?f.byte.from-r:0,b=p?f.byte.to-r:e.byteLength,g=S<s,P=b<=s;if(f.status===H.DOWNLOADING&&g&&P){f.status=H.DOWNLOADED,this.activeSegments.delete(h);const E=new DataView(e.buffer,e.byteOffset+S,v);this.sourceBufferTaskQueue.append(E,n).then(T=>T&&!n.aborted?l(h):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&g&&(h.loadedBytes=Math.min(v,s-S),h.loadedBytes>h.feedingBytes)){const E=new DataView(e.buffer,e.byteOffset+S+h.feedingBytes,h.loadedBytes-h.feedingBytes),T=h.loadedBytes===v?E:this.containerParser.parseFeedableSegmentChunk(E);T!=null&&T.byteLength&&(f.status=H.PARTIALLY_FED,h.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,n).then(w=>{if(n.aborted)o();else if(w)h.fedBytes+=T.byteLength,h.fedBytes===v&&l(h);else{if(h.feedingBytes<v)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[s,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const r=this.representations.get(e);r&&(this.initLoadIdleCallback=Mn(()=>dr(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return J(this,void 0,void 0,function*(){const s=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!r&&this.failedDownloads>0?a.abortable(this.destroyAbortController.signal,function(){return Ee(this,arguments,function*(){const l=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield R(new Promise(d=>setTimeout(d,l)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s)).then(l=>{if(!l)return;const{dataView:d,segments:u}=l,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c),this.segments.set(e.id,u)}).then(()=>this.failedDownloads=0,l=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:a.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o})}pruneBuffer(e,t,r=!1){return J(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||a.isNullable(e)||this.sourceBuffer.updating)return!1;let s=0,n=1/0,o=-1/0,l=!1;const d=u=>{var c;n=Math.min(n,u.time.from),o=Math.max(o,u.time.to);const h="size"in u?(c=u.size)!==null&&c!==void 0?c:0:u.byte.to-u.byte.from;s+=h};for(const u of this.segments.values())for(const c of u){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||s>=t)break;c.status===H.FED&&d(c)}if(l=isFinite(n)&&isFinite(o),!l){s=0,n=1/0,o=-1/0;for(const u of this.segments.values())for(const c of u){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||s>t)break;c.status===H.FED&&d(c)}}if(l=isFinite(n)&&isFinite(o),!l)for(let u=0;u<this.sourceBuffer.buffered.length;u++){const c=this.sourceBuffer.buffered.start(u)*1e3,h=this.sourceBuffer.buffered.end(u)*1e3;for(const f of this.segments.values())for(const p of f)if(p.status===H.NONE&&Math.round(p.time.from)<=Math.round(c)&&Math.round(p.time.to)>=Math.round(h)){n=c,o=h;break}}if(l=isFinite(n)&&isFinite(o),!l&&r){s=0,n=1/0,o=-1/0;const u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const c of this.segments.values())for(const h of c)h.time.from>e+u&&h.status===H.FED&&d(h)}return l=isFinite(n)&&isFinite(o),l?this.sourceBufferTaskQueue.remove(n,o):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}detectGaps(e,t){if(this.sourceBuffer)for(const r of t){let s={representation:e,from:r.time.from,to:r.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3;if(!(l<=r.time.from||o>=r.time.to)){if(o<=r.time.from&&l>=r.time.to){s=void 0;break}l>r.time.from&&l<r.time.to&&(s.from=l),o<r.time.to&&o>r.time.from&&(s.to=o)}}s&&s.to-s.from>=1&&!this.gaps.some(n=>s&&n.from===s.from&&n.to===s.to)&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Mn(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:a.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(a.isNullable(this.sourceBuffer)||a.isNullable(this.playingRepresentationId))return;const e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){const s=Math.round(this.sourceBuffer.buffered.start(r)*1e3),n=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:s,to:n})}const t=1;for(const r of this.segments.values())for(const s of r){const{status:n}=s;if(n!==H.FED&&n!==H.PARTIALLY_EJECTED)continue;const o=Math.floor(s.time.from),l=Math.ceil(s.time.to),d=e.some(c=>c.from-t<=o&&c.to+t>=l),u=e.filter(c=>o>=c.from-t&&o<=c.to+t||l>=c.from-t&&l<=c.to+t);d||(u.length===1?s.status=H.PARTIALLY_EJECTED:s.status=H.NONE)}}}var Pt;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(Pt||(Pt={}));class $b{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.abortAllController=new lt,this.subscription=new a.Subscription,this.fetchManifest=a.abortable(this.abortAllController.signal,function(s){return Ee(this,arguments,function*(){let n=s;this.requestQuic&&(n=It(n));const o=yield yield R(Rt(n,{signal:this.abortAllController.signal}).catch(Qt));return o?(this.onHeadersReceived(o.headers),yield R(o.text())):yield R(null)})}.bind(this)),this.fetch=a.abortable(this.abortAllController.signal,function(s,{rangeMethod:n=this.compatibilityMode?Pt.HEADER:Pt.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0}={}){var h,f,p,v;return Ee(this,arguments,function*(){let m=s;const S=new Headers;if(o)switch(n){case Pt.HEADER:{S.append("Range",`bytes=${o.from}-${o.to}`);break}case Pt.PARAM:{const $=new URL(m,location.href);$.searchParams.append("bytes",`${o.from}-${o.to}`),m=$.toString();break}default:a.assertNever(n)}this.requestQuic&&(m=It(m));let b=this.abortAllController.signal;if(u){const $=new lt;if(this.subscription.add(a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.fromEvent(u,"abort")).subscribe(()=>{try{$.abort()}catch(D){Qt(D)}})),this.abortAllController.signal.aborted||u.aborted)try{$.abort()}catch(D){Qt(D)}b=$.signal}const g=a.now(),P=yield yield R(Rt(m,{priority:d,headers:S,signal:b}).catch(Qt)),E=a.now();if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(E-g),!P)return yield R(null);if(!P.ok||!P.body)return yield R(Promise.reject(new Error(`Fetch error ${P.status}: ${P.statusText}`)));this.onHeadersReceived(P.headers);const T=parseInt((f=P.headers.get("Content-Length"))!==null&&f!==void 0?f:"",10)||o&&o.to-o.from+1||NaN;if(!T){const $=yield yield R(P.arrayBuffer());return(p=this.throughputEstimator)===null||p===void 0||p.addRawSpeed($.byteLength,a.now()-E),l==null||l(new DataView($),$.byteLength),yield R($)}if(!l&&!c)return yield R(P.arrayBuffer());const[w,F]=P.body.tee(),O=w.getReader();c&&((v=this.throughputEstimator)===null||v===void 0||v.trackStream(F));let I=0;const U=new ArrayBuffer(T),N=new Uint8Array(U),_=new DataView(U);let G=!1;const K=$=>{G=!0,Qt($)},te=a.abortable(b,function({done:$,value:D}){return Ee(this,arguments,function*(){if(I===0&&this.lastRequestFirstBytes$.next(a.now()-g),b.aborted)return yield R(void 0);$?l==null||l(_,I):D&&(N.set(D,I),I+=D.byteLength,l==null||l(_,I),yield yield R(O==null?void 0:O.read().then(te,K)))})}.bind(this));return yield yield R(O==null?void 0:O.read().then(te,K)),yield R(G?null:U)})}.bind(this)),this.fetchByteRangeRepresentation=a.abortable(this.abortAllController.signal,function(s,n,o){var l;return Ee(this,arguments,function*(){if(s.type!==be.BYTE_RANGE)return yield R(null);const{from:d,to:u}=s.initRange;let c=d,h=u,f=!1,p,v;s.indexRange&&(p=s.indexRange.from,v=s.indexRange.to,f=u+1===p,f&&(c=Math.min(p,d),h=Math.max(v,u))),c=Math.min(c,0);const m=yield yield R(this.fetch(s.url,{range:{from:c,to:h},priority:o,measureThroughput:!1}));if(!m)return yield R(null);const S=new DataView(m,d-c,u-c+1);if(!n.validateData(S))throw new Error("Invalid media file");const b=n.parseInit(S),g=(l=s.indexRange)!==null&&l!==void 0?l:n.getIndexRange(b);if(!g)throw new ReferenceError("No way to load representation index");let P;if(f)P=new DataView(m,g.from-c,g.to-g.from+1);else{const T=yield yield R(this.fetch(s.url,{range:g,priority:o,measureThroughput:!1}));if(!T)return yield R(null);P=new DataView(T)}const E=n.parseSegments(P,b,g);return yield R({dataView:new DataView(m),segments:E})})}.bind(this)),this.fetchTemplateRepresentation=a.abortable(this.abortAllController.signal,function(s,n){return Ee(this,arguments,function*(){if(s.type!==be.TEMPLATE)return yield R(null);const o=new URL(s.initUrl,s.baseUrl).toString(),l=yield yield R(this.fetch(o,{priority:n,measureThroughput:!1}));if(!l)return yield R(null);const d=s.segments.map(u=>Object.assign(Object.assign({},u),{status:H.NONE,size:void 0}));return yield R({segments:d,dataView:new DataView(l)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r}onHeadersReceived(e){const{type:t,reused:r}=Rl(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){var s,n;return J(this,void 0,void 0,function*(){const{type:o}=e;switch(o){case be.BYTE_RANGE:return(s=yield this.fetchByteRangeRepresentation(e,t,r))!==null&&s!==void 0?s:null;case be.TEMPLATE:return(n=yield this.fetchTemplateRepresentation(e,r))!==null&&n!==void 0?n:null;default:a.assertNever(o)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Qt=i=>{if(!(i instanceof DOMException)||!(i.name==="AbortError"||i.code===20))throw i},jn=i=>{if(!i.startsWith("P"))return;const e=(o,l)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*l},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),s=(r==null?void 0:r[1])==="-"?-1:1,n={days:e(r==null?void 0:r[5],s),hours:e(r==null?void 0:r[6],s),minutes:e(r==null?void 0:r[7],s),seconds:e(r==null?void 0:r[8],s)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},Xr=(i,e)=>{let t=i;t=t.replaceAll("$$","$");const r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,n]of Object.entries(r)){const o=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=t.replaceAll(o,(l,d)=>a.isNullable(n)?l:a.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},kb=(i,e)=>{var t,r,s,n,o,l,d,u,c,h,f,p,v,m,S,b,g,P,E,T,w,F,O,I,U,N,_,G,K,te,$,D,z,ee,ie,ce,Pe;const j=new DOMParser().parseFromString(i,"application/xml"),ae={video:[],audio:[],text:[]},ue=j.children[0],me=ue.getElementsByTagName("Period")[0],tt=me.children;let Ae;const qe=ue.getAttribute("mediaPresentationDuration"),it=me.getAttribute("duration");if(qe)Ae=jn(qe);else if(it){const we=jn(it);a.isNonNullable(we)&&(Ae=we)}let xt=0;const vt=(r=(t=ue.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&r!==void 0?r:[],Ul=vt.includes(Xi.WEBM_AS_IN_FFMPEG)||vt.includes(Xi.WEBM_AS_IN_SPEC)?Nt.WEBM:Nt.MP4;for(const we of tt){const fi=we.getAttribute("mimeType"),jl=we.getAttribute("codecs"),ua=(s=we.getAttribute("contentType"))!==null&&s!==void 0?s:fi==null?void 0:fi.split("/")[0],Hl=(o=(n=we.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],Gl=we.querySelectorAll("Representation"),Yl=we.querySelector("SegmentTemplate");if(ua!=="text")for(const ne of Gl){const Bt=(l=ne.getAttribute("mimeType"))!==null&&l!==void 0?l:fi,da=(u=(d=ne.getAttribute("codecs"))!==null&&d!==void 0?d:jl)!==null&&u!==void 0?u:"",pi=(h=(c=ne.getAttribute("contentType"))!==null&&c!==void 0?c:Bt==null?void 0:Bt.split("/")[0])!==null&&h!==void 0?h:ua,ql=(p=(f=we.getAttribute("profiles"))===null||f===void 0?void 0:f.split(","))!==null&&p!==void 0?p:[],zl=parseInt((v=ne.getAttribute("width"))!==null&&v!==void 0?v:"",10),ca=parseInt((m=ne.getAttribute("height"))!==null&&m!==void 0?m:"",10),ha=parseInt((S=ne.getAttribute("bandwidth"))!==null&&S!==void 0?S:"",10)/1e3,fa=(b=ne.getAttribute("frameRate"))!==null&&b!==void 0?b:"",Wl=(g=ne.getAttribute("quality"))!==null&&g!==void 0?g:void 0,Ql=fa?oa(fa):void 0,Jl=(P=ne.getAttribute("id"))!==null&&P!==void 0?P:(xt++).toString(10),Kl=pi==="video"?`${ca}p`:pi==="audio"?`${ha}Kbps`:da,Xl=`${Jl}@${Kl}`,Zl=(w=(T=(E=ne.querySelector("BaseURL"))===null||E===void 0?void 0:E.textContent)===null||T===void 0?void 0:T.trim())!==null&&w!==void 0?w:"",pa=new URL(Zl,e).toString(),eu=[...vt,...Hl,...ql];let fr;const tu=ne.querySelector("SegmentBase"),rt=(F=ne.querySelector("SegmentTemplate"))!==null&&F!==void 0?F:Yl;if(tu){const Mt=(I=(O=ne.querySelector("SegmentBase Initialization"))===null||O===void 0?void 0:O.getAttribute("range"))!==null&&I!==void 0?I:"",[Vt,mr]=Mt.split("-").map(st=>parseInt(st,10)),Ft={from:Vt,to:mr},Ut=(U=ne.querySelector("SegmentBase"))===null||U===void 0?void 0:U.getAttribute("indexRange"),[vr,mi]=Ut?Ut.split("-").map(st=>parseInt(st,10)):[],jt=Ut?{from:vr,to:mi}:void 0;fr={type:be.BYTE_RANGE,url:pa,initRange:Ft,indexRange:jt}}else if(rt){const Mt={representationId:(N=ne.getAttribute("id"))!==null&&N!==void 0?N:void 0,bandwidth:(_=ne.getAttribute("bandwidth"))!==null&&_!==void 0?_:void 0},Vt=parseInt((G=rt.getAttribute("timescale"))!==null&&G!==void 0?G:"",10),mr=(K=rt.getAttribute("initialization"))!==null&&K!==void 0?K:"",Ft=rt.getAttribute("media"),Ut=($=parseInt((te=rt.getAttribute("startNumber"))!==null&&te!==void 0?te:"",10))!==null&&$!==void 0?$:1,vr=Xr(mr,Mt);if(!Ft)throw new ReferenceError("No media attribute in SegmentTemplate");const mi=(D=rt.querySelectorAll("SegmentTimeline S"))!==null&&D!==void 0?D:[],jt=[];if(mi.length){let st=Ut,at=0;for(const Ht of mi){const St=parseInt((z=Ht.getAttribute("d"))!==null&&z!==void 0?z:"",10)*1e3,Gt=parseInt((ee=Ht.getAttribute("r"))!==null&&ee!==void 0?ee:"",10)||0,Yt=(ce=parseInt((ie=Ht.getAttribute("t"))!==null&&ie!==void 0?ie:"",10))!==null&&ce!==void 0?ce:void 0;for(let ma=0;ma<Gt+1;ma++){const iu=Xr(Ft,Object.assign(Object.assign({},Mt),{segmentNumber:st.toString(10),segmentTime:Yt.toString(10)})),ru=Yt?Yt/Vt:at;at+=St/Vt;const su=at;st++,jt.push({time:{from:ru,to:su},url:iu})}}}else if(a.isNonNullable(Ae)){const at=parseInt((Pe=rt.getAttribute("duration"))!==null&&Pe!==void 0?Pe:"",10)/Vt*1e3,Ht=Math.ceil(Ae/at);let St=0;for(let Gt=1;Gt<Ht;Gt++){const Yt=Xr(Ft,Object.assign(Object.assign({},Mt),{segmentNumber:Gt.toString(10),segmentTime:St.toString(10)}));jt.push({time:{from:St,to:St+at},url:Yt}),St+=at}}fr={type:be.TEMPLATE,baseUrl:pa,initUrl:vr,segments:jt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!pi||!Bt)continue;const pr={video:Se.VIDEO,audio:Se.AUDIO,text:Se.TEXT}[pi];pr&&ae[pr].push({id:Xl,kind:pr,segmentReference:fr,profiles:eu,duration:Ae,bitrate:ha,mime:Bt,codecs:da,width:zl,height:ca,fps:Ql,quality:Wl})}}return{duration:Ae,container:Ul,representations:ae}},Pb=["timeupdate","progress","play","seeked","stalled","waiting"];var ve;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(ve||(ve={}));let Ab=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new a.Subscription,this.state$=new Q(ve.NONE),this.currentVideoRepresentation$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.forceEnded$=new a.Subject,this.gapWatchdogStarted=!1,this.destroyController=new lt,this.initManifest=a.abortable(this.destroyController.signal,function(t,r){return Ee(this,arguments,function*(){this.element=t,this.state$.startTransitionTo(ve.MANIFEST_READY);const s=yield yield R(this.fetcher.fetchManifest(r).catch(l=>this.error$.next({id:"LoadManifest",category:a.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:l})));if(!s)return yield R(void 0);let n;try{n=kb(s!=null?s:"",r)}catch(l){this.error$.next({id:"ManifestParsing",category:a.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:l})}if(!n)return yield R(void 0);const o=({mime:l,codecs:d})=>{var u,c,h;return Boolean(((u=t.canPlayType)===null||u===void 0?void 0:u.call(t,l))&&((h=(c=window.MediaSource)===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0?void 0:h.call(c,`${l}; codecs="${d}"`)))};this.manifest=Object.assign(Object.assign({},n),{representations:oi(Object.entries(n.representations).map(([l,d])=>[l,d.filter(o)]))}),this.manifest.representations.video.length?this.state$.setState(ve.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:a.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this)),this.initRepresentations=a.abortable(this.destroyController.signal,function(t,r){return Ee(this,arguments,function*(){a.assertNonNullable(this.manifest),a.assertNonNullable(this.element),this.state$.startTransitionTo(ve.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0};this.videoBufferManager=new Un(Se.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(r)&&(this.audioBufferManager=new Un(Se.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,s),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));const n=a.merge(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(a.map(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),o=a.merge(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(a.map(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.subscription.add(a.merge(this.forceEnded$,a.combine({allBuffersFull:n,someBufferEnded:o}).pipe(a.filter(({allBuffersFull:l,someBufferEnded:d})=>l&&d))).subscribe(()=>{var l;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{(l=this.source)===null||l===void 0||l.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.subscription.add(a.merge(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.source.readyState!=="open"&&(yield yield R(new Promise(l=>{var d;return(d=this.source)===null||d===void 0?void 0:d.addEventListener("sourceopen",l)}))),a.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&a.isNonNullable(r)?yield yield R(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(r)])):yield yield R(this.videoBufferManager.startWith(t)),this.state$.setState(ve.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,r;if(!this.element||!this.videoBufferManager)return;const s=this.element.currentTime*1e3;this.videoBufferManager.maintain(s),(t=this.audioBufferManager)===null||t===void 0||t.maintain(s),(this.videoBufferManager.gaps.length||!((r=this.audioBufferManager)===null||r===void 0)&&r.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=a.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),n=>{this.error$.next({id:"GapWatchdog",category:a.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new $b({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initBuffer(){a.assertNonNullable(this.element),this.state$.setState(ve.RUNNING),this.subscription.add(a.merge(...Pb.map(e=>a.fromEvent(this.element,e)),a.fromEvent(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:a.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(a.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(a.fromEvent(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Ds(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}switchRepresentation(e,t){return J(this,void 0,void 0,function*(){const r={[Se.VIDEO]:this.videoBufferManager,[Se.AUDIO]:this.audioBufferManager,[Se.TEXT]:null}[e];return r==null?void 0:r.switchTo(t)})}seek(e,t){var r,s,n,o,l;a.assertNonNullable(this.element),a.assertNonNullable(this.videoBufferManager);let d;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?d=e:d=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!==null&&r!==void 0?r:e,(n=(s=this.audioBufferManager)===null||s===void 0?void 0:s.findSegmentStartTime(e))!==null&&n!==void 0?n:e),Ds(this.element.buffered,d)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)===null||o===void 0||o.abort()),this.videoBufferManager.maintain(d),(l=this.audioBufferManager)===null||l===void 0||l.maintain(d),this.element.currentTime=d/1e3}stop(){var e,t;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(e=this.videoBufferManager)===null||e===void 0||e.destroy(),this.videoBufferManager=null,(t=this.audioBufferManager)===null||t===void 0||t.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(ve.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3,t=[];for(const r of this.bufferManagers)for(const s of r.gaps)r.playingRepresentation$.getValue()===s.representation&&s.from<=e&&s.to>e&&(this.element.duration*1e3-s.to<this.tuning.endGapTolerance?t.push(1/0):t.push(s.to));if(t.length){const r=Math.max(...t);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=r/1e3}}};var X;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(X||(X={}));const wb=({id:i,width:e,height:t,bitrate:r,fps:s,quality:n})=>{var o;const l=(o=n?ci(n):void 0)!==null&&o!==void 0?o:pt({width:e,height:t});return l&&{id:i,quality:l,bitrate:r,size:{width:e,height:t},fps:s}},_b=({id:i,bitrate:e})=>({id:i,bitrate:e}),Rb=(i,e,t)=>{var r;const s=e.indexOf(t);return(r=xe(i,Math.round(i.length*s/e.length)))!==null&&r!==void 0?r:xe(i,-1)};class Ib{constructor(e){this.subscription=new a.Subscription,this.videoState=new Q(X.STOPPED),this.elementSize$=new a.ValueSubject(void 0),this.textTracksManager=new Oe,this.videoTracks=[],this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new MS,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(n.state===C.Requested&&(s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&t!==X.STOPPED&&r!==exports.PlaybackState.STOPPED&&this.seek(n.position,n.forcePrecise),r===exports.PlaybackState.STOPPED){t!==X.STOPPED&&(this.videoState.startTransitionTo(X.STOPPED),this.player.stop(),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(X.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(t){case X.STOPPED:this.videoState.startTransitionTo(X.READY),this.prepare();return;case X.READY:r===exports.PlaybackState.PAUSED?(this.videoState.setState(X.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(X.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.READY&&k(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case X.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(X.PAUSED),this.video.pause()):(s==null?void 0:s.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case X.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(X.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}}},this.params=e,this.video=Ge(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioTracksExist$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Ab({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,r=Ye(this.video),s=u=>{e.error$.next({id:"DashVKProvider",category:a.ErrorCategory.WTF,message:"DashVKProvider internal logic error",thrown:u})},n=(u,c)=>this.subscription.add(u.subscribe(c,s));n(r.timeUpdate$,e.position$),n(r.durationChange$,e.duration$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.lastRequestFirstBytes$.pipe(a.filter(a.isNonNullable),a.once(),a.mapTo(void 0)),e.firstBytesEvent$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(mt(this.video,t.isLooped,s)),this.subscription.add(He(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Ze(this.video,t.playbackRate,r.playbackRateState$,s)),n(Ji(this.video),this.elementSize$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(X.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(X.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(r.canplay$.subscribe(()=>{this.videoState.getState()===X.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var c;if(u===ve.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[];const h=this.player.getRepresentations();a.assertNonNullable(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((m,S)=>S.bitrate-m.bitrate),p=Array.from(h.video).sort((m,S)=>S.bitrate-m.bitrate);if(!this.params.tuning.isAudioDisabled)for(const m of f){const S=_b(m);S&&this.audioTracks.push({track:S,representation:m})}for(const m of p){const S=wb(m);if(S){this.videoTracks.push({track:S,representation:m});const b=!this.params.tuning.isAudioDisabled&&Rb(f,p,m);b&&this.audioRepresentations.set(m.id,b)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:m})=>m)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:m})=>m)),this.params.output.isAudioTracksExist$.next(!!this.audioTracks.length);const v=this.selectVideoRepresentation();a.assertNonNullable(v),this.player.initRepresentations(v.id,(c=this.audioRepresentations.get(v.id))===null||c===void 0?void 0:c.id)}else u===ve.REPRESENTATIOS_READY&&(this.videoState.setState(X.READY),this.player.initBuffer())},s));const o=u=>e.error$.next({id:"RepresentationSwitch",category:a.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(a.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,a.fromEvent(this.video,"progress")).subscribe(()=>{const u=this.player.state$.getState(),c=this.player.state$.getTransition();if(u!==ve.RUNNING||c||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const h=this.selectVideoRepresentation();if(h){this.player.switchRepresentation(Se.VIDEO,h.id).catch(o);const f=this.audioRepresentations.get(h.id);f&&this.player.switchRepresentation(Se.AUDIO,f.id).catch(o)}},s)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(a.filterChanged(),a.map(u=>{var c;return u&&((c=this.videoTracks.find(({representation:{id:h}})=>h===u))===null||c===void 0?void 0:c.track)})).subscribe(e.currentVideoTrack$,s)),this.textTracksManager.connect(this.video,t,e);const l=t.playbackState.stateChangeStarted$.pipe(a.map(({to:u})=>u===exports.PlaybackState.READY),a.filterChanged());this.subscription.add(a.merge(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const u=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(a.merge(l,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,s))}selectVideoRepresentation(){var e,t,r,s,n,o;const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.videoTrack.getState(),u=(e=this.videoTracks.find(({track:{id:b}})=>b===d))===null||e===void 0?void 0:e.track,c=this.params.output.currentVideoTrack$.getValue(),h=ot(this.video.buffered,this.video.currentTime*1e3),f=l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=Math.min(h/Math.min(f,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),v=Math.max(u&&!l&&(r=(t=this.audioRepresentations.get(u.id))===null||t===void 0?void 0:t.bitrate)!==null&&r!==void 0?r:0,c&&(n=(s=this.audioRepresentations.get(c.id))===null||s===void 0?void 0:s.bitrate)!==null&&n!==void 0?n:0),m=di(this.videoTracks.map(({track:b})=>b),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:p,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),S=l?m!=null?m:u:u!=null?u:m;return S&&((o=this.videoTracks.find(({track:b})=>b===S))===null||o===void 0?void 0:o.representation)}prepare(){return J(this,void 0,void 0,function*(){this.player.initManifest(this.video,this.params.source.url)})}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){et(this.video).then(e=>{e||(this.videoState.setState(X.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}}const Nb=5e3,Le={};var V;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(V||(V={}));const Ci=(i,e)=>new a.Observable(t=>{const r=(s,n)=>t.next(n);return i.on(e,r),()=>i.off(e,r)});class Cb{constructor(e){this.subscription=new a.Subscription,this.videoState=new Q(V.INITIALIZING),this.textTracksManager=new Oe,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(t!==V.INITIALIZING)switch((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===C.Requested&&this.seek(n.position),r){case exports.PlaybackState.STOPPED:switch(t){case V.STOPPED:break;case V.READY:case V.PLAYING:case V.PAUSED:this.stop();break;default:a.assertNever(t)}break;case exports.PlaybackState.READY:switch(t){case V.STOPPED:this.prepare();break;case V.READY:case V.PLAYING:case V.PAUSED:break;default:a.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case V.PLAYING:break;case V.STOPPED:this.prepare();break;case V.READY:case V.PAUSED:this.playIfAllowed();break;default:a.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case V.PAUSED:break;case V.STOPPED:this.prepare();break;case V.READY:this.videoState.setState(V.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case V.PLAYING:this.pause();break;default:a.assertNever(t)}break;default:a.assertNever(r)}},this.video=Ge(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioTracksExist$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)===null||e===void 0||e.detachMedia(),(t=this.hls)===null||t===void 0||t.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:a.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:s}),e=!0},r=window.setTimeout(()=>t("timeout"),Nb);dr(import("hls.js/dist/hls.min.js").then(s=>{e||(Le.Hls=s.default,Le.Events=s.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){a.assertNonNullable(Le.Hls,"hls.js not loaded"),this.hls=new Le.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(V.STOPPED)}subscribe(){a.assertNonNullable(Le.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:a.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},s=Ye(this.video),n=(u,c)=>this.subscription.add(u.subscribe(c,r));n(s.timeUpdate$,t.position$),n(s.durationChange$,t.duration$),n(s.ended$,t.endedEvent$),n(s.looped$,t.loopedEvent$),n(s.error$,t.error$),n(s.isBuffering$,t.isBuffering$),n(s.currentBuffer$,t.currentBuffer$),n(s.loadStart$,t.firstBytesEvent$),n(s.playing$,t.firstFrameEvent$),n(s.canplay$,t.canplay$),n(s.seeked$,t.seekedEvent$),this.subscription.add(mt(this.video,e.isLooped,r)),this.subscription.add(He(this.video,e.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ze(this.video,e.playbackRate,s.playbackRateState$,r)),this.subscription.add(Ci(this.hls,Le.Events.ERROR).subscribe(u=>{var c;u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:a.ErrorCategory.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${(c=u.err)===null||c===void 0?void 0:c.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(V.PLAYING),k(e.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(V.PAUSED),k(e.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===V.READY&&this.videoState.setState(V.READY),this.videoState.getState()===V.PLAYING&&this.playIfAllowed()},r)),n(Ci(this.hls,Le.Events.MANIFEST_PARSED).pipe(a.map(({levels:u})=>u.reduce((c,h)=>{var f,p;const v=h.name||h.height.toString(10),{width:m,height:S}=h,b=(p=ci((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&p!==void 0?p:pt({width:m,height:S});if(!b)return c;const g=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,P={id:v.toString(),quality:b,bitrate:h.bitrate/1e3,size:{width:m,height:S},fps:g};return this.trackLevels.set(v,{track:P,level:h}),c.push(P),c},[]))),t.availableVideoTracks$),n(Ci(this.hls,Le.Events.LEVEL_LOADING).pipe(a.map(({url:u})=>de(u))),t.hostname$),this.subscription.add(Ne(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:r}));const o=u=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:h})=>h===u))===null||c===void 0?void 0:c.track},l=Ci(this.hls,Le.Events.LEVEL_SWITCHED).pipe(a.map(({level:u})=>o(this.hls.levels[u])));l.pipe(a.filter(a.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Ne(e.videoTrack,()=>{var u;return(u=o(this.hls.levels[this.hls.currentLevel]))===null||u===void 0?void 0:u.id},u=>{var c;if(a.isNullable(u))return;const h=(c=this.trackLevels.get(u))===null||c===void 0?void 0:c.level;if(!h)return;const f=this.hls.levels.indexOf(h),p=this.hls.currentLevel,v=this.hls.levels[p];!v||h.bitrate>v.bitrate?this.hls.nextLevel=f:(this.hls.loadLevel=f,this.hls.loadLevel=f)},{changed$:l.pipe(a.map(u=>u==null?void 0:u.id)),onError:r})),n(s.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=a.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo(V.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return J(this,void 0,void 0,function*(){this.videoState.startTransitionTo(V.PLAYING),(yield et(this.video))||(this.videoState.setState(V.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(V.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.setAttribute("src",""),this.video.load(),this.videoState.setState(V.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const Hn="X-Playback-Duration";var Gn=i=>J(void 0,void 0,void 0,function*(){const e=yield Rt(i,{method:"HEAD"});return e.headers.has(Hn)?parseInt(e.headers.get(Hn),10):void 0});const Db=i=>{let e=null;if(i.QUALITY&&(e=ci(i.QUALITY)),!e&&i.RESOLUTION){const[t,r]=i.RESOLUTION.split("x").map(s=>parseInt(s,10));e=pt({width:t,height:r})}return e!=null?e:null},xl=(i,e=i)=>J(void 0,void 0,void 0,function*(){var t;const n=(yield(yield Rt(i)).text()).split(`
8
8
  `),o=[];for(let l=0;l<n.length;l++){const u=n[l].match(/^#EXT-X-STREAM-INF:(.+)/);if(!u)continue;const c=oi(u[1].split(",").map(b=>b.split("="))),h=(t=c.QUALITY)!==null&&t!==void 0?t:`stream-${c.BANDWIDTH}`,f=Db(c);let p;c.BANDWIDTH&&(p=parseInt(c.BANDWIDTH,10)/1e3||void 0),!p&&c["AVERAGE-BANDWIDTH"]&&(p=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const v=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0;let m;if(c.RESOLUTION){const[b,g]=c.RESOLUTION.split("x").map(P=>parseInt(P,10));b&&g&&(m={width:b,height:g})}const S=new URL(n[++l],e).toString();f&&o.push({id:h,quality:f,url:S,bandwidth:p,size:m,fps:v})}return o});var Y;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(Y||(Y={}));class Ob{constructor(e){var t;this.subscription=new a.Subscription,this.videoState=new Q(Y.STOPPED),this.textTracksManager=new Oe,this.manifests$=new a.ValueSubject([]),this.liveOffset=new na,this.manifestStartTime$=new a.ValueSubject(void 0),this.syncPlayback=()=>{const s=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(n===exports.PlaybackState.STOPPED){s!==Y.STOPPED&&(this.videoState.startTransitionTo(Y.STOPPED),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Y.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(s===Y.STOPPED){this.videoState.startTransitionTo(Y.READY),this.prepare();return}if(l||d){const h=this.videoState.getState();this.videoState.setState(Y.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),c.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&c.state===C.Requested){this.videoState.startTransitionTo(Y.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(s){case Y.READY:n===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):n===exports.PlaybackState.PAUSED?(this.videoState.setState(Y.PAUSED),this.liveOffset.pause(),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):n===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed());return;case Y.PLAYING:n===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Y.PAUSED),this.liveOffset.pause(),this.video.pause()):(o==null?void 0:o.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Y.PAUSED:n===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Y.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&&(k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case Y.CHANGING_MANIFEST:break;default:return a.assertNever(s)}},this.params=e,this.video=Ge(e.container),this.params.output.element$.next(this.video);const r={id:"master",quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([r]),xl(_t(this.params.source.url),this.params.source.url).then(s=>{this.manifests$.next([r,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),this.params.output.isLive$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioTracksExist$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.maxSeekBackTime$=new a.ValueSubject((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:r,videoTrack:s}=this.params.desiredState,n=r.getState(),o=s.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:s.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d)return;const u=n?"master":l;return n&&!o&&s.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,r=l=>{e.error$.next({id:"HlsLiveProvider",category:a.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:l})},s=Ye(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,r));n(s.ended$,e.endedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(He(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ze(this.video,t.playbackRate,s.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===Y.READY&&this.videoState.setState(Y.READY),this.videoState.getState()===Y.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(l=>-l/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(s.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&a.isNonNullable(u.to)){const h=u.to;this.params.desiredState.videoTrack.setState(h);const f=this.manifests$.getValue().find(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(de(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===Y.CHANGING_MANIFEST&&this.videoState.setState(d.to),l&&l.state===C.Requested&&this.seek(l.position)},r)),this.subscription.add(s.loadedData$.subscribe(()=>{var l,d,u;const c=(u=(d=(l=this.video)===null||l===void 0?void 0:l.getStartDate)===null||d===void 0?void 0:d.call(l))===null||u===void 0?void 0:u.getTime();this.manifestStartTime$.next(c||void 0)},r)),this.subscription.add(a.combine({startTime:this.manifestStartTime$.pipe(a.filter(a.isNonNullable)),currentTime:s.timeUpdate$}).subscribe(({startTime:l,currentTime:d})=>this.params.output.liveTime$.next(l+d*1e3),r)),this.subscription.add(this.manifests$.pipe(a.map(l=>l.map(({id:d,quality:u,size:c,bandwidth:h,fps:f})=>({id:d,quality:u,size:c,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,r));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();if(a.isNullable(e))return;const t=_t(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),Gn(t).then(r=>{var s;if(!a.isNullable(r))this.maxSeekBackTime$.next(r);else{const n=(s=this.params.source.maxSeekBackTime)!==null&&s!==void 0?s:this.maxSeekBackTime$.getValue();if(a.isNullable(n)||!isFinite(n))try{Rt(t).then(o=>o.text()).then(o=>{var l;const d=(l=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(o))===null||l===void 0?void 0:l[1];if(d){const u=new URL(d,t).toString();Gn(u).then(c=>{a.isNullable(c)||this.maxSeekBackTime$.next(c)})}})}catch(o){}}})}playIfAllowed(){et(this.video).then(e=>{e||(this.videoState.setState(Y.PAUSED),this.liveOffset.pause(),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next();const t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}}var W;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(W||(W={}));class Lb{constructor(e){this.subscription=new a.Subscription,this.videoState=new Q(W.STOPPED),this.textTracksManager=new Oe,this.manifests$=new a.ValueSubject([]),this.syncPlayback=()=>{const r=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s===exports.PlaybackState.STOPPED){r!==W.STOPPED&&(this.videoState.startTransitionTo(W.STOPPED),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(W.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.seekState.getState();if(r===W.STOPPED){this.videoState.startTransitionTo(W.READY),this.prepare();return}if(o||l){const c=this.videoState.getState();this.videoState.setState(W.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),u.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:h*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&u.state===C.Requested&&this.seek(u.position),r){case W.READY:s===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):s===exports.PlaybackState.PAUSED?(this.videoState.setState(W.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed());return;case W.PLAYING:s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(W.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case W.PAUSED:s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case W.CHANGING_MANIFEST:break;default:return a.assertNever(r)}},this.params=e,this.video=Ge(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([t]),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioTracksExist$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),xl(this.params.source.url).then(r=>{this.manifests$.next([t,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:r,videoTrack:s}=this.params.desiredState,n=r.getState(),o=s.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:s.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d)return;const u=n?"master":l;return n&&!o&&s.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,r=l=>{e.error$.next({id:"HlsProvider",category:a.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:l})},s=Ye(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d));n(s.timeUpdate$,e.position$),n(s.durationChange$,e.duration$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.seeked$,e.seekedEvent$),this.subscription.add(mt(this.video,t.isLooped,r)),this.subscription.add(He(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ze(this.video,t.playbackRate,s.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===W.READY&&this.videoState.setState(W.READY),this.videoState.getState()===W.PLAYING&&this.playIfAllowed()},r).add(s.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&a.isNonNullable(u.to)){const h=u.to;this.params.desiredState.videoTrack.setState(h);const f=this.manifests$.getValue().find(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(de(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===W.CHANGING_MANIFEST&&this.videoState.setState(d.to),l.state===C.Requested&&this.seek(l.position)},r))),this.subscription.add(this.manifests$.pipe(a.map(l=>l.map(({id:d,quality:u,size:c,bandwidth:h,fps:f})=>({id:d,quality:u,size:c,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,r));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();a.isNullable(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){et(this.video).then(e=>{e||(this.videoState.setState(W.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var Z;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(Z||(Z={}));class xb{constructor(e){this.subscription=new a.Subscription,this.videoState=new Q(Z.STOPPED),this.trackUrls={},this.textTracksManager=new Oe,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(r===exports.PlaybackState.STOPPED){t!==Z.STOPPED&&(this.videoState.startTransitionTo(Z.STOPPED),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Z.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.seekState.getState();if(t===Z.STOPPED){this.videoState.startTransitionTo(Z.READY),this.prepare();return}if(o){const{currentTime:d}=this.video;this.prepare(),l.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:d*1e3,forcePrecise:!0});return}switch((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&l.state===C.Requested&&this.seek(l.position),t){case Z.READY:r===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):r===exports.PlaybackState.PAUSED?(this.videoState.setState(Z.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed());return;case Z.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Z.PAUSED),this.video.pause()):(s==null?void 0:s.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Z.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.params=e,this.video=Ge(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach(([t,r],s)=>{const n=s.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:r}}),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioTracksExist$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,r=l=>{e.error$.next({id:"MpegProvider",category:a.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:l})},s=Ye(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,r));n(s.timeUpdate$,e.position$),n(s.durationChange$,e.duration$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.seeked$,e.seekedEvent$),this.subscription.add(mt(this.video,t.isLooped,r)),this.subscription.add(He(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Ze(this.video,t.playbackRate,s.playbackRateState$,r)),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(Z.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(Z.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===Z.READY&&this.videoState.setState(Z.READY);const d=this.params.desiredState.videoTrack.getTransition();d&&a.isNonNullable(d.to)&&(this.params.desiredState.videoTrack.setState(d.to),this.params.output.currentVideoTrack$.next(this.trackUrls[d.to].track)),this.videoState.getState()===Z.PLAYING&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);const o=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){var e,t;const r=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState();a.assertNonNullable(r,"MpegProvider: track is not selected");let{url:s}=this.trackUrls[r];a.assertNonNullable(s,`MpegProvider: No url for ${r}`),this.params.tuning.requestQuick&&(s=It(s)),this.video.setAttribute("src",s),this.video.load(),this.params.output.hostname$.next(de(s))}playIfAllowed(){et(this.video).then(e=>{e||(this.videoState.setState(Z.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}const Yn=["stun:videostun.mycdn.me:80"],Bb=1e3,Mb=3,Zr=()=>null;class Vb{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=Zr,this.externalStopCallback=Zr,this.externalErrorCallback=Zr,this.options=this.normalizeOptions(t);const r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return J(this,void 0,void 0,function*(){try{const t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return J(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:Yn}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return J(this,void 0,void 0,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return J(this,void 0,void 0,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:a.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return J(this,void 0,void 0,function*(){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return J(this,void 0,void 0,function*(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),Bb)}normalizeOptions(e={}){const t={stunServerList:Yn,maxRetryNumber:Mb,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var q;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(q||(q={}));class Fb{constructor(e){this.videoState=new Q(q.STOPPED),this.maxSeekBackTime$=new a.ValueSubject(0),this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(r===exports.PlaybackState.STOPPED){t!==q.STOPPED&&(this.videoState.startTransitionTo(q.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(q.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition();if(t===q.STOPPED){this.videoState.startTransitionTo(q.READY),this.prepare();return}if(o){this.prepare();return}switch(t){case q.READY:r===exports.PlaybackState.PAUSED?(this.videoState.setState(q.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed());return;case q.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(q.PAUSED),this.video.pause()):(s==null?void 0:s.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case q.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Ge(e.container),this.liveStreamClient=new Vb(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.video.remove(),this.params.output.element$.next(void 0),this.liveStreamClient.disconnect()}subscribe(){const{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"WebRTCLiveProvider",category:a.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:l})=>{this.log({message:`[videoState change] ${l}: ${JSON.stringify(o)}`})});const s=Ye(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,r));n(s.timeUpdate$,e.liveTime$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),this.subscription.add(s.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(s.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===q.READY&&this.videoState.setState(q.READY)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(q.PAUSED)},r)).add(s.playing$.subscribe(()=>{this.videoState.setState(q.PLAYING)},r)).add(s.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(He(this.video,t.volume,s.volumeState$,r)).add(s.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case q.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case q.READY:break;case q.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case q.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(o.to)}},r)).add(a.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(de(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioTracksExist$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:exports.VideoQuality.INVARIANT}),this.video.srcObject=e,k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(q.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:a.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){et(this.video).then(e=>{e||(this.videoState.setState(q.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}prepare(){this.liveStreamClient.connect()}}class qn{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return Boolean(this.current.done)}}var Ub=()=>{var i,e;const t=window.navigator;return t.userAgentData?((e=(i=t.userAgentData)===null||i===void 0?void 0:i.platform)===null||e===void 0?void 0:e.toLowerCase())==="android":window.navigator.userAgent.toLowerCase().includes("android")},es,ts,is,rs,ss,as,Di,ns,Oi,os,Li,ls,xi,us,Bi,ds;const Bl=Ub(),We=document.createElement("video"),ze={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&((ts=(es=window.SourceBuffer)===null||es===void 0?void 0:es.prototype)===null||ts===void 0?void 0:ts.appendBuffer)),hls:Boolean(((is=We.canPlayType)===null||is===void 0?void 0:is.call(We,"application/x-mpegurl"))||((rs=We.canPlayType)===null||rs===void 0?void 0:rs.call(We,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection)},Re={mp4:Boolean((ss=We.canPlayType)===null||ss===void 0?void 0:ss.call(We,"video/mp4")),webm:Boolean((as=We.canPlayType)===null||as===void 0?void 0:as.call(We,"video/webm"))},Qe={h264:Boolean((ns=(Di=window.MediaSource)===null||Di===void 0?void 0:Di.isTypeSupported)===null||ns===void 0?void 0:ns.call(Di,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean((os=(Oi=window.MediaSource)===null||Oi===void 0?void 0:Oi.isTypeSupported)===null||os===void 0?void 0:os.call(Oi,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean((ls=(Li=window.MediaSource)===null||Li===void 0?void 0:Li.isTypeSupported)===null||ls===void 0?void 0:ls.call(Li,'video/webm; codecs="vp9"')),aac:Boolean((us=(xi=window.MediaSource)===null||xi===void 0?void 0:xi.isTypeSupported)===null||us===void 0?void 0:us.call(xi,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean((ds=(Bi=window.MediaSource)===null||Bi===void 0?void 0:Bi.isTypeSupported)===null||ds===void 0?void 0:ds.call(Bi,'audio/webm; codecs="opus"'))},Jt=(Qe.h264||Qe.h265)&&Qe.aac,hr=ze.hls&&Re.mp4,jb=Boolean(window.WebSocket),Hb=()=>Object.keys(Qe).filter(i=>Qe[i]),Gb=(i,e=!1)=>i.filter(t=>{switch(t){case exports.VideoFormat.DASH:return ze.mse&&Re.mp4&&Jt;case exports.VideoFormat.DASH_SEP:return ze.mse&&Re.mp4&&Jt;case exports.VideoFormat.DASH_WEBM:return ze.mse&&Re.webm&&Qe.vp9&&Qe.opus;case exports.VideoFormat.DASH_LIVE:return ze.mse&&Re.mp4&&Jt;case exports.VideoFormat.DASH_ONDEMAND:return ze.mse&&Re.mp4&&Jt;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_ONDEMAND:return hr||e&&ze.mse&&Re.mp4&&Jt;case exports.VideoFormat.MPEG:return Re.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return ze.webrtc&&jb&&Qe.h264&&(Re.mp4||Re.webm);default:return a.assertNever(t)}}),Yb=()=>Bl?[exports.VideoFormat.MPEG,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND]:hr?[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG],qb=()=>Bl?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE]:hr?[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.DASH_LIVE]:[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.HLS_LIVE],zn=i=>i?[exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var zb=i=>new a.Observable(e=>{const t=new a.Subscription,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(a.map(({from:u,to:c})=>`${u}-${c}`)),s=i.desiredPlaybackState$.stateChangeEnded$,n=i.providerChanged$,o=new a.Subject;let l=0,d="unknown";return t.add(r.subscribe(u=>{l&&window.clearTimeout(l),d=u,l=window.setTimeout(()=>o.next(u),i.maxTransitionInterval)})),t.add(s.subscribe(()=>{window.clearTimeout(l),d="provider change",l=0})),t.add(n.subscribe(()=>{l&&(window.clearTimeout(l),l=window.setTimeout(()=>o.next(d),i.maxTransitionInterval))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const Wn={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},Wb={cacheDuration:12e4},Qb={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Jb={maxPausedTime:3e4},Kb={maxPausedTime:3e4};class Xb{constructor(e){this.current$=new a.ValueSubject({type:void 0}),this.providerError$=new a.Subject,this.noAvailableProvidersError$=new a.Subject,this.providerOutput={position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),volume$:new a.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new a.ValueSubject(void 0),availableVideoTracks$:new a.ValueSubject([]),availableAudioTracks$:new a.ValueSubject([]),isAudioTracksExist$:new a.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new a.ValueSubject(!1),currentBuffer$:new a.ValueSubject(void 0),isBuffering$:new a.ValueSubject(!0),error$:new a.Subject,willSeekEvent$:new a.Subject,seekedEvent$:new a.Subject,loopedEvent$:new a.Subject,endedEvent$:new a.Subject,firstBytesEvent$:new a.Subject,firstFrameEvent$:new a.Subject,canplay$:new a.Subject,isLive$:new a.ValueSubject(void 0),liveTime$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),element$:new a.ValueSubject(void 0)},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Gb([...qb(),...Yb()],this.params.tuning.useHlsJs).filter(o=>a.isNonNullable(e.sources[o])),{formatsToAvoid:r}=this.params.tuning,s=r.length?[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:t;this.screenFormatsIterator=new qn(s);const n=[...zn(!0),...zn(!1)];this.chromecastFormatsIterator=new qn(n.filter(o=>a.isNonNullable(e.sources[o])))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(a.isNullable(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(s){this.providerError$.next({id:"ProviderNotConstructed",category:a.ErrorCategory.WTF,message:"Failed to create provider",thrown:s})}r?this.current$.next({type:t,provider:r,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const e=this.current$.getValue().destination;a.assertNonNullable(e,"No current provider"),this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),s=r.state!==C.None;this.params.desiredState.seekState.setState({state:C.Requested,position:s?r.position:t,forcePrecise:s?r.forcePrecise:!1}),e.destroy();const n=this.providerOutput.isBuffering$;n.getValue()||n.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case he.SCREEN:return this.createScreenProvider(t);case he.CHROMECAST:return this.createChromecastProvider(t);default:return a.assertNever(e)}}createScreenProvider(e){const{sources:t,container:r,desiredState:s}=this.params,n=this.providerOutput,o={container:r,source:null,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new lb(Object.assign(Object.assign({},o),{source:l,config:Wb}))}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),this.params.tuning.useDashJs?new US(Object.assign(Object.assign({},o),{source:l,format:e,config:Kb})):new Ib(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),hr||!this.params.tuning.useHlsJs?new Lb(Object.assign(Object.assign({},o),{source:l})):new Cb(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.HLS_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Ob(Object.assign(Object.assign({},o),{source:l,config:Jb}))}case exports.VideoFormat.MPEG:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new xb(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new rb(Object.assign(Object.assign({},o),{source:l,config:Qb}))}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Fb({container:r,source:l,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:r,desiredState:s,meta:n}=this.params,o=this.providerOutput,l=this.params.dependencies.chromecastInitializer.connection$.getValue();return a.assertNonNullable(l),new hS({connection:l,meta:n,container:r,source:t,format:e,desiredState:s,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?he.CHROMECAST:he.SCREEN}chooseFormat(e){switch(e){case he.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case he.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return a.assertNever(e)}}skipFormat(e){switch(e){case he.SCREEN:return this.screenFormatsIterator.next();case he.CHROMECAST:return this.chromecastFormatsIterator.next();default:return a.assertNever(e)}}handleNoFormatsError(e){switch(e){case he.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case he.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return a.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const r=s=>{const n=new URL(s);return n.host=t,n.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return Object.assign(Object.assign({},e),{url:r(e.url)})}return oi(Object.entries(e).map(([s,n])=>[s,r(n)]))}initProviderErrorHandling(){const e=new a.Subscription;let t=!1,r=0;return e.add(a.merge(this.providerOutput.error$,zb({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:Wn.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(a.filter(({type:s})=>s!==void 0))}).pipe(a.map(s=>({id:`ProviderHangup:${s}`,category:a.ErrorCategory.WTF,message:`A ${s} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const s=this.params.desiredState.playbackState.transitionEnded$.pipe(a.filter(({to:n})=>n===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>t=!0);e.add(s)})),e.add(this.providerError$.subscribe(s=>{if(this.current$.getValue().destination===he.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=s.category===a.ErrorCategory.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=r<Wn.providerErrorLimit;o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(r++,this.reinitProvider()):this.switchToNextProvider()}})),e}}var ge;(function(i){i[i.LOCAL_STORAGE=0]="LOCAL_STORAGE",i[i.SESSION_STORAGE=1]="SESSION_STORAGE",i[i.RUNTIME=2]="RUNTIME"})(ge||(ge={}));const Ml=new Map;let ut=ge.RUNTIME;const cs=`vk-videoplayer-dummy-key-${Math.random()}`,Zb=()=>{try{localStorage.setItem(cs,"test"),localStorage.removeItem(cs),ut=ge.LOCAL_STORAGE}catch(i){if(i instanceof DOMException||i instanceof TypeError)try{sessionStorage.getItem(cs),ut=ge.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)ut=ge.RUNTIME;else throw e}else throw i}};Zb();const eg=i=>{var e,t;switch(ut){case ge.LOCAL_STORAGE:return(e=localStorage.getItem(i))!==null&&e!==void 0?e:void 0;case ge.SESSION_STORAGE:return(t=sessionStorage.getItem(i))!==null&&t!==void 0?t:void 0;case ge.RUNTIME:return Ml.get(i);default:a.assertNever(ut)}},Qn=(i,e)=>{switch(ut){case ge.LOCAL_STORAGE:try{localStorage.setItem(i,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case ge.SESSION_STORAGE:try{sessionStorage.setItem(i,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case ge.RUNTIME:return void Ml.set(i,e);default:a.assertNever(ut)}},Os=(i,e,t)=>t*e+(1-t)*i,Vl=(i,e)=>i.reduce((t,r)=>t+r,0)/e,tg=(i,e,t,r)=>{let s=0,n=t;const o=Vl(i,e),l=e<r?e:r;for(let d=0;d<l;d++)i[n]>o?s++:s--,n=(i.length+n-1)%i.length;return Math.abs(s)===l};class Fl{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 a.ValueSubject(e.initial),this.debounced$=new a.ValueSubject(e.initial);const r=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ie(`raw_${r}`),this.smoothedSeries$=new Ie(`smoothed_${r}`),this.reportedSeries$=new Ie(`reported_${r}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let l=0;l<this.pastMeasures.length;l++)this.pastMeasures[l]!==void 0&&(t+=Math.pow(this.pastMeasures[l]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;const s=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*s,o=this.smoothed-this.params.deviationFactor*s;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>n||this.smoothed<o)&&(a.isNullable(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class ig extends Fl{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Os(this.slow,e,this.params.emaAlphaSlow),this.fast=Os(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class rg extends Fl{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Vl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Os(this.emaSmoothed,e,this.params.emaAlpha);const r=tg(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}}class Jn{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new ig({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new rg({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}}const sg=5e3,Kn="one_video_throughput",Xn="one_video_rtt",Fe=window.navigator.connection,Zn=()=>{const i=Fe==null?void 0:Fe.downlink;if(a.isNonNullable(i)&&i!==10)return i*1e3},eo=()=>{const i=Fe==null?void 0:Fe.rtt;if(a.isNonNullable(i)&&i!==3e3)return i},to=(i,e,t)=>{const r=t*8,s=r/i;return r/(s+e)};class ti{constructor(e){var t,r;this.subscription=new a.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const s=ti.load(Kn)||(e.useBrowserEstimation?Zn():void 0)||sg,n=(r=(t=ti.load(Xn))!==null&&t!==void 0?t:e.useBrowserEstimation?eo():void 0)!==null&&r!==void 0?r:0;if(this.throughput$=new a.ValueSubject(s),this.rtt$=new a.ValueSubject(n),this.rttAdjustedThroughput$=new a.ValueSubject(to(s,n,e.rttPenaltyRequestSize)),this.throughput=Jn.getSmoothedValue(s,-1,e),this.rtt=Jn.getSmoothedValue(n,1,e),e.useBrowserEstimation){const o=()=>{const d=Zn();d&&this.throughput.next(d);const u=eo();a.isNonNullable(u)&&this.rtt.next(u)};Fe&&"onchange"in Fe&&this.subscription.add(a.fromEvent(Fe,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{Qn(Kn,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{Qn(Xn,o.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(a.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(a.map(({throughput:o,rtt:l})=>to(o,l,e.rttPenaltyRequestSize)),a.filter(o=>{const l=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(o-l)/l>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=a.now();const s=new a.Subscription;switch(this.subscription.add(s),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:s.add(a.fromEvent(e,"progress").pipe(a.once()).subscribe(n=>{t=n.loaded,r=a.now()}));break;case 1:case 0:s.add(a.fromEvent(e,"loadstart").subscribe(()=>{t=0,r=a.now()}));break}s.add(a.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,l=a.now(),d=o-t,u=l-r;this.addRawSpeed(d,u,1)}this.concurrentDownloads.delete(e),s.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let r=0;const s=a.now();let n=0,o=a.now();const l=u=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${u}`).catch(()=>{})},d=({done:u,value:c})=>J(this,void 0,void 0,function*(){u?(this.addRawSpeed(r,a.now()-s,1),this.concurrentDownloads.delete(e)):c&&(r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&a.now()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,a.now()-o,this.concurrentDownloads.size),n=0,o=a.now()),yield t==null?void 0:t.read().then(d,l))});this.concurrentDownloads.add(e),t==null||t.read().then(d,l)}addRawSpeed(e,t,r=1){if(ti.sanityCheck(e,t)){const s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||e<10*1024||t<=20)}static load(e){var t;const r=eg(e);if(a.isNonNullable(r))return(t=parseInt(r,10))!==null&&t!==void 0?t:void 0}}const io={throughputEstimator:{type:"TwoEma",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:.3,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableTelemetryAtStart:!1,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useHlsJs:!0,isAudioDisabled:!1,webrtc:{connectionRetryMaxNumber:3}},ag=i=>{const e={};for(const t of Object.keys(io)){const r=io[t],s=i[t];Array.isArray(r)&&Array.isArray(s)?e[t]=s:typeof r=="object"&&typeof s=="object"?e[t]=Object.assign(Object.assign({},r),s):e[t]=s!=null?s:r}return e};var ng=({seekState:i,position$:e})=>a.merge(i.stateChangeEnded$.pipe(a.map(({to:t})=>{var r;return t.state===C.None?void 0:((r=t.position)!==null&&r!==void 0?r:NaN)/1e3}),a.filter(a.isNonNullable)),e.pipe(a.filter(()=>i.getState().state===C.None))),og=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return a.assertNonNullable(e,`Wrong container or containerId {${i.container}}`),e};const ro=({playbackState:i,seekState:e,playbackAbort$:t,looped$:r,position$:s})=>new a.Observable(n=>{let o;const l=i.transitionEnded$.pipe(a.filter(p=>(p.from===exports.PlaybackState.PAUSED||p.from===exports.PlaybackState.STOPPED)&&p.to===exports.PlaybackState.PLAYING)),d=i.stateChangeEnded$.pipe(a.filter(p=>p.from===exports.PlaybackState.PLAYING&&p.to===exports.PlaybackState.PAUSED)),u=e.stateChangeEnded$.pipe(a.filter(({to:p})=>{var v,m;return p.state===C.Requested&&((m=(v=i.getTransition())===null||v===void 0?void 0:v.from)!==null&&m!==void 0?m:i.getState())===exports.PlaybackState.PLAYING})),c=e.stateChangeEnded$.pipe(a.filter(({from:p,to:v})=>{var m,S;return p.state===C.Applying&&v.state===C.None&&((S=(m=i.getTransition())===null||m===void 0?void 0:m.from)!==null&&S!==void 0?S:i.getState())===exports.PlaybackState.PLAYING})),h=a.merge(l,c).pipe(a.map(()=>s.getValue()),a.filter(a.isNonNullable)),f=a.merge(a.merge(d,u,t),r).pipe(a.map(()=>s.getValue()),a.filter(a.isNonNullable));return new a.Subscription().add(h.subscribe(p=>{o=p})).add(f.subscribe(p=>{if(a.isNullable(o)||o===p)return;const v={from:o,to:p};o=void 0,n.next(v)}))});class lg{constructor(e={}){if(this.subscription=new a.Subscription,this.logger=new a.Logger,this.isPlaybackStarted=!1,this.desiredState={playbackState:new Q(exports.PlaybackState.STOPPED),seekState:new Q({state:C.None}),volume:new Q({volume:1,muted:!1}),videoTrack:new Q(void 0),autoVideoTrackSwitching:new Q(!0),autoVideoTrackLimits:new Q({}),isLooped:new Q(!1),playbackRate:new Q(1),externalTextTracks:new Q([]),currentTextTrack:new Q(void 0),textTrackCuesSettings:new Q({})},this.info={playbackState$:new a.ValueSubject(exports.PlaybackState.STOPPED),position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),muted$:new a.ValueSubject(!1),volume$:new a.ValueSubject(1),availableQualities$:new a.ValueSubject([]),availableQualitiesFps$:new a.ValueSubject({}),availableAudioTracks$:new a.ValueSubject([]),isAudioTracksExist$:new a.ValueSubject(!0),currentQuality$:new a.ValueSubject(void 0),isAutoQualityEnabled$:new a.ValueSubject(!0),autoQualityLimitingAvailable$:new a.ValueSubject(!1),autoQualityLimits$:new a.ValueSubject({}),currentPlaybackRate$:new a.ValueSubject(1),currentBuffer$:new a.ValueSubject({start:0,end:0}),isBuffering$:new a.ValueSubject(!0),isStalled$:new a.ValueSubject(!1),isEnded$:new a.ValueSubject(!1),isLooped$:new a.ValueSubject(!1),isLive$:new a.ValueSubject(void 0),liveTime$:new a.ValueSubject(void 0),currentFormat$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),throughputEstimation$:new a.ValueSubject(void 0),rttEstimation$:new a.ValueSubject(void 0),videoBitrate$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),chromecastState$:new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new a.ValueSubject(void 0),intrinsicVideoSize$:new a.ValueSubject(void 0)},this.events={inited$:new a.Subject,started$:new a.Subject,willPause$:new a.Subject,willResume$:new a.Subject,willDestruct$:new a.Subject,watchCoverageRecord$:new a.Subject,watchCoverageLive$:new a.Subject,managedError$:new a.Subject,fatalError$:new a.Subject,ended$:new a.Subject,looped$:new a.Subject,seeked$:new a.Subject,willSeek$:new a.Subject,firstBytes$:new a.Subject,firstFrame$:new a.Subject,canplay$:new a.Subject,log$:new a.Subject},this.experimental={element$:new a.ValueSubject(void 0),enableDebugTelemetry$:new a.ValueSubject(!1),dumpTelemetry:LS},this.initLogs(),this.tuning=ag(e),this.chromecastInitializer=new mu({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new ti(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,r,s)=>{const n=Reflect.get(t,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(l){const d=o.map(h=>JSON.stringify(h,(f,p)=>{const v=typeof p;return["number","string","boolean"].includes(v)?p:p===null?null:`<${v}>`})),u=`Player.${String(r)}`,c=`Exception calling ${u} (${d.join(", ")})`;throw this.events.fatalError$.next({id:u,category:a.ErrorCategory.WTF,message:c,thrown:l}),l}}}})}initVideo(e){var t,r,s;return this.config=e,this.domContainer=og(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Xb({sources:e.sources,meta:(r=e.meta)!==null&&r!==void 0?r:{},failoverHosts:(s=e.failoverHosts)!==null&&s!==void 0?s:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.initDebugTelemetry(),this}destroy(){var e;this.events.willDestruct$.next(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.READY),this}play(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PLAYING&&e.startTransitionTo(exports.PlaybackState.PLAYING),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PAUSED&&e.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(e,t=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:C.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:this.desiredState.volume.getState().muted}),this}setMuted(e){return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(e):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:e}),this}setQuality(e){a.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const r=t.find(s=>s.quality===e);return r&&this.desiredState.videoTrack.startTransitionTo(r.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.setState(e),this}setPlaybackRate(e){var t;a.assertNonNullable(this.providerContainer);const r=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return r&&(this.desiredState.playbackRate.setState(e),r.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>Object.assign({type:"external"},t))),this}selectTextTrack(e){var t;return(e===void 0||!((t=this.providerContainer)===null||t===void 0)&&t.providerOutput.availableTextTracks$.getValue().find(r=>r.id===e))&&this.desiredState.currentTextTrack.startTransitionTo(e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){a.assertNonNullable(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(a.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),r=t.state===C.None?void 0:t.position;return a.isNonNullable(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}setIntrinsicVideoSize(...e){const t={width:e.reduce((r,{width:s})=>r||s||0,0),height:e.reduce((r,{height:s})=>r||s||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(a.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(a.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(a.filter(({from:e})=>e===exports.PlaybackState.STOPPED),a.once()).subscribe(()=>{this.initedAt=a.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.pipe(a.filter(()=>!this.isPlaybackStarted),a.filter(e=>e.to===exports.PlaybackState.PLAYING)).subscribe(()=>{this.isPlaybackStarted=!0,this.events.started$.next()})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted&&this.events.willResume$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const d=this.desiredState.seekState.getState();d.state===C.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},d),{state:C.Applying})):this.events.managedError$.next({id:`WillSeekIn${d.state}`,category:a.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===C.Applying&&(this.desiredState.seekState.setState({state:C.None}),this.events.seeked$.next())})).add(e.current$.pipe(a.map(d=>d.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(a.map(d=>d.destination),a.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(a.map(d=>d.map(({quality:u})=>u).sort((u,c)=>Wi(u)?1:Wi(c)?-1:Ui(c,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(d=>{const u={};for(const c of d)c.fps&&(u[c.quality]=c.fps);this.info.availableQualitiesFps$.next(u)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioTracksExist$.subscribe(this.info.isAudioTracksExist$)).add(e.providerOutput.currentVideoTrack$.subscribe(d=>{this.info.currentQuality$.next(d==null?void 0:d.quality),this.info.videoBitrate$.next(d==null?void 0:d.bitrate)})).add(e.providerOutput.hostname$.pipe(a.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(a.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(a.filterChanged()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.currentBuffer$.pipe(a.map(d=>d?{start:d.from,end:d.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(a.map(d=>d.muted),a.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(a.map(d=>d.volume),a.filterChanged()).subscribe(this.info.volume$)).add(ng({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(a.merge(e.providerOutput.endedEvent$.pipe(a.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(a.mapTo(!1))).pipe(a.filterChanged()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(a.map(d=>({id:"NoProviders",category:a.ErrorCategory.VIDEO_PIPELINE,message:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const t=new a.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const r=new a.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(a.filter(({to:d})=>d===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>r.next(!1)));let s=0;const n=a.merge(e.providerOutput.isBuffering$,t,r).pipe(a.map(()=>{const d=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||r.getValue();return d&&!u}),a.filterChanged());this.subscription.add(n.subscribe(d=>{d?s=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(s),this.info.isStalled$.next(!1))}));const o=new a.Subscription;this.subscription.add(o);const l=a.merge(a.fromEvent(window,"beforeunload"),this.events.willDestruct$,e.current$.pipe(a.filter(d=>Boolean(d==null?void 0:d.provider))));e.providerOutput.isLive$.pipe(a.filterChanged()).subscribe(d=>{switch(a.assertNonNullable(this.providerContainer),o.unsubscribe(),d){case!0:{const u=new a.ValueSubject(void 0);o.add(this.providerContainer.providerOutput.liveTime$.subscribe(c=>u.next(c&&Math.floor(c/1e3)))),o.add(ro({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:l,looped$:this.events.looped$,position$:u}).pipe(a.map(({from:c,to:h})=>({start:c,end:h}))).subscribe(this.events.watchCoverageLive$));break}case!1:o.add(ro({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:l,position$:this.providerContainer.providerOutput.position$}).pipe(a.map(({from:u,to:c})=>({start:u,end:c}))).subscribe(this.events.watchCoverageRecord$));break}}),this.subscription.add(a.merge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const d=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:d==null?void 0:d.videoWidth,height:d==null?void 0:d.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(d=>{var u,c;const h=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=d==null?void 0:d.size)===null||u===void 0?void 0:u.width,height:(c=d==null?void 0:d.size)===null||c===void 0?void 0:c.height},{width:h==null?void 0:h.videoWidth,height:h==null?void 0:h.videoHeight})}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(a.map(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new a.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(a.filterChanged((r,s)=>r.provider===s.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(a.filter(r=>r.length>0),a.once()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:r})=>r===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=di(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0})),this.desiredState.videoTrack.startTransitionTo(t.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(a.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(a.map(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;a.assertNonNullable(this.providerContainer),a.assertNonNullable(t),OS(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>DS(r)),this.providerContainer.current$.subscribe(({type:r})=>Ri("provider",r)),t.duration$.subscribe(r=>Ri("duration",r)),t.availableVideoTracks$.pipe(a.filter(r=>!!r.length),a.once()).subscribe(r=>Ri("tracks",r)),this.events.fatalError$.subscribe(new Ie("fatalError")),this.events.managedError$.subscribe(new Ie("managedError")),t.position$.subscribe(new Ie("position")),t.currentVideoTrack$.pipe(a.map(r=>r==null?void 0:r.quality)).subscribe(new Ie("quality")),this.info.currentBuffer$.subscribe(new Ie("buffer")),t.isBuffering$.subscribe(new Ie("isBuffering"))].forEach(r=>this.subscription.add(r)),Ri("codecs",Hb())}}const ug=`${fu}@${hu}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return a.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return a.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return a.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return a.ValueSubject}});exports.Player=lg;exports.SDK_VERSION=ug;