@vkontakte/videoplayer-core 2.0.94 → 2.0.95

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/es2018.esm.js CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.94
3
- * Mon, 11 Dec 2023 14:20:28 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-94/doc/
2
+ * @vkontakte/videoplayer-core v2.0.95
3
+ * Tue, 12 Dec 2023 10:39:51 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-95/doc/
5
5
  */
6
- import{ValueSubject as S,Subject as L,Subscription as re,isNonNullable as _,ErrorCategory as C,isNullable as te,fromEvent as B,assertNever as V,merge as U,tap as ts,map as w,observableFrom as ke,filterChanged as fe,assertNonNullable as P,debounce as Me,getHighestQuality as hd,timeout as fd,getCurrentBrowser as Br,CurrentClientBrowser as Mn,combine as Ie,once as me,mapTo as Wt,filter as se,now as pe,videoSizeToQuality as Rt,isInvariantQuality as vi,isHigher as pi,isLower as Ki,isHigherOrEqual as Tr,isLowerOrEqual as Nn,Observable as cs,interval as is,VideoQuality as Ce,videoQualityToHeight as pd,abortable as Re,getExponentialDelay as fa,throttle as md,CurrentClientDevice as vd,safeStorage as Cs,fillWithDefault as gd,Logger as Sd}from"@vkontakte/videoplayer-shared/es2018.esm.js";import{Observable as Zv,Subject as eg,Subscription as tg,ValueSubject as ig,VideoQuality as sg}from"@vkontakte/videoplayer-shared/es2018.esm.js";import bd from"lodash/debounce.js";const yd="2.0.94";var p;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(p||(p={}));var y;(function(s){s.MPEG="MPEG",s.DASH="DASH",s.DASH_SEP="DASH_SEP",s.DASH_SEP_VK="DASH_SEP",s.DASH_WEBM="DASH_WEBM",s.DASH_WEBM_AV1="DASH_WEBM_AV1",s.DASH_WEBM_VK="DASH_WEBM",s.DASH_ONDEMAND="DASH_ONDEMAND",s.DASH_ONDEMAND_VK="DASH_ONDEMAND",s.DASH_LIVE="DASH_LIVE",s.DASH_LIVE_CMAF="DASH_LIVE_CMAF",s.DASH_LIVE_WEBM="DASH_LIVE_WEBM",s.HLS="HLS",s.HLS_ONDEMAND="HLS_ONDEMAND",s.HLS_JS="HLS",s.HLS_LIVE="HLS_LIVE",s.HLS_LIVE_CMAF="HLS_LIVE_CMAF",s.WEB_RTC_LIVE="WEB_RTC_LIVE"})(y||(y={}));var Ee;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(Ee||(Ee={}));var ye;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})(ye||(ye={}));var gi;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(gi||(gi={}));var z;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(z||(z={}));var gt;(function(s){s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip"})(gt||(gt={}));var Td=s=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class Ed{constructor(e){var t;this.connection$=new S(void 0),this.castState$=new S(ye.NOT_AVAILABLE),this.errorEvent$=new L,this.realCastState$=new S(ye.NOT_AVAILABLE),this.subscription=new re,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const i="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${i}`}),e.isDisabled||!i)return;const r=_((t=window.chrome)===null||t===void 0?void 0:t.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||Td("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:C.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())===null||i===void 0?void 0:i.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||a===void 0||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){_(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();te(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();te(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(B(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(a=i.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return V(r.sessionState)}})).add(U(B(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(ts(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),w(r=>r.castState)),ke([i.getCastState()])).pipe(fe(),w($d),ts(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===ye.CONNECTED,o=_(this.connection$.getValue());if(n&&!o){const u=i.getCurrentSession();P(u);const d=u.getCastDevice(),l=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(te(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===ye.CONNECTED?_(this.connection$.getValue())?ye.CONNECTED:ye.AVAILABLE:r)}))}initializeCastApi(){var e;let t,i,r;try{t=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:i,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:C.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const $d=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return ye.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return ye.AVAILABLE;case cast.framework.CastState.CONNECTING:return ye.CONNECTING;case cast.framework.CastState.CONNECTED:return ye.CONNECTED;default:return V(s)}};var Os=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Mr(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var nt=function(s){try{return!!s()}catch(e){return!0}},Ad=nt,hs=!Ad(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),Fn=hs,Un=Function.prototype,Er=Un.call,kd=Fn&&Un.bind.bind(Er,Er),ot=Fn?kd:function(s){return function(){return Er.apply(s,arguments)}},Vn=ot,wd=Vn({}.toString),_d=Vn("".slice),fs=function(s){return _d(wd(s),8,-1)},Pd=ot,Dd=nt,Rd=fs,Bs=Object,Id=Pd("".split),xd=Dd(function(){return!Bs("z").propertyIsEnumerable(0)})?function(s){return Rd(s)=="String"?Id(s,""):Bs(s)}:Bs,ps=function(s){return s==null},Ld=ps,Cd=TypeError,Nr=function(s){if(Ld(s))throw Cd("Can't call method on "+s);return s},Od=xd,Bd=Nr,Ti=function(s){return Od(Bd(s))},Zt={},xi=function(s){return s&&s.Math==Math&&s},Ye=xi(typeof globalThis=="object"&&globalThis)||xi(typeof window=="object"&&window)||xi(typeof self=="object"&&self)||xi(typeof Os=="object"&&Os)||function(){return this}()||Os||Function("return this")(),$r=typeof document=="object"&&document.all,Md=typeof $r=="undefined"&&$r!==void 0,Hn={all:$r,IS_HTMLDDA:Md},Gn=Hn,Nd=Gn.all,Ne=Gn.IS_HTMLDDA?function(s){return typeof s=="function"||s===Nd}:function(s){return typeof s=="function"},Fd=Ye,Ud=Ne,pa=Fd.WeakMap,Vd=Ud(pa)&&/native code/.test(String(pa)),ma=Ne,Yn=Hn,Hd=Yn.all,It=Yn.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:ma(s)||s===Hd}:function(s){return typeof s=="object"?s!==null:ma(s)},Gd=nt,xt=!Gd(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),ei={},Yd=Ye,va=It,Ar=Yd.document,qd=va(Ar)&&va(Ar.createElement),qn=function(s){return qd?Ar.createElement(s):{}},jd=xt,zd=nt,Wd=qn,jn=!jd&&!zd(function(){return Object.defineProperty(Wd("div"),"a",{get:function(){return 7}}).a!=7}),Qd=xt,Kd=nt,zn=Qd&&Kd(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Jd=It,Xd=String,Zd=TypeError,Lt=function(s){if(Jd(s))return s;throw Zd(Xd(s)+" is not an object")},eu=hs,Li=Function.prototype.call,dt=eu?Li.bind(Li):function(){return Li.apply(Li,arguments)},Fr={},Ms=Fr,Ns=Ye,tu=Ne,ga=function(s){return tu(s)?s:void 0},Ur=function(s,e){return arguments.length<2?ga(Ms[s])||ga(Ns[s]):Ms[s]&&Ms[s][e]||Ns[s]&&Ns[s][e]},iu=ot,Vr=iu({}.isPrototypeOf),su=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Wn=Ye,Fs=su,Sa=Wn.process,ba=Wn.Deno,ya=Sa&&Sa.versions||ba&&ba.version,Ta=ya&&ya.v8,Ve,ss;Ta&&(Ve=Ta.split("."),ss=Ve[0]>0&&Ve[0]<4?1:+(Ve[0]+Ve[1]));!ss&&Fs&&(Ve=Fs.match(/Edge\/(\d+)/),(!Ve||Ve[1]>=74)&&(Ve=Fs.match(/Chrome\/(\d+)/),Ve&&(ss=+Ve[1])));var ru=ss,Ea=ru,au=nt,nu=Ye,ou=nu.String,Qn=!!Object.getOwnPropertySymbols&&!au(function(){var s=Symbol();return!ou(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Ea&&Ea<41}),du=Qn,Kn=du&&!Symbol.sham&&typeof Symbol.iterator=="symbol",uu=Ur,lu=Ne,cu=Vr,hu=Kn,fu=Object,Jn=hu?function(s){return typeof s=="symbol"}:function(s){var e=uu("Symbol");return lu(e)&&cu(e.prototype,fu(s))},pu=String,Hr=function(s){try{return pu(s)}catch(e){return"Object"}},mu=Ne,vu=Hr,gu=TypeError,Gr=function(s){if(mu(s))return s;throw gu(vu(s)+" is not a function")},Su=Gr,bu=ps,ms=function(s,e){var t=s[e];return bu(t)?void 0:Su(t)},Us=dt,Vs=Ne,Hs=It,yu=TypeError,Tu=function(s,e){var t,i;if(e==="string"&&Vs(t=s.toString)&&!Hs(i=Us(t,s))||Vs(t=s.valueOf)&&!Hs(i=Us(t,s))||e!=="string"&&Vs(t=s.toString)&&!Hs(i=Us(t,s)))return i;throw yu("Can't convert object to primitive value")},Xn={exports:{}},$a=Ye,Eu=Object.defineProperty,$u=function(s,e){try{Eu($a,s,{value:e,configurable:!0,writable:!0})}catch(t){$a[s]=e}return e},Au=Ye,ku=$u,Aa="__core-js_shared__",wu=Au[Aa]||ku(Aa,{}),Zn=wu,ka=Zn;(Xn.exports=function(s,e){return ka[s]||(ka[s]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"});var eo=Xn.exports,_u=Nr,Pu=Object,vs=function(s){return Pu(_u(s))},Du=ot,Ru=vs,Iu=Du({}.hasOwnProperty),ut=Object.hasOwn||function(e,t){return Iu(Ru(e),t)},xu=ot,Lu=0,Cu=Math.random(),Ou=xu(1 .toString),to=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Ou(++Lu+Cu,36)},Bu=Ye,Mu=eo,wa=ut,Nu=to,Fu=Qn,Uu=Kn,qt=Bu.Symbol,Gs=Mu("wks"),Vu=Uu?qt.for||qt:qt&&qt.withoutSetter||Nu,qe=function(s){return wa(Gs,s)||(Gs[s]=Fu&&wa(qt,s)?qt[s]:Vu("Symbol."+s)),Gs[s]},Hu=dt,_a=It,Pa=Jn,Gu=ms,Yu=Tu,qu=qe,ju=TypeError,zu=qu("toPrimitive"),Wu=function(s,e){if(!_a(s)||Pa(s))return s;var t=Gu(s,zu),i;if(t){if(e===void 0&&(e="default"),i=Hu(t,s,e),!_a(i)||Pa(i))return i;throw ju("Can't convert object to primitive value")}return e===void 0&&(e="number"),Yu(s,e)},Qu=Wu,Ku=Jn,Yr=function(s){var e=Qu(s,"string");return Ku(e)?e:e+""},Ju=xt,Xu=jn,Zu=zn,Ci=Lt,Da=Yr,el=TypeError,Ys=Object.defineProperty,tl=Object.getOwnPropertyDescriptor,qs="enumerable",js="configurable",zs="writable";ei.f=Ju?Zu?function(e,t,i){if(Ci(e),t=Da(t),Ci(i),typeof e=="function"&&t==="prototype"&&"value"in i&&zs in i&&!i[zs]){var r=tl(e,t);r&&r[zs]&&(e[t]=i.value,i={configurable:js in i?i[js]:r[js],enumerable:qs in i?i[qs]:r[qs],writable:!1})}return Ys(e,t,i)}:Ys:function(e,t,i){if(Ci(e),t=Da(t),Ci(i),Xu)try{return Ys(e,t,i)}catch(r){}if("get"in i||"set"in i)throw el("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var gs=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},il=xt,sl=ei,rl=gs,Ei=il?function(s,e,t){return sl.f(s,e,rl(1,t))}:function(s,e,t){return s[e]=t,s},al=eo,nl=to,Ra=al("keys"),qr=function(s){return Ra[s]||(Ra[s]=nl(s))},jr={},ol=Vd,io=Ye,dl=It,ul=Ei,Ws=ut,Qs=Zn,ll=qr,cl=jr,Ia="Object already initialized",kr=io.TypeError,hl=io.WeakMap,rs,Si,as,fl=function(s){return as(s)?Si(s):rs(s,{})},pl=function(s){return function(e){var t;if(!dl(e)||(t=Si(e)).type!==s)throw kr("Incompatible receiver, "+s+" required");return t}};if(ol||Qs.state){var ze=Qs.state||(Qs.state=new hl);ze.get=ze.get,ze.has=ze.has,ze.set=ze.set,rs=function(s,e){if(ze.has(s))throw kr(Ia);return e.facade=s,ze.set(s,e),e},Si=function(s){return ze.get(s)||{}},as=function(s){return ze.has(s)}}else{var Ut=ll("state");cl[Ut]=!0,rs=function(s,e){if(Ws(s,Ut))throw kr(Ia);return e.facade=s,ul(s,Ut,e),e},Si=function(s){return Ws(s,Ut)?s[Ut]:{}},as=function(s){return Ws(s,Ut)}}var ml={set:rs,get:Si,has:as,enforce:fl,getterFor:pl},vl=hs,so=Function.prototype,xa=so.apply,La=so.call,gl=typeof Reflect=="object"&&Reflect.apply||(vl?La.bind(xa):function(){return La.apply(xa,arguments)}),Sl=fs,bl=ot,ro=function(s){if(Sl(s)==="Function")return bl(s)},ao={},no={},oo={}.propertyIsEnumerable,uo=Object.getOwnPropertyDescriptor,yl=uo&&!oo.call({1:2},1);no.f=yl?function(e){var t=uo(this,e);return!!t&&t.enumerable}:oo;var Tl=xt,El=dt,$l=no,Al=gs,kl=Ti,wl=Yr,_l=ut,Pl=jn,Ca=Object.getOwnPropertyDescriptor;ao.f=Tl?Ca:function(e,t){if(e=kl(e),t=wl(t),Pl)try{return Ca(e,t)}catch(i){}if(_l(e,t))return Al(!El($l.f,e,t),e[t])};var Dl=nt,Rl=Ne,Il=/#|\.prototype\./,$i=function(s,e){var t=Ll[xl(s)];return t==Ol?!0:t==Cl?!1:Rl(e)?Dl(e):!!e},xl=$i.normalize=function(s){return String(s).replace(Il,".").toLowerCase()},Ll=$i.data={},Cl=$i.NATIVE="N",Ol=$i.POLYFILL="P",Bl=$i,Oa=ro,Ml=Gr,Nl=hs,Fl=Oa(Oa.bind),lo=function(s,e){return Ml(s),e===void 0?s:Nl?Fl(s,e):function(){return s.apply(e,arguments)}},Oi=Ye,Ul=gl,Vl=ro,Hl=Ne,Gl=ao.f,Yl=Bl,Vt=Fr,ql=lo,Ht=Ei,Ba=ut,jl=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return Ul(s,this,arguments)};return e.prototype=s.prototype,e},Ss=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?Oi:r?Oi[t]:(Oi[t]||{}).prototype,o=i?Vt:Vt[t]||Ht(Vt,t,{})[t],u=o.prototype,d,l,c,h,f,m,g,T,A;for(h in e)d=Yl(i?h:t+(r?".":"#")+h,s.forced),l=!d&&n&&Ba(n,h),m=o[h],l&&(s.dontCallGetSet?(A=Gl(n,h),g=A&&A.value):g=n[h]),f=l&&g?g:e[h],!(l&&typeof m==typeof f)&&(s.bind&&l?T=ql(f,Oi):s.wrap&&l?T=jl(f):a&&Hl(f)?T=Vl(f):T=f,(s.sham||f&&f.sham||m&&m.sham)&&Ht(T,"sham",!0),Ht(o,h,T),a&&(c=t+"Prototype",Ba(Vt,c)||Ht(Vt,c,{}),Ht(Vt[c],h,f),s.real&&u&&(d||!u[h])&&Ht(u,h,f)))},wr=xt,zl=ut,co=Function.prototype,Wl=wr&&Object.getOwnPropertyDescriptor,zr=zl(co,"name"),Ql=zr&&function(){}.name==="something",Kl=zr&&(!wr||wr&&Wl(co,"name").configurable),Jl={EXISTS:zr,PROPER:Ql,CONFIGURABLE:Kl},ho={},Xl=Math.ceil,Zl=Math.floor,ec=Math.trunc||function(e){var t=+e;return(t>0?Zl:Xl)(t)},tc=ec,Wr=function(s){var e=+s;return e!==e||e===0?0:tc(e)},ic=Wr,sc=Math.max,rc=Math.min,ac=function(s,e){var t=ic(s);return t<0?sc(t+e,0):rc(t,e)},nc=Wr,oc=Math.min,dc=function(s){return s>0?oc(nc(s),9007199254740991):0},uc=dc,Qr=function(s){return uc(s.length)},lc=Ti,cc=ac,hc=Qr,Ma=function(s){return function(e,t,i){var r=lc(e),a=hc(r),n=cc(i,a),o;if(s&&t!=t){for(;a>n;)if(o=r[n++],o!=o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}},fc={includes:Ma(!0),indexOf:Ma(!1)},pc=ot,Ks=ut,mc=Ti,vc=fc.indexOf,gc=jr,Na=pc([].push),Sc=function(s,e){var t=mc(s),i=0,r=[],a;for(a in t)!Ks(gc,a)&&Ks(t,a)&&Na(r,a);for(;e.length>i;)Ks(t,a=e[i++])&&(~vc(r,a)||Na(r,a));return r},fo=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],bc=Sc,yc=fo,Tc=Object.keys||function(e){return bc(e,yc)},Ec=xt,$c=zn,Ac=ei,kc=Lt,wc=Ti,_c=Tc;ho.f=Ec&&!$c?Object.defineProperties:function(e,t){kc(e);for(var i=wc(t),r=_c(t),a=r.length,n=0,o;a>n;)Ac.f(e,o=r[n++],i[o]);return e};var Pc=Ur,Dc=Pc("document","documentElement"),Rc=Lt,Ic=ho,Fa=fo,xc=jr,Lc=Dc,Cc=qn,Oc=qr,Ua=">",Va="<",_r="prototype",Pr="script",po=Oc("IE_PROTO"),Js=function(){},mo=function(s){return Va+Pr+Ua+s+Va+"/"+Pr+Ua},Ha=function(s){s.write(mo("")),s.close();var e=s.parentWindow.Object;return s=null,e},Bc=function(){var s=Cc("iframe"),e="java"+Pr+":",t;return s.style.display="none",Lc.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(mo("document.F=Object")),t.close(),t.F},Bi,Ji=function(){try{Bi=new ActiveXObject("htmlfile")}catch(e){}Ji=typeof document!="undefined"?document.domain&&Bi?Ha(Bi):Bc():Ha(Bi);for(var s=Fa.length;s--;)delete Ji[_r][Fa[s]];return Ji()};xc[po]=!0;var vo=Object.create||function(e,t){var i;return e!==null?(Js[_r]=Rc(e),i=new Js,Js[_r]=null,i[po]=e):i=Ji(),t===void 0?i:Ic.f(i,t)},Mc=nt,Nc=!Mc(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),Fc=ut,Uc=Ne,Vc=vs,Hc=qr,Gc=Nc,Ga=Hc("IE_PROTO"),Dr=Object,Yc=Dr.prototype,go=Gc?Dr.getPrototypeOf:function(s){var e=Vc(s);if(Fc(e,Ga))return e[Ga];var t=e.constructor;return Uc(t)&&e instanceof t?t.prototype:e instanceof Dr?Yc:null},qc=Ei,So=function(s,e,t,i){return i&&i.enumerable?s[e]=t:qc(s,e,t),s},jc=nt,zc=Ne,Wc=It,Qc=vo,Ya=go,Kc=So,Jc=qe,Rr=Jc("iterator"),bo=!1,st,Xs,Zs;[].keys&&(Zs=[].keys(),"next"in Zs?(Xs=Ya(Ya(Zs)),Xs!==Object.prototype&&(st=Xs)):bo=!0);var Xc=!Wc(st)||jc(function(){var s={};return st[Rr].call(s)!==s});Xc?st={}:st=Qc(st);zc(st[Rr])||Kc(st,Rr,function(){return this});var yo={IteratorPrototype:st,BUGGY_SAFARI_ITERATORS:bo},Zc=qe,eh=Zc("toStringTag"),To={};To[eh]="z";var Kr=String(To)==="[object z]",th=Kr,ih=Ne,Xi=fs,sh=qe,rh=sh("toStringTag"),ah=Object,nh=Xi(function(){return arguments}())=="Arguments",oh=function(s,e){try{return s[e]}catch(t){}},bs=th?Xi:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=oh(e=ah(s),rh))=="string"?t:nh?Xi(e):(i=Xi(e))=="Object"&&ih(e.callee)?"Arguments":i},dh=Kr,uh=bs,lh=dh?{}.toString:function(){return"[object "+uh(this)+"]"},ch=Kr,hh=ei.f,fh=Ei,ph=ut,mh=lh,vh=qe,qa=vh("toStringTag"),Eo=function(s,e,t,i){if(s){var r=t?s:s.prototype;ph(r,qa)||hh(r,qa,{configurable:!0,value:e}),i&&!ch&&fh(r,"toString",mh)}},gh=yo.IteratorPrototype,Sh=vo,bh=gs,yh=Eo,Th=Zt,Eh=function(){return this},$h=function(s,e,t,i){var r=e+" Iterator";return s.prototype=Sh(gh,{next:bh(+!i,t)}),yh(s,r,!1,!0),Th[r]=Eh,s},Ah=Ss,kh=dt,$o=Jl,wh=$h,_h=go,Ph=Eo,ja=So,Dh=qe,za=Zt,Ao=yo,Rh=$o.PROPER;$o.CONFIGURABLE;Ao.IteratorPrototype;var Mi=Ao.BUGGY_SAFARI_ITERATORS,er=Dh("iterator"),Wa="keys",Ni="values",Qa="entries",Ih=function(){return this},xh=function(s,e,t,i,r,a,n){wh(t,e,i);var o=function(A){if(A===r&&h)return h;if(!Mi&&A in l)return l[A];switch(A){case Wa:return function(){return new t(this,A)};case Ni:return function(){return new t(this,A)};case Qa:return function(){return new t(this,A)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,l=s.prototype,c=l[er]||l["@@iterator"]||r&&l[r],h=!Mi&&c||o(r),f=e=="Array"&&l.entries||c,m,g,T;if(f&&(m=_h(f.call(new s)),m!==Object.prototype&&m.next&&(Ph(m,u,!0,!0),za[u]=Ih)),Rh&&r==Ni&&c&&c.name!==Ni&&(d=!0,h=function(){return kh(c,this)}),r)if(g={values:o(Ni),keys:a?h:o(Wa),entries:o(Qa)},n)for(T in g)(Mi||d||!(T in l))&&ja(l,T,g[T]);else Ah({target:e,proto:!0,forced:Mi||d},g);return n&&l[er]!==h&&ja(l,er,h,{name:r}),za[e]=h,g},Lh=function(s,e){return{value:s,done:e}},Ch=Ti,Ka=Zt,ko=ml;ei.f;var Oh=xh,Fi=Lh,wo="Array Iterator",Bh=ko.set,Mh=ko.getterFor(wo);Oh(Array,"Array",function(s,e){Bh(this,{type:wo,target:Ch(s),index:0,kind:e})},function(){var s=Mh(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,Fi(void 0,!0)):t=="keys"?Fi(i,!1):t=="values"?Fi(e[i],!1):Fi([i,e[i]],!1)},"values");Ka.Arguments=Ka.Array;var Nh=qe,Fh=Zt,Uh=Nh("iterator"),Vh=Array.prototype,Hh=function(s){return s!==void 0&&(Fh.Array===s||Vh[Uh]===s)},Gh=bs,Ja=ms,Yh=ps,qh=Zt,jh=qe,zh=jh("iterator"),_o=function(s){if(!Yh(s))return Ja(s,zh)||Ja(s,"@@iterator")||qh[Gh(s)]},Wh=dt,Qh=Gr,Kh=Lt,Jh=Hr,Xh=_o,Zh=TypeError,ef=function(s,e){var t=arguments.length<2?Xh(s):e;if(Qh(t))return Kh(Wh(t,s));throw Zh(Jh(s)+" is not iterable")},tf=dt,Xa=Lt,sf=ms,rf=function(s,e,t){var i,r;Xa(s);try{if(i=sf(s,"return"),!i){if(e==="throw")throw t;return t}i=tf(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return Xa(i),t},af=lo,nf=dt,of=Lt,df=Hr,uf=Hh,lf=Qr,Za=Vr,cf=ef,hf=_o,en=rf,ff=TypeError,Zi=function(s,e){this.stopped=s,this.result=e},tn=Zi.prototype,pf=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=af(e,i),d,l,c,h,f,m,g,T=function(E){return d&&en(d,"normal",E),new Zi(!0,E)},A=function(E){return r?(of(E),o?u(E[0],E[1],T):u(E[0],E[1])):o?u(E,T):u(E)};if(a)d=s.iterator;else if(n)d=s;else{if(l=hf(s),!l)throw ff(df(s)+" is not iterable");if(uf(l)){for(c=0,h=lf(s);h>c;c++)if(f=A(s[c]),f&&Za(tn,f))return f;return new Zi(!1)}d=cf(s,l)}for(m=a?s.next:d.next;!(g=nf(m,d)).done;){try{f=A(g.value)}catch(E){en(d,"throw",E)}if(typeof f=="object"&&f&&Za(tn,f))return f}return new Zi(!1)},mf=Yr,vf=ei,gf=gs,Sf=function(s,e,t){var i=mf(e);i in s?vf.f(s,i,gf(0,t)):s[i]=t},bf=Ss,yf=pf,Tf=Sf;bf({target:"Object",stat:!0},{fromEntries:function(e){var t={};return yf(e,function(i,r){Tf(t,i,r)},{AS_ENTRIES:!0}),t}});var Ef=Fr,$f=Ef.Object.fromEntries,Af={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},kf=Af,wf=Ye,_f=bs,Pf=Ei,sn=Zt,Df=qe,rn=Df("toStringTag");for(var tr in kf){var an=wf[tr],ir=an&&an.prototype;ir&&_f(ir)!==rn&&Pf(ir,rn,tr),sn[tr]=sn.Array}var Rf=$f,If=Rf,xf=If,Lf=xf,Qt=Mr(Lf),be;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",s[s.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(be||(be={}));var He=(s,e=0,t=be.OFFSET_P)=>{switch(t){case be.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case be.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case be.DASH_CMAF_OFFSET_P:{if(e===0)return s;const i=new URL(s);return i.searchParams.set("offset_p",e.toFixed(0)),i.toString()}default:V(t)}return s};const nn=(s,e)=>{var t;switch(e){case be.OFFSET_P:return NaN;case be.PLAYBACK_SHIFT:{const i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case be.DASH_CMAF_OFFSET_P:{const i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:V(e)}};var R=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};class ue{constructor(e){this.transitionStarted$=new L,this.transitionEnded$=new L,this.transitionUpdated$=new L,this.forceChanged$=new L,this.stateChangeStarted$=U(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=U(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||_(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const Cf=s=>{switch(s){case y.MPEG:case y.DASH:case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.HLS:case y.HLS_ONDEMAND:return!1;case y.DASH_LIVE:case y.DASH_LIVE_CMAF:case y.HLS_LIVE:case y.HLS_LIVE_CMAF:case y.DASH_LIVE_WEBM:case y.WEB_RTC_LIVE:return!0;default:return V(s)}};var q;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(q||(q={}));const Of=5,Bf=5,Mf=500,on=7e3;class Nf{constructor(e){this.subscription=new re,this.loadMediaTimeoutSubscription=new re,this.videoState=new ue(q.STOPPED),this.syncPlayback=()=>{const i=this.videoState.getState(),r=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${a}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(o)};`}),a===p.STOPPED){i!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==p.PAUSED&&o.state===z.Requested&&i!==q.STOPPED){this.seek(o.position/1e3);return}switch(a){case p.READY:{switch(i){case q.PLAYING:case q.PAUSED:case q.READY:break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:V(i)}break}case p.PLAYING:{switch(i){case q.PLAYING:break;case q.PAUSED:this.videoState.startTransitionTo(q.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case q.READY:this.videoState.startTransitionTo(q.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:V(i)}break}case p.PAUSED:{switch(i){case q.PLAYING:this.videoState.startTransitionTo(q.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case q.PAUSED:break;case q.READY:this.videoState.startTransitionTo(q.PAUSED),this.videoState.setState(q.PAUSED);break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:V(i)}break}default:V(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Cf(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new re;this.subscription.add(e),this.subscription.add(U(this.videoState.stateChangeStarted$.pipe(w(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(w(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));const t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const r=new L;e.add(r.pipe(Me(Mf)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===z.Applying||Math.abs(o-a)>Of)&&r.next(o),a=o})),e.add(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<Bf&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),R(this.params.desiredState.playbackState,p.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:V(n)}}),t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const i=U(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Me(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(q.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED)):(this.videoState.setState(q.PLAYING),R(this.params.desiredState.playbackState,p.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:z.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===q.PAUSED||e===q.PLAYING)&&(this.videoState.setState(q.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===q.PLAYING||e===q.PAUSED)&&(this.videoState.setState(q.PLAYING),R(this.params.desiredState.playbackState,p.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===q.READY&&this.videoState.setState(q.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===p.READY&&R(this.params.desiredState.playbackState,p.READY)}handleRemoteStop(){this.videoState.getState()!==q.STOPPED&&this.videoState.setState(q.STOPPED)}handleRemoteVolumeChange(e){var t,i;const r=this.params.output.volume$.getValue(),a={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(i=e.muted)!==null&&i!==void 0?i:r.muted};(a.volume!==r.volume||a.muted!==a.muted)&&this.params.output.volume$.next(a)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const i=this.params.source;let r,a,n;switch(e){case y.MPEG:{const l=i[e];P(l);const c=hd(Object.keys(l));P(c);const h=l[c];P(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case y.HLS:case y.HLS_ONDEMAND:{const l=i[e];P(l),r=l.url,a="application/x-mpegurl",n=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.DASH_WEBM_AV1:{const l=i[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_LIVE_CMAF:{const l=i[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const l=i[e];P(l),r=He(l.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case y.DASH:case y.DASH_LIVE:case y.WEB_RTC_LIVE:{const l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:C.VIDEO_PIPELINE,message:l,thrown:c}),c}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return V(e)}const o=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,a);o.contentUrl=r,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return _(u)&&(o.metadata.title=u),_(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===z.Applying||i.state===z.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(fd(on).subscribe(()=>a(`timeout(${on})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===z.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{const a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:C.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}var Ff=s=>{let e,t=!1,i=!1;s.on("playbackTimeUpdated",({timeToEnd:r})=>{i=r<=3,t&&i&&(e==null||e())}),s.extend("MediaSourceController",function(){const{parent:r}=this,a=r.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>a(n),t&&i&&(e==null||e())}}},!0)},Uf=s=>{const e=new S(1/0),t=new L,i=new S(void 0),r=new S(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},u=l=>{var c,h,f,m,g;const T=Qt(l.getAllResponseHeaders().trim().split(/[\n\r]+/).map(v=>v.split(": ")));if("x-playback-duration"in T||"x-playback-duration-millis"in T){const v=parseInt((c=l.getResponseHeader("X-Playback-Duration"))!==null&&c!==void 0?c:"",10),b=parseInt((h=l.getResponseHeader("X-Playback-Duration-Millis"))!==null&&h!==void 0?h:"",10),$=(f=b!=null?b:v*1e3)!==null&&f!==void 0?f:NaN;_($)&&!isNaN($)&&e.next($)}const A=(m=T["x-delivery-type"])!==null&&m!==void 0?m:gi.HTTP1,E=(g={1:!0,0:!1}[T["x-reused"]])!==null&&g!==void 0?g:void 0;i.next(A),r.next(E)},d=l=>{l.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return s.extend("XHRLoader",function(){const{parent:l}=this,c=l.load.bind(l);return{load:function(h){if(h.request.type==="MPD"){const f=h.onload,m=h.progress;h.onload=function(...g){return u(this),f(...g)},h.progress=function(...g){return d(this),m(...g)},o()}return c(h)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:i}},Kt=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},Vf=s=>s.extend("RequestModifier",()=>({modifyRequestURL:Kt}),!0),Hf=s=>{s.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[r,a]=i.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(i.request.url,location.href);n.searchParams.append("bytes",`${r}-${a}`),i.request.url=n.toString(),i.request.range=void 0}t(i)}}},!0)};const Ge=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=s.getState(),o=e(),u=te(r),d=new re;return r&&d.add(r.subscribe(l=>{const c=s.getState();i(l,c)&&s.setState(l)},a)),i(o,n)||(t(n),u&&s.setState(n)),d.add(s.stateChangeStarted$.subscribe(l=>{t(l.to),u&&s.setState(l.to)},a)),d},Ct=(s,e,t)=>Ge(e,()=>s.loop,i=>{_(i)&&(s.loop=i)},{onError:t}),lt=(s,e,t,i)=>Ge(e,()=>({muted:s.muted,volume:s.volume}),r=>{_(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),Tt=(s,e,t,i)=>Ge(e,()=>s.playbackRate,r=>{_(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Gf=s=>["__",s.language,s.label].join("|"),Yf=(s,e)=>{if(s.id===e)return!0;const[t,i,r]=e.split("|");return s.language===i&&s.label===r};class Ze{constructor(){this.available$=new L,this.current$=new S(void 0),this.error$=new L,this.subscription=new re,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:C.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Ge(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{_(a)&&this.setInternal(a)},{equal:(a,n)=>_(a)&&_(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(w(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Ge(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{_(a)&&this.setExternal(a)},{equal:(a,n)=>_(a)&&_(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(w(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Ge(t.currentTextTrack,()=>{if(this.video)return;const a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(Ge(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){P(this.video);const{textTracks:e}=this.video;this.subscription.add(B(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(U(B(e,"addtrack"),B(e,"removetrack"),ke(["init"])).pipe(w(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),fe((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(U(B(e,"change"),ke(["init"])).pipe(w(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),w(i=>i&&this.htmlTextTrackToITextTrack(i).id),fe()).subscribe(this.current$));const t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(B(e,"addtrack").subscribe(i=>{var r,a;(r=i.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var u,d,l,c,h;const f=(d=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&d!==void 0?d:null;f&&f.length&&(this.applyCueSettings((c=(l=o.target)===null||l===void 0?void 0:l.cues)!==null&&c!==void 0?c:null),(h=o.target)===null||h===void 0||h.removeEventListener("cuechange",n))};(a=i.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(B(e,"removetrack").subscribe(i=>{var r;(r=i.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const r=i;_(t.align)&&(r.align=t.align),_(t.position)&&(r.position=t.position),_(t.size)&&(r.size=t.size),_(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){P(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Ze.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,i;const{language:r,label:a}=e,n=e.id?e.id:Gf(e),o=this.externalTracks.has(n),u=n.includes("auto");return o?{id:n,type:"external",isAuto:u,language:r,label:a,url:(t=this.externalTracks.get(n))===null||t===void 0?void 0:t.url}:{id:n,type:"internal",isAuto:u,language:r,label:a,url:(i=this.internalTracks.get(n))===null||i===void 0?void 0:i.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){P(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(te(e)||!Yf(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){P(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){P(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const Jr=s=>{s.removeAttribute("src"),s.load()},qf=s=>{try{s.pause(),s.playbackRate=0,Jr(s),s.remove()}catch(e){console.error(e)}};class jf{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}}const Ir=window.WeakMap?new WeakMap:new jf,ct=s=>{let e=s.querySelector("video");const t=!!e;return e?Jr(e):(e=document.createElement("video"),s.appendChild(e)),Ir.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},ht=s=>{const e=Ir.get(s);Ir.delete(s),e?Jr(s):qf(s)};class ys{constructor(){this.pausedTime=0,this.streamOffset=0,this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}}const Po=s=>{var e;let t=s;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},dn=s=>{const e=Po(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},zf=s=>{const e=Po(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)},xr=3;class Wf{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let r=this._source.buffered.start(t);const a=this._source.buffered.end(t);r>e&&r-e<xr&&(r=e),this._buffer.push({from:r,to:a,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||xr))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:r,to:a})=>{const n=r>=e&&r<t,o=a>=e&&a<t;n&&o||(n?i(t,a):o?i(r,e):r<e&&a>t?(i(t,a),i(r,e)):i(r,a))})}destroy(){this._buffer=[]}}var Do=(s,e,t=xr)=>{let i=0,r=0;for(let a=0;a<s.length;a++){const n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};const ft=s=>{const e=v=>B(s,v).pipe(Wt(void 0)),i=U(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>B(s,v))).pipe(w(v=>v.type==="ended"?s.readyState<2:s.readyState<3),fe()),r=U(B(s,"progress"),B(s,"timeupdate")).pipe(w(()=>Do(s.buffered,s.currentTime))),n=Br().browser===Mn.Safari?Ie({play:e("play").pipe(me()),playing:e("playing")}).pipe(Wt(void 0)):e("playing"),o=B(s,"volumechange").pipe(w(()=>({muted:s.muted,volume:s.volume}))),u=B(s,"ratechange").pipe(w(()=>s.playbackRate)),d=B(s,"error").pipe(se(()=>!!(s.error||s.played.length)),w(()=>{var v;const b=s.error;return{id:b?`MediaError#${b.code}`:"HtmlVideoError",category:C.VIDEO_PIPELINE,message:b?b.message:"Error event from HTML video element",thrown:(v=s.error)!==null&&v!==void 0?v:void 0}})),l=B(s,"timeupdate").pipe(w(()=>s.currentTime)),c=new L,h=.3;let f;l.subscribe(v=>{s.loop&&_(f)&&_(v)&&f>=s.duration-h&&v<=h&&c.next(f),f=v});const m=B(s,"enterpictureinpicture"),g=B(s,"leavepictureinpicture"),T=new S(zf(s));m.subscribe(()=>T.next(!0)),g.subscribe(()=>T.next(!1));const A=new S(dn(s));return B(s,"fullscreenchange").pipe(w(()=>dn(s))).subscribe(A),{playing$:n,pause$:e("pause").pipe(se(()=>!s.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:B(s,"durationchange").pipe(w(()=>s.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:o,playbackRateState$:u,inPiP$:T,inFullscreen$:A}},Xr=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var Qf=Ss,Kf=vs,Jf=Qr,Xf=Wr;Qf({target:"Array",proto:!0},{at:function(e){var t=Kf(this),i=Jf(t),r=Xf(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});var Zf=Ur,Ro=Zf,ep=Ro,tp=ep("Array","at"),ip=tp,sp=ip,rp=sp,ap=rp,Qe=Mr(ap);let Zr=!1,it={};const np=s=>{Zr=s},op=()=>{it={}},dp=s=>{s(it)},Ui=(s,e)=>{var t;Zr&&(it.meta=(t=it.meta)!==null&&t!==void 0?t:{},it.meta[s]=e)};class Ke{constructor(e){this.name=e}next(e){var t,i;if(!Zr)return;it.series=(t=it.series)!==null&&t!==void 0?t:{};const r=(i=it.series[this.name])!==null&&i!==void 0?i:[];r.push([Date.now(),e]),it.series[this.name]=r}}var Pt;(function(s){s.FitsContainer="FitsContainer",s.FitsThroughput="FitsThroughput",s.Buffer="Buffer",s.DroppedFramesLimit="DroppedFramesLimit",s.FitsQualityLimits="FitsQualityLimits"})(Pt||(Pt={}));const up=new Ke("best_bitrate"),lp=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class cp{constructor(){this.history={}}recordSelection(e){this.history[e.id]=pe()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const ti=(s,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:d,droppedVideoMaxQualityLimit:l,abrLogger:c})=>{var h,f,m,g,T;const A=i.usePixelRatio&&(h=window.devicePixelRatio)!==null&&h!==void 0?h:1,E=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*A*i.containerSizeFactor,height:e.height*A*i.containerSizeFactor},v=E&&Rt(E),b=i.considerPlaybackRate&&_(o)?o:1,$=s.filter(F=>!vi(F.quality)).sort((F,I)=>pi(F.quality,I.quality)?-1:1),D=(f=Qe($,-1))===null||f===void 0?void 0:f.quality,Y=(m=Qe($,0))===null||m===void 0?void 0:m.quality,J=te(r)||_(r.min)&&_(r.max)&&Ki(r.max,r.min)||_(r.min)&&Y&&pi(r.min,Y)||_(r.max)&&D&&Ki(r.max,D),N=b*lp(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),G={},O=$.filter(F=>(v?Ki(F.quality,v):!0)?(_(t)&&isFinite(t)&&_(F.bitrate)?t-a>=F.bitrate*N:!0)?i.lazyQualitySwitch&&_(i.minBufferToSwitchUp)&&u&&!vi(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&pi(F.quality,u.quality)?(G[F.quality]=Pt.Buffer,!1):!!l&&Tr(F.quality,l)?(G[F.quality]=Pt.DroppedFramesLimit,!1):J||(te(r.max)||Nn(F.quality,r.max))&&(te(r.min)||Tr(F.quality,r.min))?!0:(G[F.quality]=Pt.FitsQualityLimits,!1):(G[F.quality]=Pt.FitsThroughput,!1):(G[F.quality]=Pt.FitsContainer,!1))[0];O&&O.bitrate&&up.next(O.bitrate);const H=(g=O!=null?O:$[Math.ceil(($.length-1)/2)])!==null&&g!==void 0?g:s[0];H.quality!==((T=d==null?void 0:d.last)===null||T===void 0?void 0:T.quality)&&c({message:`
6
+ import{ValueSubject as S,Subject as L,Subscription as re,isNonNullable as _,ErrorCategory as C,isNullable as te,fromEvent as B,assertNever as V,merge as U,tap as ts,map as w,observableFrom as ke,filterChanged as fe,assertNonNullable as P,debounce as Me,getHighestQuality as hd,timeout as fd,getCurrentBrowser as Br,CurrentClientBrowser as Mn,combine as Ie,once as me,mapTo as Wt,filter as se,now as pe,videoSizeToQuality as Rt,isInvariantQuality as vi,isHigher as pi,isLower as Ki,isHigherOrEqual as Tr,isLowerOrEqual as Nn,Observable as cs,interval as is,VideoQuality as Ce,videoQualityToHeight as pd,abortable as Re,getExponentialDelay as fa,throttle as md,CurrentClientDevice as vd,safeStorage as Cs,fillWithDefault as gd,Logger as Sd}from"@vkontakte/videoplayer-shared/es2018.esm.js";import{Observable as Zv,Subject as eg,Subscription as tg,ValueSubject as ig,VideoQuality as sg}from"@vkontakte/videoplayer-shared/es2018.esm.js";import bd from"lodash/debounce.js";const yd="2.0.95";var p;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(p||(p={}));var y;(function(s){s.MPEG="MPEG",s.DASH="DASH",s.DASH_SEP="DASH_SEP",s.DASH_SEP_VK="DASH_SEP",s.DASH_WEBM="DASH_WEBM",s.DASH_WEBM_AV1="DASH_WEBM_AV1",s.DASH_WEBM_VK="DASH_WEBM",s.DASH_ONDEMAND="DASH_ONDEMAND",s.DASH_ONDEMAND_VK="DASH_ONDEMAND",s.DASH_LIVE="DASH_LIVE",s.DASH_LIVE_CMAF="DASH_LIVE_CMAF",s.DASH_LIVE_WEBM="DASH_LIVE_WEBM",s.HLS="HLS",s.HLS_ONDEMAND="HLS_ONDEMAND",s.HLS_JS="HLS",s.HLS_LIVE="HLS_LIVE",s.HLS_LIVE_CMAF="HLS_LIVE_CMAF",s.WEB_RTC_LIVE="WEB_RTC_LIVE"})(y||(y={}));var Ee;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(Ee||(Ee={}));var ye;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})(ye||(ye={}));var gi;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(gi||(gi={}));var z;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(z||(z={}));var gt;(function(s){s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip"})(gt||(gt={}));var Td=s=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class Ed{constructor(e){var t;this.connection$=new S(void 0),this.castState$=new S(ye.NOT_AVAILABLE),this.errorEvent$=new L,this.realCastState$=new S(ye.NOT_AVAILABLE),this.subscription=new re,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const i="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${i}`}),e.isDisabled||!i)return;const r=_((t=window.chrome)===null||t===void 0?void 0:t.cast),a=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=n=>{delete window.__onGCastApiAvailable,n&&this.initializeCastApi()},a||Td("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:C.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,a;(a=(r=(i=cast.framework.CastContext.getInstance())===null||i===void 0?void 0:i.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||a===void 0||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){_(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();te(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();te(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(B(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(a=i.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return V(r.sessionState)}})).add(U(B(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(ts(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),w(r=>r.castState)),ke([i.getCastState()])).pipe(fe(),w($d),ts(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===ye.CONNECTED,o=_(this.connection$.getValue());if(n&&!o){const u=i.getCurrentSession();P(u);const d=u.getCastDevice(),l=(a=u.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(te(l)||l===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:u,castDevice:d}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===ye.CONNECTED?_(this.connection$.getValue())?ye.CONNECTED:ye.AVAILABLE:r)}))}initializeCastApi(){var e;let t,i,r;try{t=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:i,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:C.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const $d=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return ye.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return ye.AVAILABLE;case cast.framework.CastState.CONNECTING:return ye.CONNECTING;case cast.framework.CastState.CONNECTED:return ye.CONNECTED;default:return V(s)}};var Os=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Mr(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var nt=function(s){try{return!!s()}catch(e){return!0}},Ad=nt,hs=!Ad(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),Fn=hs,Un=Function.prototype,Er=Un.call,kd=Fn&&Un.bind.bind(Er,Er),ot=Fn?kd:function(s){return function(){return Er.apply(s,arguments)}},Vn=ot,wd=Vn({}.toString),_d=Vn("".slice),fs=function(s){return _d(wd(s),8,-1)},Pd=ot,Dd=nt,Rd=fs,Bs=Object,Id=Pd("".split),xd=Dd(function(){return!Bs("z").propertyIsEnumerable(0)})?function(s){return Rd(s)=="String"?Id(s,""):Bs(s)}:Bs,ps=function(s){return s==null},Ld=ps,Cd=TypeError,Nr=function(s){if(Ld(s))throw Cd("Can't call method on "+s);return s},Od=xd,Bd=Nr,Ti=function(s){return Od(Bd(s))},Zt={},xi=function(s){return s&&s.Math==Math&&s},Ye=xi(typeof globalThis=="object"&&globalThis)||xi(typeof window=="object"&&window)||xi(typeof self=="object"&&self)||xi(typeof Os=="object"&&Os)||function(){return this}()||Os||Function("return this")(),$r=typeof document=="object"&&document.all,Md=typeof $r=="undefined"&&$r!==void 0,Hn={all:$r,IS_HTMLDDA:Md},Gn=Hn,Nd=Gn.all,Ne=Gn.IS_HTMLDDA?function(s){return typeof s=="function"||s===Nd}:function(s){return typeof s=="function"},Fd=Ye,Ud=Ne,pa=Fd.WeakMap,Vd=Ud(pa)&&/native code/.test(String(pa)),ma=Ne,Yn=Hn,Hd=Yn.all,It=Yn.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:ma(s)||s===Hd}:function(s){return typeof s=="object"?s!==null:ma(s)},Gd=nt,xt=!Gd(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),ei={},Yd=Ye,va=It,Ar=Yd.document,qd=va(Ar)&&va(Ar.createElement),qn=function(s){return qd?Ar.createElement(s):{}},jd=xt,zd=nt,Wd=qn,jn=!jd&&!zd(function(){return Object.defineProperty(Wd("div"),"a",{get:function(){return 7}}).a!=7}),Qd=xt,Kd=nt,zn=Qd&&Kd(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Jd=It,Xd=String,Zd=TypeError,Lt=function(s){if(Jd(s))return s;throw Zd(Xd(s)+" is not an object")},eu=hs,Li=Function.prototype.call,dt=eu?Li.bind(Li):function(){return Li.apply(Li,arguments)},Fr={},Ms=Fr,Ns=Ye,tu=Ne,ga=function(s){return tu(s)?s:void 0},Ur=function(s,e){return arguments.length<2?ga(Ms[s])||ga(Ns[s]):Ms[s]&&Ms[s][e]||Ns[s]&&Ns[s][e]},iu=ot,Vr=iu({}.isPrototypeOf),su=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Wn=Ye,Fs=su,Sa=Wn.process,ba=Wn.Deno,ya=Sa&&Sa.versions||ba&&ba.version,Ta=ya&&ya.v8,Ve,ss;Ta&&(Ve=Ta.split("."),ss=Ve[0]>0&&Ve[0]<4?1:+(Ve[0]+Ve[1]));!ss&&Fs&&(Ve=Fs.match(/Edge\/(\d+)/),(!Ve||Ve[1]>=74)&&(Ve=Fs.match(/Chrome\/(\d+)/),Ve&&(ss=+Ve[1])));var ru=ss,Ea=ru,au=nt,nu=Ye,ou=nu.String,Qn=!!Object.getOwnPropertySymbols&&!au(function(){var s=Symbol();return!ou(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Ea&&Ea<41}),du=Qn,Kn=du&&!Symbol.sham&&typeof Symbol.iterator=="symbol",uu=Ur,lu=Ne,cu=Vr,hu=Kn,fu=Object,Jn=hu?function(s){return typeof s=="symbol"}:function(s){var e=uu("Symbol");return lu(e)&&cu(e.prototype,fu(s))},pu=String,Hr=function(s){try{return pu(s)}catch(e){return"Object"}},mu=Ne,vu=Hr,gu=TypeError,Gr=function(s){if(mu(s))return s;throw gu(vu(s)+" is not a function")},Su=Gr,bu=ps,ms=function(s,e){var t=s[e];return bu(t)?void 0:Su(t)},Us=dt,Vs=Ne,Hs=It,yu=TypeError,Tu=function(s,e){var t,i;if(e==="string"&&Vs(t=s.toString)&&!Hs(i=Us(t,s))||Vs(t=s.valueOf)&&!Hs(i=Us(t,s))||e!=="string"&&Vs(t=s.toString)&&!Hs(i=Us(t,s)))return i;throw yu("Can't convert object to primitive value")},Xn={exports:{}},$a=Ye,Eu=Object.defineProperty,$u=function(s,e){try{Eu($a,s,{value:e,configurable:!0,writable:!0})}catch(t){$a[s]=e}return e},Au=Ye,ku=$u,Aa="__core-js_shared__",wu=Au[Aa]||ku(Aa,{}),Zn=wu,ka=Zn;(Xn.exports=function(s,e){return ka[s]||(ka[s]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"});var eo=Xn.exports,_u=Nr,Pu=Object,vs=function(s){return Pu(_u(s))},Du=ot,Ru=vs,Iu=Du({}.hasOwnProperty),ut=Object.hasOwn||function(e,t){return Iu(Ru(e),t)},xu=ot,Lu=0,Cu=Math.random(),Ou=xu(1 .toString),to=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Ou(++Lu+Cu,36)},Bu=Ye,Mu=eo,wa=ut,Nu=to,Fu=Qn,Uu=Kn,qt=Bu.Symbol,Gs=Mu("wks"),Vu=Uu?qt.for||qt:qt&&qt.withoutSetter||Nu,qe=function(s){return wa(Gs,s)||(Gs[s]=Fu&&wa(qt,s)?qt[s]:Vu("Symbol."+s)),Gs[s]},Hu=dt,_a=It,Pa=Jn,Gu=ms,Yu=Tu,qu=qe,ju=TypeError,zu=qu("toPrimitive"),Wu=function(s,e){if(!_a(s)||Pa(s))return s;var t=Gu(s,zu),i;if(t){if(e===void 0&&(e="default"),i=Hu(t,s,e),!_a(i)||Pa(i))return i;throw ju("Can't convert object to primitive value")}return e===void 0&&(e="number"),Yu(s,e)},Qu=Wu,Ku=Jn,Yr=function(s){var e=Qu(s,"string");return Ku(e)?e:e+""},Ju=xt,Xu=jn,Zu=zn,Ci=Lt,Da=Yr,el=TypeError,Ys=Object.defineProperty,tl=Object.getOwnPropertyDescriptor,qs="enumerable",js="configurable",zs="writable";ei.f=Ju?Zu?function(e,t,i){if(Ci(e),t=Da(t),Ci(i),typeof e=="function"&&t==="prototype"&&"value"in i&&zs in i&&!i[zs]){var r=tl(e,t);r&&r[zs]&&(e[t]=i.value,i={configurable:js in i?i[js]:r[js],enumerable:qs in i?i[qs]:r[qs],writable:!1})}return Ys(e,t,i)}:Ys:function(e,t,i){if(Ci(e),t=Da(t),Ci(i),Xu)try{return Ys(e,t,i)}catch(r){}if("get"in i||"set"in i)throw el("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var gs=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},il=xt,sl=ei,rl=gs,Ei=il?function(s,e,t){return sl.f(s,e,rl(1,t))}:function(s,e,t){return s[e]=t,s},al=eo,nl=to,Ra=al("keys"),qr=function(s){return Ra[s]||(Ra[s]=nl(s))},jr={},ol=Vd,io=Ye,dl=It,ul=Ei,Ws=ut,Qs=Zn,ll=qr,cl=jr,Ia="Object already initialized",kr=io.TypeError,hl=io.WeakMap,rs,Si,as,fl=function(s){return as(s)?Si(s):rs(s,{})},pl=function(s){return function(e){var t;if(!dl(e)||(t=Si(e)).type!==s)throw kr("Incompatible receiver, "+s+" required");return t}};if(ol||Qs.state){var ze=Qs.state||(Qs.state=new hl);ze.get=ze.get,ze.has=ze.has,ze.set=ze.set,rs=function(s,e){if(ze.has(s))throw kr(Ia);return e.facade=s,ze.set(s,e),e},Si=function(s){return ze.get(s)||{}},as=function(s){return ze.has(s)}}else{var Ut=ll("state");cl[Ut]=!0,rs=function(s,e){if(Ws(s,Ut))throw kr(Ia);return e.facade=s,ul(s,Ut,e),e},Si=function(s){return Ws(s,Ut)?s[Ut]:{}},as=function(s){return Ws(s,Ut)}}var ml={set:rs,get:Si,has:as,enforce:fl,getterFor:pl},vl=hs,so=Function.prototype,xa=so.apply,La=so.call,gl=typeof Reflect=="object"&&Reflect.apply||(vl?La.bind(xa):function(){return La.apply(xa,arguments)}),Sl=fs,bl=ot,ro=function(s){if(Sl(s)==="Function")return bl(s)},ao={},no={},oo={}.propertyIsEnumerable,uo=Object.getOwnPropertyDescriptor,yl=uo&&!oo.call({1:2},1);no.f=yl?function(e){var t=uo(this,e);return!!t&&t.enumerable}:oo;var Tl=xt,El=dt,$l=no,Al=gs,kl=Ti,wl=Yr,_l=ut,Pl=jn,Ca=Object.getOwnPropertyDescriptor;ao.f=Tl?Ca:function(e,t){if(e=kl(e),t=wl(t),Pl)try{return Ca(e,t)}catch(i){}if(_l(e,t))return Al(!El($l.f,e,t),e[t])};var Dl=nt,Rl=Ne,Il=/#|\.prototype\./,$i=function(s,e){var t=Ll[xl(s)];return t==Ol?!0:t==Cl?!1:Rl(e)?Dl(e):!!e},xl=$i.normalize=function(s){return String(s).replace(Il,".").toLowerCase()},Ll=$i.data={},Cl=$i.NATIVE="N",Ol=$i.POLYFILL="P",Bl=$i,Oa=ro,Ml=Gr,Nl=hs,Fl=Oa(Oa.bind),lo=function(s,e){return Ml(s),e===void 0?s:Nl?Fl(s,e):function(){return s.apply(e,arguments)}},Oi=Ye,Ul=gl,Vl=ro,Hl=Ne,Gl=ao.f,Yl=Bl,Vt=Fr,ql=lo,Ht=Ei,Ba=ut,jl=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return Ul(s,this,arguments)};return e.prototype=s.prototype,e},Ss=function(s,e){var t=s.target,i=s.global,r=s.stat,a=s.proto,n=i?Oi:r?Oi[t]:(Oi[t]||{}).prototype,o=i?Vt:Vt[t]||Ht(Vt,t,{})[t],u=o.prototype,d,l,c,h,f,m,g,T,A;for(h in e)d=Yl(i?h:t+(r?".":"#")+h,s.forced),l=!d&&n&&Ba(n,h),m=o[h],l&&(s.dontCallGetSet?(A=Gl(n,h),g=A&&A.value):g=n[h]),f=l&&g?g:e[h],!(l&&typeof m==typeof f)&&(s.bind&&l?T=ql(f,Oi):s.wrap&&l?T=jl(f):a&&Hl(f)?T=Vl(f):T=f,(s.sham||f&&f.sham||m&&m.sham)&&Ht(T,"sham",!0),Ht(o,h,T),a&&(c=t+"Prototype",Ba(Vt,c)||Ht(Vt,c,{}),Ht(Vt[c],h,f),s.real&&u&&(d||!u[h])&&Ht(u,h,f)))},wr=xt,zl=ut,co=Function.prototype,Wl=wr&&Object.getOwnPropertyDescriptor,zr=zl(co,"name"),Ql=zr&&function(){}.name==="something",Kl=zr&&(!wr||wr&&Wl(co,"name").configurable),Jl={EXISTS:zr,PROPER:Ql,CONFIGURABLE:Kl},ho={},Xl=Math.ceil,Zl=Math.floor,ec=Math.trunc||function(e){var t=+e;return(t>0?Zl:Xl)(t)},tc=ec,Wr=function(s){var e=+s;return e!==e||e===0?0:tc(e)},ic=Wr,sc=Math.max,rc=Math.min,ac=function(s,e){var t=ic(s);return t<0?sc(t+e,0):rc(t,e)},nc=Wr,oc=Math.min,dc=function(s){return s>0?oc(nc(s),9007199254740991):0},uc=dc,Qr=function(s){return uc(s.length)},lc=Ti,cc=ac,hc=Qr,Ma=function(s){return function(e,t,i){var r=lc(e),a=hc(r),n=cc(i,a),o;if(s&&t!=t){for(;a>n;)if(o=r[n++],o!=o)return!0}else for(;a>n;n++)if((s||n in r)&&r[n]===t)return s||n||0;return!s&&-1}},fc={includes:Ma(!0),indexOf:Ma(!1)},pc=ot,Ks=ut,mc=Ti,vc=fc.indexOf,gc=jr,Na=pc([].push),Sc=function(s,e){var t=mc(s),i=0,r=[],a;for(a in t)!Ks(gc,a)&&Ks(t,a)&&Na(r,a);for(;e.length>i;)Ks(t,a=e[i++])&&(~vc(r,a)||Na(r,a));return r},fo=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],bc=Sc,yc=fo,Tc=Object.keys||function(e){return bc(e,yc)},Ec=xt,$c=zn,Ac=ei,kc=Lt,wc=Ti,_c=Tc;ho.f=Ec&&!$c?Object.defineProperties:function(e,t){kc(e);for(var i=wc(t),r=_c(t),a=r.length,n=0,o;a>n;)Ac.f(e,o=r[n++],i[o]);return e};var Pc=Ur,Dc=Pc("document","documentElement"),Rc=Lt,Ic=ho,Fa=fo,xc=jr,Lc=Dc,Cc=qn,Oc=qr,Ua=">",Va="<",_r="prototype",Pr="script",po=Oc("IE_PROTO"),Js=function(){},mo=function(s){return Va+Pr+Ua+s+Va+"/"+Pr+Ua},Ha=function(s){s.write(mo("")),s.close();var e=s.parentWindow.Object;return s=null,e},Bc=function(){var s=Cc("iframe"),e="java"+Pr+":",t;return s.style.display="none",Lc.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(mo("document.F=Object")),t.close(),t.F},Bi,Ji=function(){try{Bi=new ActiveXObject("htmlfile")}catch(e){}Ji=typeof document!="undefined"?document.domain&&Bi?Ha(Bi):Bc():Ha(Bi);for(var s=Fa.length;s--;)delete Ji[_r][Fa[s]];return Ji()};xc[po]=!0;var vo=Object.create||function(e,t){var i;return e!==null?(Js[_r]=Rc(e),i=new Js,Js[_r]=null,i[po]=e):i=Ji(),t===void 0?i:Ic.f(i,t)},Mc=nt,Nc=!Mc(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),Fc=ut,Uc=Ne,Vc=vs,Hc=qr,Gc=Nc,Ga=Hc("IE_PROTO"),Dr=Object,Yc=Dr.prototype,go=Gc?Dr.getPrototypeOf:function(s){var e=Vc(s);if(Fc(e,Ga))return e[Ga];var t=e.constructor;return Uc(t)&&e instanceof t?t.prototype:e instanceof Dr?Yc:null},qc=Ei,So=function(s,e,t,i){return i&&i.enumerable?s[e]=t:qc(s,e,t),s},jc=nt,zc=Ne,Wc=It,Qc=vo,Ya=go,Kc=So,Jc=qe,Rr=Jc("iterator"),bo=!1,st,Xs,Zs;[].keys&&(Zs=[].keys(),"next"in Zs?(Xs=Ya(Ya(Zs)),Xs!==Object.prototype&&(st=Xs)):bo=!0);var Xc=!Wc(st)||jc(function(){var s={};return st[Rr].call(s)!==s});Xc?st={}:st=Qc(st);zc(st[Rr])||Kc(st,Rr,function(){return this});var yo={IteratorPrototype:st,BUGGY_SAFARI_ITERATORS:bo},Zc=qe,eh=Zc("toStringTag"),To={};To[eh]="z";var Kr=String(To)==="[object z]",th=Kr,ih=Ne,Xi=fs,sh=qe,rh=sh("toStringTag"),ah=Object,nh=Xi(function(){return arguments}())=="Arguments",oh=function(s,e){try{return s[e]}catch(t){}},bs=th?Xi:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=oh(e=ah(s),rh))=="string"?t:nh?Xi(e):(i=Xi(e))=="Object"&&ih(e.callee)?"Arguments":i},dh=Kr,uh=bs,lh=dh?{}.toString:function(){return"[object "+uh(this)+"]"},ch=Kr,hh=ei.f,fh=Ei,ph=ut,mh=lh,vh=qe,qa=vh("toStringTag"),Eo=function(s,e,t,i){if(s){var r=t?s:s.prototype;ph(r,qa)||hh(r,qa,{configurable:!0,value:e}),i&&!ch&&fh(r,"toString",mh)}},gh=yo.IteratorPrototype,Sh=vo,bh=gs,yh=Eo,Th=Zt,Eh=function(){return this},$h=function(s,e,t,i){var r=e+" Iterator";return s.prototype=Sh(gh,{next:bh(+!i,t)}),yh(s,r,!1,!0),Th[r]=Eh,s},Ah=Ss,kh=dt,$o=Jl,wh=$h,_h=go,Ph=Eo,ja=So,Dh=qe,za=Zt,Ao=yo,Rh=$o.PROPER;$o.CONFIGURABLE;Ao.IteratorPrototype;var Mi=Ao.BUGGY_SAFARI_ITERATORS,er=Dh("iterator"),Wa="keys",Ni="values",Qa="entries",Ih=function(){return this},xh=function(s,e,t,i,r,a,n){wh(t,e,i);var o=function(A){if(A===r&&h)return h;if(!Mi&&A in l)return l[A];switch(A){case Wa:return function(){return new t(this,A)};case Ni:return function(){return new t(this,A)};case Qa:return function(){return new t(this,A)}}return function(){return new t(this)}},u=e+" Iterator",d=!1,l=s.prototype,c=l[er]||l["@@iterator"]||r&&l[r],h=!Mi&&c||o(r),f=e=="Array"&&l.entries||c,m,g,T;if(f&&(m=_h(f.call(new s)),m!==Object.prototype&&m.next&&(Ph(m,u,!0,!0),za[u]=Ih)),Rh&&r==Ni&&c&&c.name!==Ni&&(d=!0,h=function(){return kh(c,this)}),r)if(g={values:o(Ni),keys:a?h:o(Wa),entries:o(Qa)},n)for(T in g)(Mi||d||!(T in l))&&ja(l,T,g[T]);else Ah({target:e,proto:!0,forced:Mi||d},g);return n&&l[er]!==h&&ja(l,er,h,{name:r}),za[e]=h,g},Lh=function(s,e){return{value:s,done:e}},Ch=Ti,Ka=Zt,ko=ml;ei.f;var Oh=xh,Fi=Lh,wo="Array Iterator",Bh=ko.set,Mh=ko.getterFor(wo);Oh(Array,"Array",function(s,e){Bh(this,{type:wo,target:Ch(s),index:0,kind:e})},function(){var s=Mh(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,Fi(void 0,!0)):t=="keys"?Fi(i,!1):t=="values"?Fi(e[i],!1):Fi([i,e[i]],!1)},"values");Ka.Arguments=Ka.Array;var Nh=qe,Fh=Zt,Uh=Nh("iterator"),Vh=Array.prototype,Hh=function(s){return s!==void 0&&(Fh.Array===s||Vh[Uh]===s)},Gh=bs,Ja=ms,Yh=ps,qh=Zt,jh=qe,zh=jh("iterator"),_o=function(s){if(!Yh(s))return Ja(s,zh)||Ja(s,"@@iterator")||qh[Gh(s)]},Wh=dt,Qh=Gr,Kh=Lt,Jh=Hr,Xh=_o,Zh=TypeError,ef=function(s,e){var t=arguments.length<2?Xh(s):e;if(Qh(t))return Kh(Wh(t,s));throw Zh(Jh(s)+" is not iterable")},tf=dt,Xa=Lt,sf=ms,rf=function(s,e,t){var i,r;Xa(s);try{if(i=sf(s,"return"),!i){if(e==="throw")throw t;return t}i=tf(i,s)}catch(a){r=!0,i=a}if(e==="throw")throw t;if(r)throw i;return Xa(i),t},af=lo,nf=dt,of=Lt,df=Hr,uf=Hh,lf=Qr,Za=Vr,cf=ef,hf=_o,en=rf,ff=TypeError,Zi=function(s,e){this.stopped=s,this.result=e},tn=Zi.prototype,pf=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),u=af(e,i),d,l,c,h,f,m,g,T=function(E){return d&&en(d,"normal",E),new Zi(!0,E)},A=function(E){return r?(of(E),o?u(E[0],E[1],T):u(E[0],E[1])):o?u(E,T):u(E)};if(a)d=s.iterator;else if(n)d=s;else{if(l=hf(s),!l)throw ff(df(s)+" is not iterable");if(uf(l)){for(c=0,h=lf(s);h>c;c++)if(f=A(s[c]),f&&Za(tn,f))return f;return new Zi(!1)}d=cf(s,l)}for(m=a?s.next:d.next;!(g=nf(m,d)).done;){try{f=A(g.value)}catch(E){en(d,"throw",E)}if(typeof f=="object"&&f&&Za(tn,f))return f}return new Zi(!1)},mf=Yr,vf=ei,gf=gs,Sf=function(s,e,t){var i=mf(e);i in s?vf.f(s,i,gf(0,t)):s[i]=t},bf=Ss,yf=pf,Tf=Sf;bf({target:"Object",stat:!0},{fromEntries:function(e){var t={};return yf(e,function(i,r){Tf(t,i,r)},{AS_ENTRIES:!0}),t}});var Ef=Fr,$f=Ef.Object.fromEntries,Af={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},kf=Af,wf=Ye,_f=bs,Pf=Ei,sn=Zt,Df=qe,rn=Df("toStringTag");for(var tr in kf){var an=wf[tr],ir=an&&an.prototype;ir&&_f(ir)!==rn&&Pf(ir,rn,tr),sn[tr]=sn.Array}var Rf=$f,If=Rf,xf=If,Lf=xf,Qt=Mr(Lf),be;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",s[s.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(be||(be={}));var He=(s,e=0,t=be.OFFSET_P)=>{switch(t){case be.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case be.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case be.DASH_CMAF_OFFSET_P:{if(e===0)return s;const i=new URL(s);return i.searchParams.set("offset_p",e.toFixed(0)),i.toString()}default:V(t)}return s};const nn=(s,e)=>{var t;switch(e){case be.OFFSET_P:return NaN;case be.PLAYBACK_SHIFT:{const i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case be.DASH_CMAF_OFFSET_P:{const i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:V(e)}};var R=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};class ue{constructor(e){this.transitionStarted$=new L,this.transitionEnded$=new L,this.transitionUpdated$=new L,this.forceChanged$=new L,this.stateChangeStarted$=U(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=U(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||_(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const Cf=s=>{switch(s){case y.MPEG:case y.DASH:case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.HLS:case y.HLS_ONDEMAND:return!1;case y.DASH_LIVE:case y.DASH_LIVE_CMAF:case y.HLS_LIVE:case y.HLS_LIVE_CMAF:case y.DASH_LIVE_WEBM:case y.WEB_RTC_LIVE:return!0;default:return V(s)}};var q;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(q||(q={}));const Of=5,Bf=5,Mf=500,on=7e3;class Nf{constructor(e){this.subscription=new re,this.loadMediaTimeoutSubscription=new re,this.videoState=new ue(q.STOPPED),this.syncPlayback=()=>{const i=this.videoState.getState(),r=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${a}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(o)};`}),a===p.STOPPED){i!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==p.PAUSED&&o.state===z.Requested&&i!==q.STOPPED){this.seek(o.position/1e3);return}switch(a){case p.READY:{switch(i){case q.PLAYING:case q.PAUSED:case q.READY:break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:V(i)}break}case p.PLAYING:{switch(i){case q.PLAYING:break;case q.PAUSED:this.videoState.startTransitionTo(q.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case q.READY:this.videoState.startTransitionTo(q.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:V(i)}break}case p.PAUSED:{switch(i){case q.PLAYING:this.videoState.startTransitionTo(q.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case q.PAUSED:break;case q.READY:this.videoState.startTransitionTo(q.PAUSED),this.videoState.setState(q.PAUSED);break;case q.STOPPED:this.videoState.startTransitionTo(q.READY),this.prepare();break;default:V(i)}break}default:V(a)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Cf(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new re;this.subscription.add(e),this.subscription.add(U(this.videoState.stateChangeStarted$.pipe(w(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(w(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));const t=(r,a)=>this.subscription.add(r.subscribe(a));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const r=new L;e.add(r.pipe(Me(Mf)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(n=>{this.logRemoteEvent(n);const o=n.value;this.params.output.position$.next(o),(this.params.desiredState.seekState.getState().state===z.Applying||Math.abs(o-a)>Of)&&r.next(o),a=o})),e.add(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:a}=this.params.connection,n=r.value,o=this.params.output.isBuffering$.getValue(),u=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==u&&this.params.output.isBuffering$.next(u),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<Bf&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),R(this.params.desiredState.playbackState,p.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:V(n)}}),t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(B(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const i=U(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Me(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(q.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED)):(this.videoState.setState(q.PLAYING),R(this.params.desiredState.playbackState,p.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:z.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===q.PAUSED||e===q.PLAYING)&&(this.videoState.setState(q.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===q.PLAYING||e===q.PAUSED)&&(this.videoState.setState(q.PLAYING),R(this.params.desiredState.playbackState,p.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===q.READY&&this.videoState.setState(q.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===p.READY&&R(this.params.desiredState.playbackState,p.READY)}handleRemoteStop(){this.videoState.getState()!==q.STOPPED&&this.videoState.setState(q.STOPPED)}handleRemoteVolumeChange(e){var t,i;const r=this.params.output.volume$.getValue(),a={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(i=e.muted)!==null&&i!==void 0?i:r.muted};(a.volume!==r.volume||a.muted!==a.muted)&&this.params.output.volume$.next(a)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const i=this.params.source;let r,a,n;switch(e){case y.MPEG:{const l=i[e];P(l);const c=hd(Object.keys(l));P(c);const h=l[c];P(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case y.HLS:case y.HLS_ONDEMAND:{const l=i[e];P(l),r=l.url,a="application/x-mpegurl",n=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_SEP:case y.DASH_ONDEMAND:case y.DASH_WEBM:case y.DASH_WEBM_AV1:{const l=i[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_LIVE_CMAF:{const l=i[e];P(l),r=l.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const l=i[e];P(l),r=He(l.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case y.DASH:case y.DASH_LIVE:case y.WEB_RTC_LIVE:{const l="Unsupported format for Chromecast",c=new Error(l);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:C.VIDEO_PIPELINE,message:l,thrown:c}),c}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return V(e)}const o=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,a);o.contentUrl=r,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return _(u)&&(o.metadata.title=u),_(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===z.Applying||i.state===z.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(fd(on).subscribe(()=>a(`timeout(${on})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===z.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{const a=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:a}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:C.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}var Ff=s=>{let e,t=!1,i=!1;s.on("playbackTimeUpdated",({timeToEnd:r})=>{i=r<=3,t&&i&&(e==null||e())}),s.extend("MediaSourceController",function(){const{parent:r}=this,a=r.signalEndOfStream;return{signalEndOfStream:n=>{t=!0,e=()=>a(n),t&&i&&(e==null||e())}}},!0)},Uf=s=>{const e=new S(1/0),t=new L,i=new S(void 0),r=new S(void 0);let a=NaN,n=!1;const o=()=>{a=Date.now(),n=!1},u=l=>{var c,h,f,m,g;const T=Qt(l.getAllResponseHeaders().trim().split(/[\n\r]+/).map(v=>v.split(": ")));if("x-playback-duration"in T||"x-playback-duration-millis"in T){const v=parseInt((c=l.getResponseHeader("X-Playback-Duration"))!==null&&c!==void 0?c:"",10),b=parseInt((h=l.getResponseHeader("X-Playback-Duration-Millis"))!==null&&h!==void 0?h:"",10),$=(f=b!=null?b:v*1e3)!==null&&f!==void 0?f:NaN;_($)&&!isNaN($)&&e.next($)}const A=(m=T["x-delivery-type"])!==null&&m!==void 0?m:gi.HTTP1,E=(g={1:!0,0:!1}[T["x-reused"]])!==null&&g!==void 0?g:void 0;i.next(A),r.next(E)},d=l=>{l.readyState>=2&&!n&&(n=!0,t.next(Date.now()-a))};return s.extend("XHRLoader",function(){const{parent:l}=this,c=l.load.bind(l);return{load:function(h){if(h.request.type==="MPD"){const f=h.onload,m=h.progress;h.onload=function(...g){return u(this),f(...g)},h.progress=function(...g){return d(this),m(...g)},o()}return c(h)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:i}},Kt=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},Vf=s=>s.extend("RequestModifier",()=>({modifyRequestURL:Kt}),!0),Hf=s=>{s.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[r,a]=i.request.range.split("-").map(o=>parseInt(o,10)),n=new URL(i.request.url,location.href);n.searchParams.append("bytes",`${r}-${a}`),i.request.url=n.toString(),i.request.range=void 0}t(i)}}},!0)};const Ge=(s,e,t,{equal:i=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=s.getState(),o=e(),u=te(r),d=new re;return r&&d.add(r.subscribe(l=>{const c=s.getState();i(l,c)&&s.setState(l)},a)),i(o,n)||(t(n),u&&s.setState(n)),d.add(s.stateChangeStarted$.subscribe(l=>{t(l.to),u&&s.setState(l.to)},a)),d},Ct=(s,e,t)=>Ge(e,()=>s.loop,i=>{_(i)&&(s.loop=i)},{onError:t}),lt=(s,e,t,i)=>Ge(e,()=>({muted:s.muted,volume:s.volume}),r=>{_(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:i}),Tt=(s,e,t,i)=>Ge(e,()=>s.playbackRate,r=>{_(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Gf=s=>["__",s.language,s.label].join("|"),Yf=(s,e)=>{if(s.id===e)return!0;const[t,i,r]=e.split("|");return s.language===i&&s.label===r};class Ze{constructor(){this.available$=new L,this.current$=new S(void 0),this.error$=new L,this.subscription=new re,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:C.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Ge(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{_(a)&&this.setInternal(a)},{equal:(a,n)=>_(a)&&_(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(w(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Ge(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{_(a)&&this.setExternal(a)},{equal:(a,n)=>_(a)&&_(n)&&a.length===n.length&&a.every(({id:o},u)=>o===n[u].id),changed$:this.available$.pipe(w(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Ge(t.currentTextTrack,()=>{if(this.video)return;const a=this.htmlTextTracksAsArray().find(({mode:n})=>n==="showing");return a&&this.htmlTextTrackToITextTrack(a).id},a=>this.select(a),{changed$:this.current$,onError:r})),this.subscription.add(Ge(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){P(this.video);const{textTracks:e}=this.video;this.subscription.add(B(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(U(B(e,"addtrack"),B(e,"removetrack"),ke(["init"])).pipe(w(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),fe((i,r)=>i.length===r.length&&i.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(U(B(e,"change"),ke(["init"])).pipe(w(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),w(i=>i&&this.htmlTextTrackToITextTrack(i).id),fe()).subscribe(this.current$));const t=i=>{var r,a;return this.applyCueSettings((a=(r=i.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(B(e,"addtrack").subscribe(i=>{var r,a;(r=i.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var u,d,l,c,h;const f=(d=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&d!==void 0?d:null;f&&f.length&&(this.applyCueSettings((c=(l=o.target)===null||l===void 0?void 0:l.cues)!==null&&c!==void 0?c:null),(h=o.target)===null||h===void 0||h.removeEventListener("cuechange",n))};(a=i.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(B(e,"removetrack").subscribe(i=>{var r;(r=i.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const r=i;_(t.align)&&(r.align=t.align),_(t.position)&&(r.position=t.position),_(t.size)&&(r.size=t.size),_(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){P(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Ze.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,i;const{language:r,label:a}=e,n=e.id?e.id:Gf(e),o=this.externalTracks.has(n),u=n.includes("auto");return o?{id:n,type:"external",isAuto:u,language:r,label:a,url:(t=this.externalTracks.get(n))===null||t===void 0?void 0:t.url}:{id:n,type:"internal",isAuto:u,language:r,label:a,url:(i=this.internalTracks.get(n))===null||i===void 0?void 0:i.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:a})=>!this.internalTracks.has(i)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){P(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(te(e)||!Yf(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){P(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){P(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const Jr=s=>{s.removeAttribute("src"),s.load()},qf=s=>{try{s.pause(),s.playbackRate=0,Jr(s),s.remove()}catch(e){console.error(e)}};class jf{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}}const Ir=window.WeakMap?new WeakMap:new jf,ct=s=>{let e=s.querySelector("video");const t=!!e;return e?Jr(e):(e=document.createElement("video"),s.appendChild(e)),Ir.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},ht=s=>{const e=Ir.get(s);Ir.delete(s),e?Jr(s):qf(s)};class ys{constructor(){this.pausedTime=0,this.streamOffset=0,this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}}const Po=s=>{var e;let t=s;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},dn=s=>{const e=Po(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},zf=s=>{const e=Po(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)},xr=3;class Wf{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let r=this._source.buffered.start(t);const a=this._source.buffered.end(t);r>e&&r-e<xr&&(r=e),this._buffer.push({from:r,to:a,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||xr))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:r,to:a})=>{const n=r>=e&&r<t,o=a>=e&&a<t;n&&o||(n?i(t,a):o?i(r,e):r<e&&a>t?(i(t,a),i(r,e)):i(r,a))})}destroy(){this._buffer=[]}}var Do=(s,e,t=xr)=>{let i=0,r=0;for(let a=0;a<s.length;a++){const n=s.start(a),o=s.end(a);if(n<=e&&e<=o){if(i=n,r=o,!t)return{from:i,to:r};for(let u=a-1;u>=0;u--)s.end(u)+t>=i&&(i=s.start(u));for(let u=a+1;u<s.length;u++)s.start(u)-t<=r&&(r=s.end(u))}}return{from:i,to:r}};const ft=s=>{const e=v=>B(s,v).pipe(Wt(void 0)),i=U(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(v=>B(s,v))).pipe(w(v=>v.type==="ended"?s.readyState<2:s.readyState<3),fe()),r=U(B(s,"progress"),B(s,"timeupdate")).pipe(w(()=>Do(s.buffered,s.currentTime))),n=Br().browser===Mn.Safari?Ie({play:e("play").pipe(me()),playing:e("playing")}).pipe(Wt(void 0)):e("playing"),o=B(s,"volumechange").pipe(w(()=>({muted:s.muted,volume:s.volume}))),u=B(s,"ratechange").pipe(w(()=>s.playbackRate)),d=B(s,"error").pipe(se(()=>!!(s.error||s.played.length)),w(()=>{var v;const b=s.error;return{id:b?`MediaError#${b.code}`:"HtmlVideoError",category:C.VIDEO_PIPELINE,message:b?b.message:"Error event from HTML video element",thrown:(v=s.error)!==null&&v!==void 0?v:void 0}})),l=B(s,"timeupdate").pipe(w(()=>s.currentTime)),c=new L,h=.3;let f;l.subscribe(v=>{s.loop&&_(f)&&_(v)&&f>=s.duration-h&&v<=h&&c.next(f),f=v});const m=B(s,"enterpictureinpicture"),g=B(s,"leavepictureinpicture"),T=new S(zf(s));m.subscribe(()=>T.next(!0)),g.subscribe(()=>T.next(!1));const A=new S(dn(s));return B(s,"fullscreenchange").pipe(w(()=>dn(s))).subscribe(A),{playing$:n,pause$:e("pause").pipe(se(()=>!s.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:l,durationChange$:B(s,"durationchange").pipe(w(()=>s.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:o,playbackRateState$:u,inPiP$:T,inFullscreen$:A}},Xr=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var Qf=Ss,Kf=vs,Jf=Qr,Xf=Wr;Qf({target:"Array",proto:!0},{at:function(e){var t=Kf(this),i=Jf(t),r=Xf(e),a=r>=0?r:i+r;return a<0||a>=i?void 0:t[a]}});var Zf=Ur,Ro=Zf,ep=Ro,tp=ep("Array","at"),ip=tp,sp=ip,rp=sp,ap=rp,Qe=Mr(ap);let Zr=!1,it={};const np=s=>{Zr=s},op=()=>{it={}},dp=s=>{s(it)},Ui=(s,e)=>{var t;Zr&&(it.meta=(t=it.meta)!==null&&t!==void 0?t:{},it.meta[s]=e)};class Ke{constructor(e){this.name=e}next(e){var t,i;if(!Zr)return;it.series=(t=it.series)!==null&&t!==void 0?t:{};const r=(i=it.series[this.name])!==null&&i!==void 0?i:[];r.push([Date.now(),e]),it.series[this.name]=r}}var Pt;(function(s){s.FitsContainer="FitsContainer",s.FitsThroughput="FitsThroughput",s.Buffer="Buffer",s.DroppedFramesLimit="DroppedFramesLimit",s.FitsQualityLimits="FitsQualityLimits"})(Pt||(Pt={}));const up=new Ke("best_bitrate"),lp=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class cp{constructor(){this.history={}}recordSelection(e){this.history[e.id]=pe()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const ti=(s,{container:e,throughput:t,tuning:i,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:u,history:d,droppedVideoMaxQualityLimit:l,abrLogger:c})=>{var h,f,m,g,T;const A=i.usePixelRatio&&(h=window.devicePixelRatio)!==null&&h!==void 0?h:1,E=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*A*i.containerSizeFactor,height:e.height*A*i.containerSizeFactor},v=E&&Rt(E),b=i.considerPlaybackRate&&_(o)?o:1,$=s.filter(F=>!vi(F.quality)).sort((F,I)=>pi(F.quality,I.quality)?-1:1),D=(f=Qe($,-1))===null||f===void 0?void 0:f.quality,Y=(m=Qe($,0))===null||m===void 0?void 0:m.quality,J=te(r)||_(r.min)&&_(r.max)&&Ki(r.max,r.min)||_(r.min)&&Y&&pi(r.min,Y)||_(r.max)&&D&&Ki(r.max,D),N=b*lp(n!=null?n:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),G={},O=$.filter(F=>(v?Ki(F.quality,v):!0)?(_(t)&&isFinite(t)&&_(F.bitrate)?t-a>=F.bitrate*N:!0)?i.lazyQualitySwitch&&_(i.minBufferToSwitchUp)&&u&&!vi(u.quality)&&(n!=null?n:0)<i.minBufferToSwitchUp&&pi(F.quality,u.quality)?(G[F.quality]=Pt.Buffer,!1):!!l&&Tr(F.quality,l)?(G[F.quality]=Pt.DroppedFramesLimit,!1):J||(te(r.max)||Nn(F.quality,r.max))&&(te(r.min)||Tr(F.quality,r.min))?!0:(G[F.quality]=Pt.FitsQualityLimits,!1):(G[F.quality]=Pt.FitsThroughput,!1):(G[F.quality]=Pt.FitsContainer,!1))[0];O&&O.bitrate&&up.next(O.bitrate);const H=(g=O!=null?O:$[Math.ceil(($.length-1)/2)])!==null&&g!==void 0?g:s[0];H.quality!==((T=d==null?void 0:d.last)===null||T===void 0?void 0:T.quality)&&c({message:`
7
7
  [available tracks] ${s.map(F=>F.quality).join(", ")}
8
8
 
9
9
  [limit params]
@@ -35,4 +35,4 @@ precision highp float;
35
35
  #endif
36
36
  #define PI 3.14159265358979323846264
37
37
  varying vec2 v_texel;uniform sampler2D u_texture;uniform vec2 u_focus;void main(void){float lambda0=u_focus.x/360.0;float phi0=u_focus.y/180.0;float lambda=PI*2.0*(v_texel.x-0.5-lambda0);float phi=PI*(v_texel.y-0.5-phi0);float p=sqrt(lambda*lambda+phi*phi);float c=atan(p);float cos_c=cos(c);float sin_c=sin(c);float x=lambda0+atan(lambda*sin_c,p*cos(phi0)*cos_c-phi*sin(phi0)*sin_c);float y=asin(cos_c*sin(phi0)+(phi*sin_c*cos(phi0))/p);vec2 tc=vec2(mod(x/(PI*2.0)-0.5,1.0),mod(y/PI-0.5,1.0));gl_FragColor=texture2D(u_texture,tc);}`;class fv{constructor(e,t,i){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();const r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new uv(this.params.fov,this.params.orientation),this.cameraRotationManager=new lv(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),a=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(a,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(cv,this.gl.VERTEX_SHADER),i=this.createShader(hv,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1;const r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-i,n=t-r,o=e+i,u=t-r,d=e+i,l=t+r,c=e-i,h=t+r;return[a,n,o,u,d,l,c,h]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){const e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}}class Yo{constructor(e){this.subscription=new re,this.videoState=new ue(le.STOPPED),this.elementSize$=new S(void 0),this.textTracksManager=new Ze,this.droppedFramesManager=new Ts,this.videoTracks$=new S([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new cp,this.textTracks=[],this.syncPlayback=()=>{var t,i,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(u.state===z.Requested&&(o==null?void 0:o.to)!==p.PAUSED&&a!==le.STOPPED&&n!==p.STOPPED){const l=(i=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&i!==void 0?i:0;this.seek(u.position-l,u.forcePrecise)}if(n===p.STOPPED){a!==le.STOPPED&&(this.videoState.startTransitionTo(le.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(le.STOPPED),R(this.params.desiredState.playbackState,p.STOPPED,!0));return}switch(a){case le.STOPPED:this.videoState.startTransitionTo(le.READY),this.prepare();return;case le.READY:n===p.PAUSED?(this.videoState.setState(le.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING?(this.videoState.startTransitionTo(le.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.READY&&R(this.params.desiredState.playbackState,p.READY);return;case le.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(le.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&R(this.params.desiredState.playbackState,p.PLAYING);return;case le.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(le.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&R(this.params.desiredState.playbackState,p.PAUSED);return;default:return V(a)}}},this.init3DScene=t=>{var i,r,a;if(this.scene3D)return;this.scene3D=new fv(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=t.projectionData)===null||i===void 0?void 0:i.pose.yaw)||0,y:((r=t.projectionData)===null||r===void 0?void 0:r.pose.pitch)||0,z:((a=t.projectionData)===null||a===void 0?void 0:a.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const n=this.elementSize$.getValue();n&&this.scene3D.setViewportSize(n.width,n.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=ct(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new dv({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=ft(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:C.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:(o,u)=>this.subscription.add(o.subscribe(u,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:a}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(w(d=>d.map(({track:l})=>l)))}),a(i.ended$,e.endedEvent$),a(i.looped$,e.loopedEvent$),a(i.error$,e.error$),a(i.isBuffering$,e.isBuffering$),a(i.currentBuffer$,e.currentBuffer$),a(i.playing$,e.firstFrameEvent$),a(i.canplay$,e.canplay$),a(i.inPiP$,e.inPiP$),a(i.inFullscreen$,e.inFullscreen$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.isLive$,e.isLive$),a(this.player.lastRequestFirstBytes$.pipe(se(_),me()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Ct(this.video,t.isLooped,r)),this.subscription.add(lt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Tt(this.video,t.playbackRate,i.playbackRateState$,r)),a(ns(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(le.PLAYING),R(t.playbackState,p.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(le.PAUSED),R(t.playbackState,p.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===le.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var l;if(d===Oe.MANIFEST_READY){const c=[];this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();P(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((A,E)=>E.bitrate-A.bitrate),m=Array.from(h.video).sort((A,E)=>E.bitrate-A.bitrate),g=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const A of f){const E=gm(A);E&&this.audioTracks.push({track:E,representation:A})}for(const A of m){const E=vm(A);if(E){c.push({track:E,representation:A});const v=!this.params.tuning.isAudioDisabled&&Sm(f,m,A);v&&this.audioRepresentations.set(A.id,v)}}this.videoTracks$.next(c);for(const A of g){const E=bm(A);E&&this.textTracks.push({track:E,representation:A})}this.params.output.availableVideoTracks$.next(c.map(({track:A})=>A)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:A})=>A)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:A})=>A));const T=this.selectVideoRepresentation();P(T),this.player.initRepresentations(T.id,(l=this.audioRepresentations.get(T.id))===null||l===void 0?void 0:l.id)}else d===Oe.REPRESENTATIOS_READY&&(this.videoState.setState(le.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:C.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(U(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,B(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),l=this.player.state$.getTransition();if(d!==Oe.RUNNING||l||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation(),h=this.params.desiredState.autoVideoTrackLimits.getTransition();if(h&&this.params.output.autoVideoTrackLimits$.next(h.to),c){this.player.switchRepresentation(Te.VIDEO,c.id).catch(n);const f=this.audioRepresentations.get(c.id);f&&this.player.switchRepresentation(Te.AUDIO,f.id).catch(n)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:d})=>{this.scene3D&&d&&this.scene3D.pointCameraTo(d.x,d.y)})),this.subscription.add(this.elementSize$.subscribe(d=>{this.scene3D&&d&&this.scene3D.setViewportSize(d.width,d.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(fe(),w(d=>{var l;return d&&((l=this.videoTracks$.getValue().find(({representation:{id:c}})=>c===d))===null||l===void 0?void 0:l.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var l,c;if(d!=null&&d.is3dVideo&&(!((l=this.params.tuning.spherical)===null||l===void 0)&&l.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${h}`})}else this.destroy3DScene(),!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled&&e.is3DVideo$.next(!1)},r)),this.textTracksManager.connect(this.video,t,e);const o=t.playbackState.stateChangeStarted$.pipe(w(({to:d})=>d===p.READY),fe());this.subscription.add(U(o,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const d=t.autoVideoTrackSwitching.getState(),c=t.playbackState.getState()===p.READY?this.params.tuning.dash.forwardBufferTargetPreload:d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(c)})),this.subscription.add(U(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===p.READY)));const u=U(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Me(0));this.subscription.add(u.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,i,r,a,n;const o=this.params.desiredState.autoVideoTrackSwitching.getState(),u=this.params.desiredState.videoTrack.getState(),d=(e=this.videoTracks$.getValue().find(({track:{id:A}})=>A===u))===null||e===void 0?void 0:e.track,l=this.params.output.currentVideoTrack$.getValue(),c=bt(this.video.buffered,this.video.currentTime*1e3),h=o?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,f=Math.min(c/Math.min(h,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=Math.max(d&&!o&&(i=(t=this.audioRepresentations.get(d.id))===null||t===void 0?void 0:t.bitrate)!==null&&i!==void 0?i:0,l&&(a=(r=this.audioRepresentations.get(l.id))===null||r===void 0?void 0:r.bitrate)!==null&&a!==void 0?a:0),g=ti(this.videoTracks$.getValue().map(({track:A})=>A),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:m,forwardBufferHealth:f,current:l,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),T=o?g!=null?g:d:d!=null?d:g;return T&&((n=this.videoTracks$.getValue().find(({track:A})=>A===T))===null||n===void 0?void 0:n.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Et(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(le.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),ht(this.video)}}class pv extends Yo{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}class mv extends Yo{constructor(e){super(e),this.liveOffset=new ys}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(Ie({interval:is(Cr),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()===le.PLAYING){const n=e.position$.getValue()+(r-1);e.position$.next(n),(a=this.liveOffset)===null||a===void 0||a.resetTo(-n*1e3)}})).add(Ie({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(w(({liveBufferTime:r,liveAvailabilityStartTime:a})=>r&&a?r+a:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t===p.PAUSED&&i===le.PAUSED,a=-e,n=Math.trunc(a/1e3<=Math.abs(this.params.output.duration$.getValue())?a:0);this.player.seekLive(n).then(()=>{var o;this.params.output.position$.next(e/1e3),(o=this.liveOffset)===null||o===void 0||o.resetTo(n,r)})}}const We={};var ie;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(ie||(ie={}));const ci=(s,e)=>new cs(t=>{const i=(r,a)=>t.next(a);return s.on(e,i),()=>s.off(e,i)});class vv{constructor(e){this.subscription=new re,this.videoState=new ue(ie.INITIALIZING),this.textTracksManager=new Ze,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(t!==ie.INITIALIZING)switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===z.Requested&&this.seek(a.position),i){case p.STOPPED:switch(t){case ie.STOPPED:break;case ie.READY:case ie.PLAYING:case ie.PAUSED:this.stop();break;default:V(t)}break;case p.READY:switch(t){case ie.STOPPED:this.prepare();break;case ie.READY:case ie.PLAYING:case ie.PAUSED:break;default:V(t)}break;case p.PLAYING:switch(t){case ie.PLAYING:break;case ie.STOPPED:this.prepare();break;case ie.READY:case ie.PAUSED:this.playIfAllowed();break;default:V(t)}break;case p.PAUSED:switch(t){case ie.PAUSED:break;case ie.STOPPED:this.prepare();break;case ie.READY:this.videoState.setState(ie.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED);break;case ie.PLAYING:this.pause();break;default:V(t)}break;default:V(i)}},this.video=ct(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(we(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)===null||e===void 0||e.detachMedia(),(t=this.hls)===null||t===void 0||t.destroy(),this.params.output.element$.next(void 0),ht(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:C.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(r=>{e||(We.Hls=r.default,We.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){P(We.Hls,"hls.js not loaded"),this.hls=new We.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(ie.STOPPED)}subscribe(){P(We.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=d=>{t.error$.next({id:"HlsJsProvider",category:C.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=ft(this.video),a=(d,l)=>this.subscription.add(d.subscribe(l,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(Ct(this.video,e.isLooped,i)),this.subscription.add(lt(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Tt(this.video,e.playbackRate,r.playbackRateState$,i)),this.subscription.add(ci(this.hls,We.Events.ERROR).subscribe(d=>{var l;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:C.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${(l=d.err)===null||l===void 0?void 0:l.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ie.PLAYING),R(e.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ie.PAUSED),R(e.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())===null||d===void 0?void 0:d.to)===ie.READY&&this.videoState.setState(ie.READY),this.videoState.getState()===ie.PLAYING&&this.playIfAllowed()},i)),a(ci(this.hls,We.Events.MANIFEST_PARSED).pipe(w(({levels:d})=>d.reduce((l,c)=>{var h,f;const m=c.name||c.height.toString(10),{width:g,height:T}=c,A=(f=Ai((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:Rt({width:g,height:T});if(!A)return l;const E=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,v={id:m.toString(),quality:A,bitrate:c.bitrate/1e3,size:{width:g,height:T},fps:E};return this.trackLevels.set(m,{track:v,level:c}),l.push(v),l},[]))),t.availableVideoTracks$),a(ci(this.hls,We.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){const l=[];for(const c of d.subtitleTracks){const h=c.name,f=c.attrs.URI||"",m=c.lang,g="internal";l.push({id:h,url:f,language:m,type:g})}e.internalTextTracks.startTransitionTo(l)}}),a(ci(this.hls,We.Events.LEVEL_LOADING).pipe(w(({url:d})=>we(d))),t.hostname$),this.subscription.add(Ge(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:i}));const n=d=>{var l;return(l=Array.from(this.trackLevels.values()).find(({level:c})=>c===d))===null||l===void 0?void 0:l.track},o=ci(this.hls,We.Events.LEVEL_SWITCHED).pipe(w(({level:d})=>n(this.hls.levels[d])));o.pipe(se(_)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Ge(e.videoTrack,()=>{var d;return(d=n(this.hls.levels[this.hls.currentLevel]))===null||d===void 0?void 0:d.id},d=>{var l;if(te(d))return;const c=(l=this.trackLevels.get(d))===null||l===void 0?void 0:l.level;if(!c)return;const h=this.hls.levels.indexOf(c),f=this.hls.currentLevel,m=this.hls.levels[f];!m||c.bitrate>m.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o.pipe(w(d=>d==null?void 0:d.id)),onError:i})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const u=U(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Me(0));this.subscription.add(u.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(ie.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(ie.PLAYING),await Et(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.DOM,thrown:t}))||(this.videoState.setState(ie.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED,!0))}pause(){this.videoState.startTransitionTo(ie.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(ie.STOPPED),R(this.params.desiredState.playbackState,p.STOPPED,!0)}}const An="X-Playback-Duration";var kn=async s=>{var e;const t=await bi(s),i=await t.text(),r=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(i))===null||e===void 0?void 0:e[1];return r?parseInt(r,10):t.headers.has(An)?parseInt(t.headers.get(An),10):void 0};const gv=s=>{let e=null;if(s.QUALITY&&(e=Ai(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=Rt({width:t,height:i})}return e!=null?e:null},qo=async(s,e=s)=>{var t,i;const n=(await(await bi(s)).text()).split(`
38
- `),o=[],u=[];for(let d=0;d<n.length;d++){const l=n[d],c=l.match(/^#EXT-X-STREAM-INF:(.+)/),h=l.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!c&&!h)){if(c){const f=Qt(c[1].split(",").map(b=>b.split("="))),m=(t=f.QUALITY)!==null&&t!==void 0?t:`stream-${f.BANDWIDTH}`,g=gv(f);let T;f.BANDWIDTH&&(T=parseInt(f.BANDWIDTH,10)/1e3||void 0),!T&&f["AVERAGE-BANDWIDTH"]&&(T=parseInt(f["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const A=f["FRAME-RATE"]?parseFloat(f["FRAME-RATE"]):void 0;let E;if(f.RESOLUTION){const[b,$]=f.RESOLUTION.split("x").map(D=>parseInt(D,10));b&&$&&(E={width:b,height:$})}const v=new URL(n[++d],e).toString();g&&o.push({id:m,quality:g,url:v,bandwidth:T,size:E,fps:A})}if(h){const f=Qt(h[1].split(",").map(A=>A.split("=")).map(([A,E])=>[A,E.replace(/^"|"$/g,"")])),m=(i=f.URI)===null||i===void 0?void 0:i.replace(/playlist$/,"subtitles.vtt"),g=f.LANGUAGE,T=f.NAME;m&&g&&u.push({type:"internal",id:g,label:T,language:g,url:m,isAuto:!1})}}}return{qualityManifests:o,textTracks:u}};var ne;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(ne||(ne={}));class Sv{constructor(e){var t;this.subscription=new re,this.videoState=new ue(ne.STOPPED),this.textTracksManager=new Ze,this.manifests$=new S([]),this.liveOffset=new ys,this.manifestStartTime$=new S(void 0),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(n===p.STOPPED){a!==ne.STOPPED&&(this.videoState.startTransitionTo(ne.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ne.STOPPED),R(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(a===ne.STOPPED){this.videoState.startTransitionTo(ne.READY),this.prepare();return}if(u||d){const h=this.videoState.getState();this.videoState.setState(ne.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),c.state===z.None&&this.params.desiredState.seekState.setState({state:z.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==p.PAUSED&&c.state===z.Requested){this.videoState.startTransitionTo(ne.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(a){case ne.READY:n===p.READY?R(this.params.desiredState.playbackState,p.READY):n===p.PAUSED?(this.videoState.setState(ne.PAUSED),this.liveOffset.pause(),R(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING&&(this.videoState.startTransitionTo(ne.PLAYING),this.playIfAllowed());return;case ne.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(ne.PAUSED),this.liveOffset.pause(),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&R(this.params.desiredState.playbackState,p.PLAYING);return;case ne.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(ne.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)===p.PAUSED&&(R(this.params.desiredState.playbackState,p.PAUSED),this.liveOffset.pause());return;case ne.CHANGING_MANIFEST:break;default:return V(a)}},this.params=e,this.video=ct(e.container),this.params.output.element$.next(this.video);const i={id:"master",quality:Ce.INVARIANT,url:this.params.source.url};qo(He(this.params.source.url),this.params.source.url).then(({qualityManifests:r})=>{this.manifests$.next([i,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:C.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(we(this.params.source.url)),this.maxSeekBackTime$=new S((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:r}=this.params.desiredState,a=i.getState(),n=r.getTransition(),o=(t=(e=n==null?void 0:n.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",u=this.manifests$.getValue();if(!u.length)return;const d=a?"master":o;return a&&!n&&r.startTransitionTo("master"),u.find(l=>l.id===d)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:C.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=ft(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(lt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Tt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ne.PLAYING),R(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ne.PAUSED),R(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ne.READY&&this.videoState.setState(ne.READY),this.videoState.getState()===ne.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(fe(),w(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&_(d.to)){const c=d.to;this.params.desiredState.videoTrack.setState(c);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(we(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===ne.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===z.Requested&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var o,u,d;const l=(d=(u=(o=this.video)===null||o===void 0?void 0:o.getStartDate)===null||u===void 0?void 0:u.call(o))===null||d===void 0?void 0:d.getTime();this.manifestStartTime$.next(l||void 0)},i)),this.subscription.add(Ie({startTime:this.manifestStartTime$.pipe(se(_)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(w(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));const n=U(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.manifests$,ke(["init"])).pipe(Me(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ht(this.video)}prepare(){const e=this.selectManifest();if(te(e))return;const t=this.params.format===y.HLS_LIVE_CMAF?be.DASH_CMAF_OFFSET_P:be.OFFSET_P,i=He(e.url,this.liveOffset.getTotalOffset(),t);this.video.setAttribute("src",i),this.video.load(),kn(i).then(r=>{var a;if(!te(r))this.maxSeekBackTime$.next(r);else{const n=(a=this.params.source.maxSeekBackTime)!==null&&a!==void 0?a:this.maxSeekBackTime$.getValue();if(te(n)||!isFinite(n))try{bi(i).then(o=>o.text()).then(o=>{var u;const d=(u=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(o))===null||u===void 0?void 0:u[1];if(d){const l=new URL(d,i).toString();kn(l).then(c=>{te(c)||this.maxSeekBackTime$.next(c)})}})}catch(o){}}})}playIfAllowed(){Et(this.video).then(e=>{e||(this.videoState.setState(ne.PAUSED),this.liveOffset.pause(),R(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}var de;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(de||(de={}));class bv{constructor(e){this.subscription=new re,this.videoState=new ue(de.STOPPED),this.textTracksManager=new Ze,this.manifests$=new S([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const r=this.videoState.getState(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a===p.STOPPED){r!==de.STOPPED&&(this.videoState.startTransitionTo(de.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(de.STOPPED),R(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(r===de.STOPPED){this.videoState.startTransitionTo(de.READY),this.prepare();return}if(o||u){const c=this.videoState.getState();this.videoState.setState(de.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),l.state===z.None&&this.params.desiredState.seekState.setState({state:z.Requested,position:h*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==p.PAUSED&&l.state===z.Requested&&this.seek(l.position),r){case de.READY:a===p.READY?R(this.params.desiredState.playbackState,p.READY):a===p.PAUSED?(this.videoState.setState(de.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED)):a===p.PLAYING&&(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed());return;case de.PLAYING:a===p.PAUSED?(this.videoState.startTransitionTo(de.PAUSED),this.video.pause()):(n==null?void 0:n.to)===p.PLAYING&&R(this.params.desiredState.playbackState,p.PLAYING);return;case de.PAUSED:a===p.PLAYING?(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===p.PAUSED&&R(this.params.desiredState.playbackState,p.PAUSED);return;case de.CHANGING_MANIFEST:break;default:return V(r)}},this.params=e,this.video=ct(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:Ce.INVARIANT,url:this.params.source.url};this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(we(this.params.source.url)),qo(this.params.source.url).then(({qualityManifests:i,textTracks:r})=>{this.manifests$.next([t,...i]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:C.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:r}=this.params.desiredState,a=i.getState(),n=r.getTransition(),o=(t=(e=n==null?void 0:n.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",u=this.manifests$.getValue();if(!u.length)return;const d=a?"master":o;return a&&!n&&r.startTransitionTo("master"),u.find(l=>l.id===d)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:C.WTF,message:"HlsProvider internal logic error",thrown:o})},r=ft(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(Ct(this.video,t.isLooped,i)),this.subscription.add(lt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Tt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(de.PLAYING),R(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED),R(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===de.READY&&this.videoState.setState(de.READY),this.videoState.getState()===de.PLAYING&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&_(d.to)){const c=d.to;this.params.desiredState.videoTrack.setState(c);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(we(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===de.CHANGING_MANIFEST&&this.videoState.setState(u.to),o.state===z.Requested&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(w(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!this.params.tuning.useNativeHLSTextTracks){const{textTracks:o}=this.video;this.subscription.add(U(B(o,"addtrack"),B(o,"removetrack"),B(o,"change"),ke(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}const n=U(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,ke(["init"])).pipe(Me(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ht(this.video)}prepare(){const e=this.selectManifest();te(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){Et(this.video).then(e=>{e||(this.videoState.setState(de.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var ce;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(ce||(ce={}));class yv{constructor(e){this.subscription=new re,this.videoState=new ue(ce.STOPPED),this.trackUrls={},this.textTracksManager=new Ze,this.syncPlayback=()=>{var t,i,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition();if(n===p.STOPPED){a!==ce.STOPPED&&(this.videoState.startTransitionTo(ce.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ce.STOPPED),R(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.autoVideoTrackLimits.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.seekState.getState();if(d&&a!==ce.READY&&!l){this.handleQualityLimitTransition(d.to.max);return}if(a===ce.STOPPED){this.videoState.startTransitionTo(ce.READY),this.prepare();return}if(l){const{currentTime:h}=this.video;this.prepare(),c.state===z.None&&this.params.desiredState.seekState.setState({state:z.Requested,position:h*1e3,forcePrecise:!0}),l.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((r=(i=this.trackUrls[l.to])===null||i===void 0?void 0:i.track)===null||r===void 0?void 0:r.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((o==null?void 0:o.to)!==p.PAUSED&&c.state===z.Requested&&this.seek(c.position),a){case ce.READY:n===p.READY?R(this.params.desiredState.playbackState,p.READY):n===p.PAUSED?(this.videoState.setState(ce.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING&&(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed());return;case ce.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(ce.PAUSED),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&R(this.params.desiredState.playbackState,p.PLAYING);return;case ce.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&R(this.params.desiredState.playbackState,p.PAUSED);return;default:return V(a)}},this.params=e,this.video=ct(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{const a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:C.WTF,message:"MpegProvider internal logic error",thrown:o})},r=ft(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(Ct(this.video,t.isLooped,i)),this.subscription.add(lt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Tt(this.video,t.playbackRate,r.playbackRateState$,i)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ce.PLAYING),R(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ce.PAUSED),R(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ce.READY&&this.videoState.setState(ce.READY);const u=this.params.desiredState.videoTrack.getTransition();u&&_(u.to)&&(this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to].track)),this.videoState.getState()===ce.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const n=U(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Me(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ht(this.video)}prepare(){const e=this.params.desiredState.videoTrack.getState();P(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];P(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Kt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(we(t))}playIfAllowed(){Et(this.video).then(e=>{e||(this.videoState.setState(ce.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,i,r;let a;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const n=(i=Object.values(this.trackUrls).find(d=>Nn(d.track.quality,e)))===null||i===void 0?void 0:i.track,o=this.params.desiredState.videoTrack.getState(),u=(r=this.trackUrls[o!=null?o:"0"])===null||r===void 0?void 0:r.track;n&&u&&Tr(u.quality,n.quality)&&(a=n)}else if(!e){const n=Object.values(this.trackUrls).map(o=>o.track);a=ti(n,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}a&&(this.params.output.currentVideoTrack$.next(a),this.params.desiredState.videoTrack.startTransitionTo(a.id)),this.params.output.autoVideoTrackLimits$.next({max:e})}}const wn=["stun:videostun.mycdn.me:80"],Tv=1e3,Ev=3,dr=()=>null;class $v{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=dr,this.externalStopCallback=dr,this.externalErrorCallback=dr,this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:wn}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:C.WTF,message:e.message})}async onPeerConnectionStream(e){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),Tv)}normalizeOptions(e={}){const t={stunServerList:wn,maxRetryNumber:Ev,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var oe;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(oe||(oe={}));class Av{constructor(e){this.videoState=new ue(oe.STOPPED),this.maxSeekBackTime$=new S(0),this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(i===p.STOPPED){t!==oe.STOPPED&&(this.videoState.startTransitionTo(oe.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(oe.STOPPED),R(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===oe.STOPPED){this.videoState.startTransitionTo(oe.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case oe.READY:i===p.PAUSED?(this.videoState.setState(oe.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED)):i===p.PLAYING&&(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed());return;case oe.PLAYING:i===p.PAUSED?(this.videoState.startTransitionTo(oe.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&R(this.params.desiredState.playbackState,p.PLAYING);return;case oe.PAUSED:i===p.PLAYING?(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&R(this.params.desiredState.playbackState,p.PAUSED);return;default:return V(t)}},this.subscription=new re,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ct(e.container),this.liveStreamClient=new $v(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ht(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:C.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};U(this.videoState.stateChangeStarted$.pipe(w(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(w(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const r=ft(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())===null||n===void 0?void 0:n.to)===oe.READY&&this.videoState.setState(oe.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(oe.PAUSED)},i)).add(r.playing$.subscribe(()=>{this.videoState.setState(oe.PLAYING)},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(lt(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case oe.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(p.STOPPED);break;case oe.READY:break;case oe.PAUSED:t.playbackState.setState(p.PAUSED);break;case oe.PLAYING:t.playbackState.setState(p.PLAYING);break;default:return V(n.to)}},i)).add(U(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Me(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:Ce.INVARIANT}),this.video.srcObject=e,R(this.params.desiredState.playbackState,p.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(oe.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:C.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Et(this.video).then(e=>{e||(this.videoState.setState(oe.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class _n{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!!this.current.done}}var ur,lr,cr,hr,fr,pr,Yi,mr,qi,vr,ji,gr,zi,Sr,Wi,br,Qi,yr;const jo=Br().device===vd.Android,yt=document.createElement("video"),kv='video/mp4; codecs="avc1.42000a,mp4a.40.2"',wv='video/mp4; codecs="hev1.1.6.L93.B0"',zo='video/webm; codecs="vp09.00.10.08"',Wo='video/webm; codecs="av01.0.00M.08"',_v='audio/mp4; codecs="mp4a.40.2"',Pv='audio/webm; codecs="opus"',Ue={mse:!!(window.MediaSource&&window.MediaStreamTrack&&(!((lr=(ur=window.SourceBuffer)===null||ur===void 0?void 0:ur.prototype)===null||lr===void 0)&&lr.appendBuffer)),hls:!!(!((cr=yt.canPlayType)===null||cr===void 0)&&cr.call(yt,"application/x-mpegurl")||!((hr=yt.canPlayType)===null||hr===void 0)&&hr.call(yt,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},De={mp4:!!(!((fr=yt.canPlayType)===null||fr===void 0)&&fr.call(yt,"video/mp4")),webm:!!(!((pr=yt.canPlayType)===null||pr===void 0)&&pr.call(yt,"video/webm")),cmaf:!0},Xe={h264:!!(!((mr=(Yi=window.MediaSource)===null||Yi===void 0?void 0:Yi.isTypeSupported)===null||mr===void 0)&&mr.call(Yi,kv)),h265:!!(!((vr=(qi=window.MediaSource)===null||qi===void 0?void 0:qi.isTypeSupported)===null||vr===void 0)&&vr.call(qi,wv)),vp9:!!(!((gr=(ji=window.MediaSource)===null||ji===void 0?void 0:ji.isTypeSupported)===null||gr===void 0)&&gr.call(ji,zo)),av1:!!(!((Sr=(zi=window.MediaSource)===null||zi===void 0?void 0:zi.isTypeSupported)===null||Sr===void 0)&&Sr.call(zi,Wo)),aac:!!(!((br=(Wi=window.MediaSource)===null||Wi===void 0?void 0:Wi.isTypeSupported)===null||br===void 0)&&br.call(Wi,_v)),opus:!!(!((yr=(Qi=window.MediaSource)===null||Qi===void 0?void 0:Qi.isTypeSupported)===null||yr===void 0)&&yr.call(Qi,Pv))},Yt=(Xe.h264||Xe.h265)&&Xe.aac;var St;(function(s){s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient"})(St||(St={}));var rt;(function(s){s.DASH="dash",s.HLS="hls",s.MPEG="mpeg"})(rt||(rt={}));let _t;const Dv=async()=>{if(!window.navigator.mediaCapabilities)return;const s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:Wo}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:zo}})]);_t={[y.DASH_WEBM_AV1]:e,[y.DASH_WEBM]:t}};try{Dv()}catch(s){console.error(s)}const yi=Ue.hls&&De.mp4,Rv=()=>Object.keys(Xe).filter(s=>Xe[s]),Iv=(s,e=!1)=>s.filter(t=>{switch(t){case y.DASH:return Ue.mse&&De.mp4&&Yt;case y.DASH_SEP:return Ue.mse&&De.mp4&&Yt;case y.DASH_WEBM:return Ue.mse&&De.webm&&Xe.vp9&&Xe.opus;case y.DASH_WEBM_AV1:return Ue.mse&&De.webm&&Xe.av1&&Xe.opus;case y.DASH_LIVE:return Ue.mse&&De.mp4&&Yt;case y.DASH_LIVE_CMAF:return Ue.mse&&De.mp4&&Yt&&De.cmaf;case y.DASH_ONDEMAND:return Ue.mse&&De.mp4&&Yt;case y.HLS:case y.HLS_ONDEMAND:return yi||e&&Ue.mse&&De.mp4&&Yt;case y.HLS_LIVE:case y.HLS_LIVE_CMAF:return yi;case y.MPEG:return De.mp4;case y.DASH_LIVE_WEBM:return!1;case y.WEB_RTC_LIVE:return Ue.webrtc&&Ue.ws&&Xe.h264&&(De.mp4||De.webm);default:return V(t)}}),hi=s=>{const e=y.DASH_WEBM,t=y.DASH_WEBM_AV1;switch(s){case St.VP9:return[e,t];case St.AV1:return[t,e];case St.NONE:return[];case St.SMOOTH:return _t?_t[t].smooth?[t,e]:_t[e].smooth?[e,t]:[t,e]:[e,t];case St.POWER_EFFICIENT:return _t?_t[t].powerEfficient?[t,e]:_t[e].powerEfficient?[e,t]:[t,e]:[e,t];default:V(s)}return[e,t]},xv=({webmCodec:s,androidPreferredFormat:e})=>{if(jo)switch(e){case rt.MPEG:return[y.MPEG,...hi(s),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND];case rt.HLS:return[y.HLS,y.HLS_ONDEMAND,...hi(s),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.MPEG];case rt.DASH:return[...hi(s),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG]}return yi?[...hi(s),y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG,y.DASH]:[...hi(s),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG]},Lv=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{const i=e?[y.DASH_LIVE_CMAF,y.DASH_LIVE]:[y.DASH_LIVE,y.DASH_LIVE_CMAF],r=e?[y.HLS_LIVE_CMAF,y.HLS_LIVE]:[y.HLS_LIVE,y.HLS_LIVE_CMAF],a=[...i,...r],n=[...r,...i];let o;if(jo)switch(s){case rt.DASH:{o=a;break}case rt.HLS:case rt.MPEG:{o=n;break}}else yi?o=n:o=a;return t?[y.WEB_RTC_LIVE,...o]:[...o,y.WEB_RTC_LIVE]},Pn=s=>s?[y.HLS_LIVE,y.HLS_LIVE_CMAF,y.DASH_LIVE_CMAF]:[y.DASH_WEBM,y.DASH_WEBM_AV1,y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG];var Cv=s=>new cs(e=>{const t=new re,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(w(({from:d,to:l})=>`${d}-${l}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(w(({type:d})=>d!==void 0)),n=new L;let o=0,u="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>n.next(d),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const Ov={cacheDuration:12e4},Bv={chunkDuration:5e3,maxParallelRequests:5};class Mv{constructor(e){this.current$=new S({type:void 0}),this.providerError$=new L,this.noAvailableProvidersError$=new L,this.providerOutput={position$:new S(0),duration$:new S(1/0),volume$:new S({muted:!1,volume:1}),currentVideoTrack$:new S(void 0),availableVideoTracks$:new S([]),availableAudioTracks$:new S([]),isAudioAvailable$:new S(!0),autoVideoTrackLimitingAvailable$:new S(!1),autoVideoTrackLimits$:new S(void 0),currentBuffer$:new S(void 0),isBuffering$:new S(!0),error$:new L,warning$:new L,willSeekEvent$:new L,seekedEvent$:new L,loopedEvent$:new L,endedEvent$:new L,firstBytesEvent$:new L,firstFrameEvent$:new L,canplay$:new L,isLive$:new S(void 0),isLowLatency$:new S(!1),canChangePlaybackSpeed$:new S(!0),liveTime$:new S(void 0),liveBufferTime$:new S(void 0),availableTextTracks$:new S([]),currentTextTrack$:new S(void 0),hostname$:new S(void 0),httpConnectionType$:new S(void 0),httpConnectionReused$:new S(void 0),inPiP$:new S(!1),inFullscreen$:new S(!1),element$:new S(void 0),availableSources$:new S(void 0),is3DVideo$:new S(!1)},this.subscription=new re,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Iv([...Lv(this.params.tuning),...xv(this.params.tuning)],this.params.tuning.useHlsJs).filter(o=>_(e.sources[o])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning;let a=[];i?a=[i]:r.length?a=[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new _n(a);const n=[...Pn(!0),...Pn(!1)];this.chromecastFormatsIterator=new _n(n.filter(o=>_(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(te(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:C.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!==z.None;if(this.params.desiredState.seekState.setState({state:z.Requested,position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){const n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case Ee.SCREEN:return this.createScreenProvider(t);case Ee.CHROMECAST:return this.createChromecastProvider(t);default:return V(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:r}=this.params,a=this.providerOutput,n={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case y.DASH:{const o=this.applyFailoverHost(t[e]);return P(o),new Lp({...n,source:o,config:Ov})}case y.DASH_SEP:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),this.params.tuning.useDashJs?new un({...n,source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):new pv({...n,source:o})}case y.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),this.params.tuning.useDashJsCMAF?new un({...n,source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):new mv({...n,source:o})}case y.HLS:case y.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),yi||!this.params.tuning.useHlsJs?new bv({...n,source:o}):new vv({...n,source:o})}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new Sv({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case y.MPEG:{const o=this.applyFailoverHost(t[e]);return P(o),new yv({...n,source:o})}case y.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new Pp({...n,source:o,config:{...Bv,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case y.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new Av({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return V(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return P(o),new Nf({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?Ee.CHROMECAST:Ee.SCREEN}chooseFormat(e){switch(e){case Ee.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case Ee.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return V(e)}}skipFormat(e){switch(e){case Ee.SCREEN:return this.screenFormatsIterator.next();case Ee.CHROMECAST:return this.chromecastFormatsIterator.next();default:return V(e)}}handleNoFormatsError(e){switch(e){case Ee.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case Ee.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return V(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=r=>{const a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return Qt(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){const e=new re;let t=!1,i=0;return e.add(U(this.providerOutput.error$,Cv({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(w(r=>({id:`ProviderHangup:${r}`,category:C.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const r=this.params.desiredState.playbackState.transitionEnded$.pipe(se(({to:a})=>a===p.PLAYING),me()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{const a=this.current$.getValue().destination;if(a===Ee.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(Ee.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=r.category===C.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),u=i<this.params.tuning.providerErrorLimit;o&&(n&&t||!u)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):u?(i++,this.reinitProvider()):this.switchToNextProvider(a!=null?a:Ee.SCREEN)}})),e}}const Or=(s,e,t)=>t*e+(1-t)*s,Qo=(s,e)=>s.reduce((t,i)=>t+i,0)/e,Nv=(s,e,t,i)=>{let r=0,a=t;const n=Qo(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};class Ko{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 S(e.initial),this.debounced$=new S(e.initial);const i=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ke(`raw_${i}`),this.smoothedSeries$=new Ke(`smoothed_${i}`),this.reportedSeries$=new Ke(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(te(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 Fv extends Ko{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Or(this.slow,e,this.params.emaAlphaSlow),this.fast=Or(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Uv extends Ko{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Qo(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Or(this.emaSmoothed,e,this.params.emaAlpha);const i=Nv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class Dn{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Fv({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Uv({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}}const Vv=5e3,Rn="one_video_throughput",In="one_video_rtt",at=window.navigator.connection,xn=()=>{const s=at==null?void 0:at.downlink;if(_(s)&&s!==10)return s*1e3},Ln=()=>{const s=at==null?void 0:at.rtt;if(_(s)&&s!==3e3)return s},Cn=(s,e,t)=>{const i=t*8,r=i/s;return i/(r+e)};class mi{constructor(e){var t,i;this.subscription=new re,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=mi.load(Rn)||(e.useBrowserEstimation?xn():void 0)||Vv,a=(i=(t=mi.load(In))!==null&&t!==void 0?t:e.useBrowserEstimation?Ln():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new S(r),this.rtt$=new S(a),this.rttAdjustedThroughput$=new S(Cn(r,a,e.rttPenaltyRequestSize)),this.throughput=Dn.getSmoothedValue(r,-1,e),this.rtt=Dn.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const u=xn();u&&this.throughput.next(u);const d=Ln();_(d)&&this.rtt.next(d)};at&&"onchange"in at&&this.subscription.add(B(at,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Cs.set(Rn,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Cs.set(In,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Ie({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(w(({throughput:n,rtt:o})=>Cn(n,o,e.rttPenaltyRequestSize)),se(n=>{const o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=pe();const r=new re;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(B(e,"progress").pipe(me()).subscribe(a=>{t=a.loaded,i=pe()}));break;case 1:case 0:r.add(B(e,"loadstart").subscribe(()=>{t=0,i=pe()}));break}r.add(B(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=pe(),u=n-t,d=o-i;this.addRawSpeed(u,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let i=0;const r=pe();let a=0,n=pe();const o=d=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},u=async({done:d,value:l})=>{d?(this.addRawSpeed(i,pe()-r,1),this.concurrentDownloads.delete(e)):l&&(i+=l.byteLength,a+=l.byteLength,a>=this.tuningConfig.streamMinSampleSize&&pe()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,pe()-n,this.concurrentDownloads.size),a=0,n=pe()),await(t==null?void 0:t.read().then(u,o)))};this.concurrentDownloads.add(e),t==null||t.read().then(u,o)}addRawSpeed(e,t,i=1){if(mi.sanityCheck(e,t)){const r=e*8/t;this.throughput.next(r*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||e<10*1024||t<=20)}static load(e){var t;const i=Cs.get(e);if(_(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const On={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Ce.Q_480P},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,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:St.VP9,androidPreferredFormat:rt.MPEG,preferCMAF:!1,preferWebRTC:!1,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,useDashJsCMAF:!0,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},Hv=s=>{var e;return{...gd(s,On),configName:[...(e=s.configName)!==null&&e!==void 0?e:[],...On.configName]}};var Bn=({seekState:s,position$:e})=>U(s.stateChangeEnded$.pipe(w(({to:t})=>{var i;return t.state===z.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),se(_)),e.pipe(se(()=>s.getState().state===z.None))),Gv=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return P(e,`Wrong container or containerId {${s.container}}`),e};class Qv{constructor(e={configName:[]}){if(this.subscription=new re,this.logger=new Sd,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.desiredState={playbackState:new ue(p.STOPPED),seekState:new ue({state:z.None}),volume:new ue({volume:1,muted:!1}),videoTrack:new ue(void 0),autoVideoTrackSwitching:new ue(!0),autoVideoTrackLimits:new ue({}),isLooped:new ue(!1),playbackRate:new ue(1),externalTextTracks:new ue([]),internalTextTracks:new ue([]),currentTextTrack:new ue(void 0),textTrackCuesSettings:new ue({}),cameraOrientation:new ue({x:0,y:0})},this.info={playbackState$:new S(p.STOPPED),position$:new S(0),duration$:new S(1/0),muted$:new S(!1),volume$:new S(1),availableQualities$:new S([]),availableQualitiesFps$:new S({}),availableAudioTracks$:new S([]),isAudioAvailable$:new S(!0),currentQuality$:new S(void 0),isAutoQualityEnabled$:new S(!0),autoQualityLimitingAvailable$:new S(!1),autoQualityLimits$:new S({}),currentPlaybackRate$:new S(1),currentBuffer$:new S({start:0,end:0}),isBuffering$:new S(!0),isStalled$:new S(!1),isEnded$:new S(!1),isLooped$:new S(!1),isLive$:new S(void 0),canChangePlaybackSpeed$:new S(void 0),atLiveEdge$:new S(void 0),atLiveDurationEdge$:new S(void 0),liveTime$:new S(void 0),liveBufferTime$:new S(void 0),currentFormat$:new S(void 0),availableTextTracks$:new S([]),currentTextTrack$:new S(void 0),throughputEstimation$:new S(void 0),rttEstimation$:new S(void 0),videoBitrate$:new S(void 0),hostname$:new S(void 0),httpConnectionType$:new S(void 0),httpConnectionReused$:new S(void 0),surface$:new S(gt.NONE),chromecastState$:new S(ye.NOT_AVAILABLE),chromecastDeviceName$:new S(void 0),intrinsicVideoSize$:new S(void 0),availableSources$:new S(void 0),is3DVideo$:new S(!1)},this.events={inited$:new L,ready$:new L,started$:new L,playing$:new L,paused$:new L,stopped$:new L,willStart$:new L,willResume$:new L,willPause$:new L,willStop$:new L,willDestruct$:new L,watchCoverageRecord$:new L,watchCoverageLive$:new L,managedError$:new L,fatalError$:new L,ended$:new L,looped$:new L,seeked$:new L,willSeek$:new L,firstBytes$:new L,firstFrame$:new L,canplay$:new L,log$:new L},this.experimental={element$:new S(void 0),tuningConfigName$:new S([]),enableDebugTelemetry$:new S(!1),dumpTelemetry:dp},this.initLogs(),this.tuning=Hv(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ed({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new mi(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{const a=Reflect.get(t,i,r);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const u=n.map(c=>JSON.stringify(c,(h,f)=>{const m=typeof f;return["number","string","boolean"].includes(m)?f:f===null?null:`<${m}>`})),d=`Player.${String(i)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:C.WTF,message:l,thrown:o}),o}}}})}initVideo(e){var t,i,r;return this.config=e,this.domContainer=Gv(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Mv({sources:e.sources,meta:(i=e.meta)!==null&&i!==void 0?i:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===p.STOPPED&&e.startTransitionTo(p.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==p.PLAYING&&t.startTransitionTo(p.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?B(document,"visibilitychange").pipe(me()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==p.PAUSED&&e.startTransitionTo(p.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==p.STOPPED&&e.startTransitionTo(p.STOPPED),this}seekTime(e,t=!0){const i=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=i&&!r&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:z.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===ye.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===ye.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){P(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const i=t.find(r=>r.quality===e);return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var t;P(this.providerContainer);const i=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return i&&(this.desiredState.playbackRate.setState(e),i.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t,i,r;return e!==void 0&&this.desiredState.currentTextTrack.getState()===void 0&&this.desiredState.currentTextTrack.getPrevState()===void 0&&((t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$.getValue().length)===0?(i=this.providerContainer)===null||i===void 0||i.providerOutput.availableTextTracks$.pipe(se(a=>a.length>0),me()).subscribe(a=>{a.find(n=>n.id===e)&&this.desiredState.currentTextTrack.startTransitionTo(e)}):(e===void 0||!((r=this.providerContainer)===null||r===void 0)&&r.providerOutput.availableTextTracks$.getValue().find(a=>a.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()}startCameraManualRotation(e,t){const i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const i=this.getScene3D();if(i){const r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){P(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(te(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===z.None?void 0:t.position;return _(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const i=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=i==null?void 0:i.provider)===null||t===void 0)&&t.scene3D)return i.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(U(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(w(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(w(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(w(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(w(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(w(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(se(({from:e})=>e===p.STOPPED),me()).subscribe(()=>{this.initedAt=pe(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case p.READY:this.events.ready$.next();break;case p.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case p.PAUSED:this.events.paused$.next();break;case p.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case p.PAUSED:this.events.willPause$.next();break;case p.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case p.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===z.Requested?this.desiredState.seekState.setState({...n,state:z.Applying}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:C.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===z.Applying&&(this.desiredState.seekState.setState({state:z.None}),this.events.seeked$.next())})).add(e.current$.pipe(w(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(w(n=>n.destination),fe()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(w(n=>n.map(({quality:o})=>o).sort((o,u)=>vi(o)?1:vi(u)?-1:pi(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{const o={};for(const u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.hostname$.pipe(fe()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(fe()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(fe()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(w(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(Ie({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Bn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(w(({isLive:n,position:o,isLowLatency:u})=>{const d=u?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return n&&Math.abs(o)<d/1e3}),fe(),ts(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(Ie({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(w(({isLive:n,position:o,duration:u})=>n&&Math.abs(u)-Math.abs(o)<this.tuning.live.activeLiveDelay),fe(),ts(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(w(n=>n.muted),fe()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(w(n=>n.volume),fe()).subscribe(this.info.volume$)).add(Bn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(U(e.providerOutput.endedEvent$.pipe(Wt(!0)),e.providerOutput.seekedEvent$.pipe(Wt(!1))).pipe(fe()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(w(n=>({id:n?`No${n}`:"NoProviders",category:C.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(me(),w(n=>n!=null?n:pe()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(me(),w(()=>pe()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(me(),w(()=>pe()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new S(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new S(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(se(({to:n})=>n===p.PLAYING),me()).subscribe(()=>i.next(!1)));let r=0;const a=U(e.providerOutput.isBuffering$,t,i).pipe(w(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),fe());this.subscription.add(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(U(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var o,u;const d=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(o=n==null?void 0:n.size)===null||o===void 0?void 0:o.width,height:(u=n==null?void 0:n.size)===null||u===void 0?void 0:u.height},{width:d==null?void 0:d.videoWidth,height:d==null?void 0:d.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(U(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),d=this.chromecastInitializer.castState$.getValue();let l;d===ye.CONNECTED?l=gt.SECOND_SCREEN:u?n?l=gt.PIP:o?l=gt.FULLSCREEN:l=gt.INLINE:l=gt.NONE,this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(w(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new re;this.subscription.add(t),this.subscription.add(e.current$.pipe(fe((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(se(i=>i.length>0),me()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:i})=>i===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=ti(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,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(U(this.desiredState.videoTrack.stateChangeStarted$.pipe(w(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(w(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(w(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(w(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(w(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(w(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(w(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(w(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(w(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;P(this.providerContainer),P(t),op(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>np(i)),this.providerContainer.current$.subscribe(({type:i})=>Ui("provider",i)),t.duration$.subscribe(i=>Ui("duration",i)),t.availableVideoTracks$.pipe(se(i=>!!i.length),me()).subscribe(i=>Ui("tracks",i)),this.events.fatalError$.subscribe(new Ke("fatalError")),this.events.managedError$.subscribe(new Ke("managedError")),t.position$.subscribe(new Ke("position")),t.currentVideoTrack$.pipe(w(i=>i==null?void 0:i.quality)).subscribe(new Ke("quality")),this.info.currentBuffer$.subscribe(new Ke("buffer")),t.isBuffering$.subscribe(new Ke("isBuffering"))].forEach(i=>this.subscription.add(i)),Ui("codecs",Rv())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:C.DOM,message:String(r)})})};this.subscription.add(U(B(document,"visibilitychange"),B(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===p.PLAYING,n=!!e&&!(e!=null&&e.released);r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}}const Kv=`@vkontakte/videoplayer-core@${yd}`;export{ye as ChromecastState,gi as HttpConnectionType,Zv as Observable,p as PlaybackState,Qv as Player,Kv as SDK_VERSION,eg as Subject,tg as Subscription,gt as Surface,yd as VERSION,ig as ValueSubject,y as VideoFormat,sg as VideoQuality};
38
+ `),o=[],u=[];for(let d=0;d<n.length;d++){const l=n[d],c=l.match(/^#EXT-X-STREAM-INF:(.+)/),h=l.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!c&&!h)){if(c){const f=Qt(c[1].split(",").map(b=>b.split("="))),m=(t=f.QUALITY)!==null&&t!==void 0?t:`stream-${f.BANDWIDTH}`,g=gv(f);let T;f.BANDWIDTH&&(T=parseInt(f.BANDWIDTH,10)/1e3||void 0),!T&&f["AVERAGE-BANDWIDTH"]&&(T=parseInt(f["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const A=f["FRAME-RATE"]?parseFloat(f["FRAME-RATE"]):void 0;let E;if(f.RESOLUTION){const[b,$]=f.RESOLUTION.split("x").map(D=>parseInt(D,10));b&&$&&(E={width:b,height:$})}const v=new URL(n[++d],e).toString();g&&o.push({id:m,quality:g,url:v,bandwidth:T,size:E,fps:A})}if(h){const f=Qt(h[1].split(",").map(A=>A.split("=")).map(([A,E])=>[A,E.replace(/^"|"$/g,"")])),m=(i=f.URI)===null||i===void 0?void 0:i.replace(/playlist$/,"subtitles.vtt"),g=f.LANGUAGE,T=f.NAME;m&&g&&u.push({type:"internal",id:g,label:T,language:g,url:m,isAuto:!1})}}}return{qualityManifests:o,textTracks:u}};var ne;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(ne||(ne={}));class Sv{constructor(e){var t;this.subscription=new re,this.videoState=new ue(ne.STOPPED),this.textTracksManager=new Ze,this.manifests$=new S([]),this.liveOffset=new ys,this.manifestStartTime$=new S(void 0),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(n===p.STOPPED){a!==ne.STOPPED&&(this.videoState.startTransitionTo(ne.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ne.STOPPED),R(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(a===ne.STOPPED){this.videoState.startTransitionTo(ne.READY),this.prepare();return}if(u||d){const h=this.videoState.getState();this.videoState.setState(ne.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),c.state===z.None&&this.params.desiredState.seekState.setState({state:z.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==p.PAUSED&&c.state===z.Requested){this.videoState.startTransitionTo(ne.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(a){case ne.READY:n===p.READY?R(this.params.desiredState.playbackState,p.READY):n===p.PAUSED?(this.videoState.setState(ne.PAUSED),this.liveOffset.pause(),R(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING&&(this.videoState.startTransitionTo(ne.PLAYING),this.playIfAllowed());return;case ne.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(ne.PAUSED),this.liveOffset.pause(),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&R(this.params.desiredState.playbackState,p.PLAYING);return;case ne.PAUSED:if(n===p.PLAYING)if(this.videoState.startTransitionTo(ne.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);else{let h=this.liveOffset.getTotalOffset();h>=this.maxSeekBackTime$.getValue()&&(h=0,this.liveOffset.resetTo(h)),this.liveOffset.resume(),this.params.output.position$.next(-h/1e3),this.prepare()}else(o==null?void 0:o.to)===p.PAUSED&&(R(this.params.desiredState.playbackState,p.PAUSED),this.liveOffset.pause());return;case ne.CHANGING_MANIFEST:break;default:return V(a)}},this.params=e,this.video=ct(e.container),this.params.output.element$.next(this.video);const i={id:"master",quality:Ce.INVARIANT,url:this.params.source.url};qo(He(this.params.source.url),this.params.source.url).then(({qualityManifests:r})=>{this.manifests$.next([i,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:C.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(we(this.params.source.url)),this.maxSeekBackTime$=new S((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:r}=this.params.desiredState,a=i.getState(),n=r.getTransition(),o=(t=(e=n==null?void 0:n.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",u=this.manifests$.getValue();if(!u.length)return;const d=a?"master":o;return a&&!n&&r.startTransitionTo("master"),u.find(l=>l.id===d)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsLiveProvider",category:C.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=ft(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(lt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Tt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ne.PLAYING),R(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ne.PAUSED),R(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ne.READY&&this.videoState.setState(ne.READY),this.videoState.getState()===ne.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(fe(),w(o=>-o/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&_(d.to)){const c=d.to;this.params.desiredState.videoTrack.setState(c);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(we(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===ne.CHANGING_MANIFEST&&this.videoState.setState(u.to),o&&o.state===z.Requested&&this.seek(o.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var o,u,d;const l=(d=(u=(o=this.video)===null||o===void 0?void 0:o.getStartDate)===null||u===void 0?void 0:u.call(o))===null||d===void 0?void 0:d.getTime();this.manifestStartTime$.next(l||void 0)},i)),this.subscription.add(Ie({startTime:this.manifestStartTime$.pipe(se(_)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:u})=>this.params.output.liveTime$.next(o+u*1e3),i)),this.subscription.add(this.manifests$.pipe(w(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i));const n=U(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.manifests$,ke(["init"])).pipe(Me(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ht(this.video)}prepare(){const e=this.selectManifest();if(te(e))return;const t=this.params.format===y.HLS_LIVE_CMAF?be.DASH_CMAF_OFFSET_P:be.OFFSET_P,i=He(e.url,this.liveOffset.getTotalOffset(),t);this.video.setAttribute("src",i),this.video.load(),kn(i).then(r=>{var a;if(!te(r))this.maxSeekBackTime$.next(r);else{const n=(a=this.params.source.maxSeekBackTime)!==null&&a!==void 0?a:this.maxSeekBackTime$.getValue();if(te(n)||!isFinite(n))try{bi(i).then(o=>o.text()).then(o=>{var u;const d=(u=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(o))===null||u===void 0?void 0:u[1];if(d){const l=new URL(d,i).toString();kn(l).then(c=>{te(c)||this.maxSeekBackTime$.next(c)})}})}catch(o){}}})}playIfAllowed(){Et(this.video).then(e=>{e||(this.videoState.setState(ne.PAUSED),this.liveOffset.pause(),R(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}var de;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(de||(de={}));class bv{constructor(e){this.subscription=new re,this.videoState=new ue(de.STOPPED),this.textTracksManager=new Ze,this.manifests$=new S([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const r=this.videoState.getState(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a===p.STOPPED){r!==de.STOPPED&&(this.videoState.startTransitionTo(de.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(de.STOPPED),R(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const l=this.params.desiredState.seekState.getState();if(r===de.STOPPED){this.videoState.startTransitionTo(de.READY),this.prepare();return}if(o||u){const c=this.videoState.getState();this.videoState.setState(de.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),l.state===z.None&&this.params.desiredState.seekState.setState({state:z.Requested,position:h*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==p.PAUSED&&l.state===z.Requested&&this.seek(l.position),r){case de.READY:a===p.READY?R(this.params.desiredState.playbackState,p.READY):a===p.PAUSED?(this.videoState.setState(de.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED)):a===p.PLAYING&&(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed());return;case de.PLAYING:a===p.PAUSED?(this.videoState.startTransitionTo(de.PAUSED),this.video.pause()):(n==null?void 0:n.to)===p.PLAYING&&R(this.params.desiredState.playbackState,p.PLAYING);return;case de.PAUSED:a===p.PLAYING?(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===p.PAUSED&&R(this.params.desiredState.playbackState,p.PAUSED);return;case de.CHANGING_MANIFEST:break;default:return V(r)}},this.params=e,this.video=ct(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:Ce.INVARIANT,url:this.params.source.url};this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(we(this.params.source.url)),qo(this.params.source.url).then(({qualityManifests:i,textTracks:r})=>{this.manifests$.next([t,...i]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:C.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:r}=this.params.desiredState,a=i.getState(),n=r.getTransition(),o=(t=(e=n==null?void 0:n.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",u=this.manifests$.getValue();if(!u.length)return;const d=a?"master":o;return a&&!n&&r.startTransitionTo("master"),u.find(l=>l.id===d)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"HlsProvider",category:C.WTF,message:"HlsProvider internal logic error",thrown:o})},r=ft(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u));if(a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(Ct(this.video,t.isLooped,i)),this.subscription.add(lt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Tt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(de.PLAYING),R(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED),R(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===de.READY&&this.videoState.setState(de.READY),this.videoState.getState()===de.PLAYING&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&_(d.to)){const c=d.to;this.params.desiredState.videoTrack.setState(c);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(we(h.url)))}l&&this.params.desiredState.autoVideoTrackSwitching.setState(l.to),u&&u.from===de.CHANGING_MANIFEST&&this.videoState.setState(u.to),o.state===z.Requested&&this.seek(o.position)},i))),this.subscription.add(this.manifests$.pipe(w(o=>o.map(({id:u,quality:d,size:l,bandwidth:c,fps:h})=>({id:u,quality:d,size:l,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,i)),!this.params.tuning.useNativeHLSTextTracks){const{textTracks:o}=this.video;this.subscription.add(U(B(o,"addtrack"),B(o,"removetrack"),B(o,"change"),ke(["init"])).subscribe(()=>{for(let u=0;u<o.length;u++)o[u].mode="hidden"},i))}const n=U(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,ke(["init"])).pipe(Me(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ht(this.video)}prepare(){const e=this.selectManifest();te(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){Et(this.video).then(e=>{e||(this.videoState.setState(de.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var ce;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(ce||(ce={}));class yv{constructor(e){this.subscription=new re,this.videoState=new ue(ce.STOPPED),this.trackUrls={},this.textTracksManager=new Ze,this.syncPlayback=()=>{var t,i,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition();if(n===p.STOPPED){a!==ce.STOPPED&&(this.videoState.startTransitionTo(ce.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(ce.STOPPED),R(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.autoVideoTrackLimits.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.seekState.getState();if(d&&a!==ce.READY&&!l){this.handleQualityLimitTransition(d.to.max);return}if(a===ce.STOPPED){this.videoState.startTransitionTo(ce.READY),this.prepare();return}if(l){const{currentTime:h}=this.video;this.prepare(),c.state===z.None&&this.params.desiredState.seekState.setState({state:z.Requested,position:h*1e3,forcePrecise:!0}),l.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((r=(i=this.trackUrls[l.to])===null||i===void 0?void 0:i.track)===null||r===void 0?void 0:r.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((o==null?void 0:o.to)!==p.PAUSED&&c.state===z.Requested&&this.seek(c.position),a){case ce.READY:n===p.READY?R(this.params.desiredState.playbackState,p.READY):n===p.PAUSED?(this.videoState.setState(ce.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING&&(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed());return;case ce.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(ce.PAUSED),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&R(this.params.desiredState.playbackState,p.PLAYING);return;case ce.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(ce.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&R(this.params.desiredState.playbackState,p.PAUSED);return;default:return V(a)}},this.params=e,this.video=ct(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{const a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"MpegProvider",category:C.WTF,message:"MpegProvider internal logic error",thrown:o})},r=ft(this.video),a=(o,u)=>this.subscription.add(o.subscribe(u,i));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(Ct(this.video,t.isLooped,i)),this.subscription.add(lt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Tt(this.video,t.playbackRate,r.playbackRateState$,i)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ce.PLAYING),R(t.playbackState,p.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ce.PAUSED),R(t.playbackState,p.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ce.READY&&this.videoState.setState(ce.READY);const u=this.params.desiredState.videoTrack.getTransition();u&&_(u.to)&&(this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to].track)),this.videoState.getState()===ce.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const n=U(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Me(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ht(this.video)}prepare(){const e=this.params.desiredState.videoTrack.getState();P(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];P(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Kt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(we(t))}playIfAllowed(){Et(this.video).then(e=>{e||(this.videoState.setState(ce.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,i,r;let a;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const n=(i=Object.values(this.trackUrls).find(d=>Nn(d.track.quality,e)))===null||i===void 0?void 0:i.track,o=this.params.desiredState.videoTrack.getState(),u=(r=this.trackUrls[o!=null?o:"0"])===null||r===void 0?void 0:r.track;n&&u&&Tr(u.quality,n.quality)&&(a=n)}else if(!e){const n=Object.values(this.trackUrls).map(o=>o.track);a=ti(n,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}a&&(this.params.output.currentVideoTrack$.next(a),this.params.desiredState.videoTrack.startTransitionTo(a.id)),this.params.output.autoVideoTrackLimits$.next({max:e})}}const wn=["stun:videostun.mycdn.me:80"],Tv=1e3,Ev=3,dr=()=>null;class $v{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=dr,this.externalStopCallback=dr,this.externalErrorCallback=dr,this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:wn}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:C.WTF,message:e.message})}async onPeerConnectionStream(e){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),Tv)}normalizeOptions(e={}){const t={stunServerList:wn,maxRetryNumber:Ev,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var oe;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(oe||(oe={}));class Av{constructor(e){this.videoState=new ue(oe.STOPPED),this.maxSeekBackTime$=new S(0),this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(i===p.STOPPED){t!==oe.STOPPED&&(this.videoState.startTransitionTo(oe.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(oe.STOPPED),R(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===oe.STOPPED){this.videoState.startTransitionTo(oe.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case oe.READY:i===p.PAUSED?(this.videoState.setState(oe.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED)):i===p.PLAYING&&(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed());return;case oe.PLAYING:i===p.PAUSED?(this.videoState.startTransitionTo(oe.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&R(this.params.desiredState.playbackState,p.PLAYING);return;case oe.PAUSED:i===p.PLAYING?(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&R(this.params.desiredState.playbackState,p.PAUSED);return;default:return V(t)}},this.subscription=new re,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=ct(e.container),this.liveStreamClient=new $v(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),ht(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=n=>{e.error$.next({id:"WebRTCLiveProvider",category:C.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};U(this.videoState.stateChangeStarted$.pipe(w(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(w(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const r=ft(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,i));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),this.subscription.add(r.durationChange$.subscribe(n=>{e.duration$.next(n===1/0?0:n)})).add(r.canplay$.subscribe(()=>{var n;((n=this.videoState.getTransition())===null||n===void 0?void 0:n.to)===oe.READY&&this.videoState.setState(oe.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(oe.PAUSED)},i)).add(r.playing$.subscribe(()=>{this.videoState.setState(oe.PLAYING)},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(lt(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case oe.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(p.STOPPED);break;case oe.READY:break;case oe.PAUSED:t.playbackState.setState(p.PAUSED);break;case oe.PLAYING:t.playbackState.setState(p.PLAYING);break;default:return V(n.to)}},i)).add(U(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,ke(["init"])).pipe(Me(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(we(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:Ce.INVARIANT}),this.video.srcObject=e,R(this.params.desiredState.playbackState,p.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(oe.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:C.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Et(this.video).then(e=>{e||(this.videoState.setState(oe.PAUSED),R(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:C.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class _n{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!!this.current.done}}var ur,lr,cr,hr,fr,pr,Yi,mr,qi,vr,ji,gr,zi,Sr,Wi,br,Qi,yr;const jo=Br().device===vd.Android,yt=document.createElement("video"),kv='video/mp4; codecs="avc1.42000a,mp4a.40.2"',wv='video/mp4; codecs="hev1.1.6.L93.B0"',zo='video/webm; codecs="vp09.00.10.08"',Wo='video/webm; codecs="av01.0.00M.08"',_v='audio/mp4; codecs="mp4a.40.2"',Pv='audio/webm; codecs="opus"',Ue={mse:!!(window.MediaSource&&window.MediaStreamTrack&&(!((lr=(ur=window.SourceBuffer)===null||ur===void 0?void 0:ur.prototype)===null||lr===void 0)&&lr.appendBuffer)),hls:!!(!((cr=yt.canPlayType)===null||cr===void 0)&&cr.call(yt,"application/x-mpegurl")||!((hr=yt.canPlayType)===null||hr===void 0)&&hr.call(yt,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},De={mp4:!!(!((fr=yt.canPlayType)===null||fr===void 0)&&fr.call(yt,"video/mp4")),webm:!!(!((pr=yt.canPlayType)===null||pr===void 0)&&pr.call(yt,"video/webm")),cmaf:!0},Xe={h264:!!(!((mr=(Yi=window.MediaSource)===null||Yi===void 0?void 0:Yi.isTypeSupported)===null||mr===void 0)&&mr.call(Yi,kv)),h265:!!(!((vr=(qi=window.MediaSource)===null||qi===void 0?void 0:qi.isTypeSupported)===null||vr===void 0)&&vr.call(qi,wv)),vp9:!!(!((gr=(ji=window.MediaSource)===null||ji===void 0?void 0:ji.isTypeSupported)===null||gr===void 0)&&gr.call(ji,zo)),av1:!!(!((Sr=(zi=window.MediaSource)===null||zi===void 0?void 0:zi.isTypeSupported)===null||Sr===void 0)&&Sr.call(zi,Wo)),aac:!!(!((br=(Wi=window.MediaSource)===null||Wi===void 0?void 0:Wi.isTypeSupported)===null||br===void 0)&&br.call(Wi,_v)),opus:!!(!((yr=(Qi=window.MediaSource)===null||Qi===void 0?void 0:Qi.isTypeSupported)===null||yr===void 0)&&yr.call(Qi,Pv))},Yt=(Xe.h264||Xe.h265)&&Xe.aac;var St;(function(s){s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient"})(St||(St={}));var rt;(function(s){s.DASH="dash",s.HLS="hls",s.MPEG="mpeg"})(rt||(rt={}));let _t;const Dv=async()=>{if(!window.navigator.mediaCapabilities)return;const s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:Wo}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:zo}})]);_t={[y.DASH_WEBM_AV1]:e,[y.DASH_WEBM]:t}};try{Dv()}catch(s){console.error(s)}const yi=Ue.hls&&De.mp4,Rv=()=>Object.keys(Xe).filter(s=>Xe[s]),Iv=(s,e=!1)=>s.filter(t=>{switch(t){case y.DASH:return Ue.mse&&De.mp4&&Yt;case y.DASH_SEP:return Ue.mse&&De.mp4&&Yt;case y.DASH_WEBM:return Ue.mse&&De.webm&&Xe.vp9&&Xe.opus;case y.DASH_WEBM_AV1:return Ue.mse&&De.webm&&Xe.av1&&Xe.opus;case y.DASH_LIVE:return Ue.mse&&De.mp4&&Yt;case y.DASH_LIVE_CMAF:return Ue.mse&&De.mp4&&Yt&&De.cmaf;case y.DASH_ONDEMAND:return Ue.mse&&De.mp4&&Yt;case y.HLS:case y.HLS_ONDEMAND:return yi||e&&Ue.mse&&De.mp4&&Yt;case y.HLS_LIVE:case y.HLS_LIVE_CMAF:return yi;case y.MPEG:return De.mp4;case y.DASH_LIVE_WEBM:return!1;case y.WEB_RTC_LIVE:return Ue.webrtc&&Ue.ws&&Xe.h264&&(De.mp4||De.webm);default:return V(t)}}),hi=s=>{const e=y.DASH_WEBM,t=y.DASH_WEBM_AV1;switch(s){case St.VP9:return[e,t];case St.AV1:return[t,e];case St.NONE:return[];case St.SMOOTH:return _t?_t[t].smooth?[t,e]:_t[e].smooth?[e,t]:[t,e]:[e,t];case St.POWER_EFFICIENT:return _t?_t[t].powerEfficient?[t,e]:_t[e].powerEfficient?[e,t]:[t,e]:[e,t];default:V(s)}return[e,t]},xv=({webmCodec:s,androidPreferredFormat:e})=>{if(jo)switch(e){case rt.MPEG:return[y.MPEG,...hi(s),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND];case rt.HLS:return[y.HLS,y.HLS_ONDEMAND,...hi(s),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.MPEG];case rt.DASH:return[...hi(s),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG]}return yi?[...hi(s),y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG,y.DASH]:[...hi(s),y.DASH_SEP,y.DASH,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG]},Lv=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{const i=e?[y.DASH_LIVE_CMAF,y.DASH_LIVE]:[y.DASH_LIVE,y.DASH_LIVE_CMAF],r=e?[y.HLS_LIVE_CMAF,y.HLS_LIVE]:[y.HLS_LIVE,y.HLS_LIVE_CMAF],a=[...i,...r],n=[...r,...i];let o;if(jo)switch(s){case rt.DASH:{o=a;break}case rt.HLS:case rt.MPEG:{o=n;break}}else yi?o=n:o=a;return t?[y.WEB_RTC_LIVE,...o]:[...o,y.WEB_RTC_LIVE]},Pn=s=>s?[y.HLS_LIVE,y.HLS_LIVE_CMAF,y.DASH_LIVE_CMAF]:[y.DASH_WEBM,y.DASH_WEBM_AV1,y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG];var Cv=s=>new cs(e=>{const t=new re,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(w(({from:d,to:l})=>`${d}-${l}`)),r=s.desiredPlaybackState$.stateChangeEnded$,a=s.providerChanged$.pipe(w(({type:d})=>d!==void 0)),n=new L;let o=0,u="unknown";return t.add(i.subscribe(d=>{o&&window.clearTimeout(o),u=d,o=window.setTimeout(()=>n.next(d),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),u="unknown",o=0})),t.add(a.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>n.next(u),s.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const Ov={cacheDuration:12e4},Bv={chunkDuration:5e3,maxParallelRequests:5};class Mv{constructor(e){this.current$=new S({type:void 0}),this.providerError$=new L,this.noAvailableProvidersError$=new L,this.providerOutput={position$:new S(0),duration$:new S(1/0),volume$:new S({muted:!1,volume:1}),currentVideoTrack$:new S(void 0),availableVideoTracks$:new S([]),availableAudioTracks$:new S([]),isAudioAvailable$:new S(!0),autoVideoTrackLimitingAvailable$:new S(!1),autoVideoTrackLimits$:new S(void 0),currentBuffer$:new S(void 0),isBuffering$:new S(!0),error$:new L,warning$:new L,willSeekEvent$:new L,seekedEvent$:new L,loopedEvent$:new L,endedEvent$:new L,firstBytesEvent$:new L,firstFrameEvent$:new L,canplay$:new L,isLive$:new S(void 0),isLowLatency$:new S(!1),canChangePlaybackSpeed$:new S(!0),liveTime$:new S(void 0),liveBufferTime$:new S(void 0),availableTextTracks$:new S([]),currentTextTrack$:new S(void 0),hostname$:new S(void 0),httpConnectionType$:new S(void 0),httpConnectionReused$:new S(void 0),inPiP$:new S(!1),inFullscreen$:new S(!1),element$:new S(void 0),availableSources$:new S(void 0),is3DVideo$:new S(!1)},this.subscription=new re,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Iv([...Lv(this.params.tuning),...xv(this.params.tuning)],this.params.tuning.useHlsJs).filter(o=>_(e.sources[o])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning;let a=[];i?a=[i]:r.length?a=[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:a=t,this.log({message:`Selected formats: ${a.join(" > ")}`}),this.screenFormatsIterator=new _n(a);const n=[...Pn(!0),...Pn(!1)];this.chromecastFormatsIterator=new _n(n.filter(o=>_(e.sources[o]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(te(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:C.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!==z.None;if(this.params.desiredState.seekState.setState({state:z.Requested,position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){const n=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:n.x,y:n.y})}e.destroy();const a=this.providerOutput.isBuffering$;a.getValue()||a.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case Ee.SCREEN:return this.createScreenProvider(t);case Ee.CHROMECAST:return this.createChromecastProvider(t);default:return V(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:r}=this.params,a=this.providerOutput,n={container:i,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case y.DASH:{const o=this.applyFailoverHost(t[e]);return P(o),new Lp({...n,source:o,config:Ov})}case y.DASH_SEP:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),this.params.tuning.useDashJs?new un({...n,source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):new pv({...n,source:o})}case y.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),this.params.tuning.useDashJsCMAF?new un({...n,source:o,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):new mv({...n,source:o})}case y.HLS:case y.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return P(o),yi||!this.params.tuning.useHlsJs?new bv({...n,source:o}):new vv({...n,source:o})}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return P(o),new Sv({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case y.MPEG:{const o=this.applyFailoverHost(t[e]);return P(o),new yv({...n,source:o})}case y.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new Pp({...n,source:o,config:{...Bv,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case y.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return P(o),new Av({container:i,source:o,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return V(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return P(o),new Nf({connection:o,meta:a,container:i,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?Ee.CHROMECAST:Ee.SCREEN}chooseFormat(e){switch(e){case Ee.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case Ee.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return V(e)}}skipFormat(e){switch(e){case Ee.SCREEN:return this.screenFormatsIterator.next();case Ee.CHROMECAST:return this.chromecastFormatsIterator.next();default:return V(e)}}handleNoFormatsError(e){switch(e){case Ee.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case Ee.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return V(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=r=>{const a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return Qt(Object.entries(e).map(([r,a])=>[r,i(a)]))}initProviderErrorHandling(){const e=new re;let t=!1,i=0;return e.add(U(this.providerOutput.error$,Cv({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(w(r=>({id:`ProviderHangup:${r}`,category:C.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const r=this.params.desiredState.playbackState.transitionEnded$.pipe(se(({to:a})=>a===p.PLAYING),me()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{const a=this.current$.getValue().destination;if(a===Ee.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(Ee.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=r.category===C.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),u=i<this.params.tuning.providerErrorLimit;o&&(n&&t||!u)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):u?(i++,this.reinitProvider()):this.switchToNextProvider(a!=null?a:Ee.SCREEN)}})),e}}const Or=(s,e,t)=>t*e+(1-t)*s,Qo=(s,e)=>s.reduce((t,i)=>t+i,0)/e,Nv=(s,e,t,i)=>{let r=0,a=t;const n=Qo(s,e),o=e<i?e:i;for(let u=0;u<o;u++)s[a]>n?r++:r--,a=(s.length+a-1)%s.length;return Math.abs(r)===o};class Ko{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 S(e.initial),this.debounced$=new S(e.initial);const i=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ke(`raw_${i}`),this.smoothedSeries$=new Ke(`smoothed_${i}`),this.reportedSeries$=new Ke(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(te(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 Fv extends Ko{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Or(this.slow,e,this.params.emaAlphaSlow),this.fast=Or(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Uv extends Ko{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Qo(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Or(this.emaSmoothed,e,this.params.emaAlpha);const i=Nv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class Dn{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Fv({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Uv({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}}const Vv=5e3,Rn="one_video_throughput",In="one_video_rtt",at=window.navigator.connection,xn=()=>{const s=at==null?void 0:at.downlink;if(_(s)&&s!==10)return s*1e3},Ln=()=>{const s=at==null?void 0:at.rtt;if(_(s)&&s!==3e3)return s},Cn=(s,e,t)=>{const i=t*8,r=i/s;return i/(r+e)};class mi{constructor(e){var t,i;this.subscription=new re,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=mi.load(Rn)||(e.useBrowserEstimation?xn():void 0)||Vv,a=(i=(t=mi.load(In))!==null&&t!==void 0?t:e.useBrowserEstimation?Ln():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new S(r),this.rtt$=new S(a),this.rttAdjustedThroughput$=new S(Cn(r,a,e.rttPenaltyRequestSize)),this.throughput=Dn.getSmoothedValue(r,-1,e),this.rtt=Dn.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const u=xn();u&&this.throughput.next(u);const d=Ln();_(d)&&this.rtt.next(d)};at&&"onchange"in at&&this.subscription.add(B(at,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{Cs.set(Rn,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{Cs.set(In,n.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(Ie({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(w(({throughput:n,rtt:o})=>Cn(n,o,e.rttPenaltyRequestSize)),se(n=>{const o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=pe();const r=new re;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(B(e,"progress").pipe(me()).subscribe(a=>{t=a.loaded,i=pe()}));break;case 1:case 0:r.add(B(e,"loadstart").subscribe(()=>{t=0,i=pe()}));break}r.add(B(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=pe(),u=n-t,d=o-i;this.addRawSpeed(u,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let i=0;const r=pe();let a=0,n=pe();const o=d=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},u=async({done:d,value:l})=>{d?(this.addRawSpeed(i,pe()-r,1),this.concurrentDownloads.delete(e)):l&&(i+=l.byteLength,a+=l.byteLength,a>=this.tuningConfig.streamMinSampleSize&&pe()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,pe()-n,this.concurrentDownloads.size),a=0,n=pe()),await(t==null?void 0:t.read().then(u,o)))};this.concurrentDownloads.add(e),t==null||t.read().then(u,o)}addRawSpeed(e,t,i=1){if(mi.sanityCheck(e,t)){const r=e*8/t;this.throughput.next(r*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||e<10*1024||t<=20)}static load(e){var t;const i=Cs.get(e);if(_(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const On={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Ce.Q_480P},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,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:St.VP9,androidPreferredFormat:rt.MPEG,preferCMAF:!1,preferWebRTC:!1,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,useDashJsCMAF:!0,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},Hv=s=>{var e;return{...gd(s,On),configName:[...(e=s.configName)!==null&&e!==void 0?e:[],...On.configName]}};var Bn=({seekState:s,position$:e})=>U(s.stateChangeEnded$.pipe(w(({to:t})=>{var i;return t.state===z.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),se(_)),e.pipe(se(()=>s.getState().state===z.None))),Gv=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return P(e,`Wrong container or containerId {${s.container}}`),e};class Qv{constructor(e={configName:[]}){if(this.subscription=new re,this.logger=new Sd,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.desiredState={playbackState:new ue(p.STOPPED),seekState:new ue({state:z.None}),volume:new ue({volume:1,muted:!1}),videoTrack:new ue(void 0),autoVideoTrackSwitching:new ue(!0),autoVideoTrackLimits:new ue({}),isLooped:new ue(!1),playbackRate:new ue(1),externalTextTracks:new ue([]),internalTextTracks:new ue([]),currentTextTrack:new ue(void 0),textTrackCuesSettings:new ue({}),cameraOrientation:new ue({x:0,y:0})},this.info={playbackState$:new S(p.STOPPED),position$:new S(0),duration$:new S(1/0),muted$:new S(!1),volume$:new S(1),availableQualities$:new S([]),availableQualitiesFps$:new S({}),availableAudioTracks$:new S([]),isAudioAvailable$:new S(!0),currentQuality$:new S(void 0),isAutoQualityEnabled$:new S(!0),autoQualityLimitingAvailable$:new S(!1),autoQualityLimits$:new S({}),currentPlaybackRate$:new S(1),currentBuffer$:new S({start:0,end:0}),isBuffering$:new S(!0),isStalled$:new S(!1),isEnded$:new S(!1),isLooped$:new S(!1),isLive$:new S(void 0),canChangePlaybackSpeed$:new S(void 0),atLiveEdge$:new S(void 0),atLiveDurationEdge$:new S(void 0),liveTime$:new S(void 0),liveBufferTime$:new S(void 0),currentFormat$:new S(void 0),availableTextTracks$:new S([]),currentTextTrack$:new S(void 0),throughputEstimation$:new S(void 0),rttEstimation$:new S(void 0),videoBitrate$:new S(void 0),hostname$:new S(void 0),httpConnectionType$:new S(void 0),httpConnectionReused$:new S(void 0),surface$:new S(gt.NONE),chromecastState$:new S(ye.NOT_AVAILABLE),chromecastDeviceName$:new S(void 0),intrinsicVideoSize$:new S(void 0),availableSources$:new S(void 0),is3DVideo$:new S(!1)},this.events={inited$:new L,ready$:new L,started$:new L,playing$:new L,paused$:new L,stopped$:new L,willStart$:new L,willResume$:new L,willPause$:new L,willStop$:new L,willDestruct$:new L,watchCoverageRecord$:new L,watchCoverageLive$:new L,managedError$:new L,fatalError$:new L,ended$:new L,looped$:new L,seeked$:new L,willSeek$:new L,firstBytes$:new L,firstFrame$:new L,canplay$:new L,log$:new L},this.experimental={element$:new S(void 0),tuningConfigName$:new S([]),enableDebugTelemetry$:new S(!1),dumpTelemetry:dp},this.initLogs(),this.tuning=Hv(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Ed({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new mi(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{const a=Reflect.get(t,i,r);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const u=n.map(c=>JSON.stringify(c,(h,f)=>{const m=typeof f;return["number","string","boolean"].includes(m)?f:f===null?null:`<${m}>`})),d=`Player.${String(i)}`,l=`Exception calling ${d} (${u.join(", ")})`;throw this.events.fatalError$.next({id:d,category:C.WTF,message:l,thrown:o}),o}}}})}initVideo(e){var t,i,r;return this.config=e,this.domContainer=Gv(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Mv({sources:e.sources,meta:(i=e.meta)!==null&&i!==void 0?i:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===p.STOPPED&&e.startTransitionTo(p.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==p.PLAYING&&t.startTransitionTo(p.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?B(document,"visibilitychange").pipe(me()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==p.PAUSED&&e.startTransitionTo(p.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==p.STOPPED&&e.startTransitionTo(p.STOPPED),this}seekTime(e,t=!0){const i=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=i&&!r&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:z.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===ye.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===ye.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){P(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const i=t.find(r=>r.quality===e);return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var t;P(this.providerContainer);const i=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return i&&(this.desiredState.playbackRate.setState(e),i.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t,i,r;return e!==void 0&&this.desiredState.currentTextTrack.getState()===void 0&&this.desiredState.currentTextTrack.getPrevState()===void 0&&((t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$.getValue().length)===0?(i=this.providerContainer)===null||i===void 0||i.providerOutput.availableTextTracks$.pipe(se(a=>a.length>0),me()).subscribe(a=>{a.find(n=>n.id===e)&&this.desiredState.currentTextTrack.startTransitionTo(e)}):(e===void 0||!((r=this.providerContainer)===null||r===void 0)&&r.providerOutput.availableTextTracks$.getValue().find(a=>a.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()}startCameraManualRotation(e,t){const i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const i=this.getScene3D();if(i){const r=i.getCameraRotation(),a=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+a.x,y:r.y+a.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){P(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(te(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===z.None?void 0:t.position;return _(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const i=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=i==null?void 0:i.provider)===null||t===void 0)&&t.scene3D)return i.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(U(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(w(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(w(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(w(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(w(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(w(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(se(({from:e})=>e===p.STOPPED),me()).subscribe(()=>{this.initedAt=pe(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case p.READY:this.events.ready$.next();break;case p.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case p.PAUSED:this.events.paused$.next();break;case p.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case p.PAUSED:this.events.willPause$.next();break;case p.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case p.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const n=this.desiredState.seekState.getState();n.state===z.Requested?this.desiredState.seekState.setState({...n,state:z.Applying}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:C.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===z.Applying&&(this.desiredState.seekState.setState({state:z.None}),this.events.seeked$.next())})).add(e.current$.pipe(w(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(w(n=>n.destination),fe()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(w(n=>n.map(({quality:o})=>o).sort((o,u)=>vi(o)?1:vi(u)?-1:pi(u,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{const o={};for(const u of n)u.fps&&(o[u.quality]=u.fps);this.info.availableQualitiesFps$.next(o)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{this.info.currentQuality$.next(n==null?void 0:n.quality),this.info.videoBitrate$.next(n==null?void 0:n.bitrate)})).add(e.providerOutput.hostname$.pipe(fe()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(fe()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(fe()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(n=>{this.desiredState.autoVideoTrackLimits.setState(n!=null?n:{})})).add(e.providerOutput.currentBuffer$.pipe(w(n=>n?{start:n.from,end:n.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(Ie({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Bn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(w(({isLive:n,position:o,isLowLatency:u})=>{const d=u?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return n&&Math.abs(o)<d/1e3}),fe(),ts(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(Ie({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(w(({isLive:n,position:o,duration:u})=>n&&Math.abs(u)-Math.abs(o)<this.tuning.live.activeLiveDelay),fe(),ts(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(w(n=>n.muted),fe()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(w(n=>n.volume),fe()).subscribe(this.info.volume$)).add(Bn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(U(e.providerOutput.endedEvent$.pipe(Wt(!0)),e.providerOutput.seekedEvent$.pipe(Wt(!1))).pipe(fe()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(w(n=>({id:n?`No${n}`:"NoProviders",category:C.VIDEO_PIPELINE,message:n?`${n} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(me(),w(n=>n!=null?n:pe()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(me(),w(()=>pe()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(me(),w(()=>pe()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new S(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new S(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(se(({to:n})=>n===p.PLAYING),me()).subscribe(()=>i.next(!1)));let r=0;const a=U(e.providerOutput.isBuffering$,t,i).pipe(w(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||i.getValue();return n&&!o}),fe());this.subscription.add(a.subscribe(n=>{n?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(U(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const n=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:n==null?void 0:n.videoWidth,height:n==null?void 0:n.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(n=>{var o,u;const d=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(o=n==null?void 0:n.size)===null||o===void 0?void 0:o.width,height:(u=n==null?void 0:n.size)===null||u===void 0?void 0:u.height},{width:d==null?void 0:d.videoWidth,height:d==null?void 0:d.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(U(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),u=e.providerOutput.element$.getValue(),d=this.chromecastInitializer.castState$.getValue();let l;d===ye.CONNECTED?l=gt.SECOND_SCREEN:u?n?l=gt.PIP:o?l=gt.FULLSCREEN:l=gt.INLINE:l=gt.NONE,this.info.surface$.getValue()!==l&&this.info.surface$.next(l)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(w(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new re;this.subscription.add(t),this.subscription.add(e.current$.pipe(fe((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(se(i=>i.length>0),me()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:i})=>i===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=ti(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,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(U(this.desiredState.videoTrack.stateChangeStarted$.pipe(w(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(w(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(w(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(w(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(w(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(w(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(w(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(w(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(w(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;P(this.providerContainer),P(t),op(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>np(i)),this.providerContainer.current$.subscribe(({type:i})=>Ui("provider",i)),t.duration$.subscribe(i=>Ui("duration",i)),t.availableVideoTracks$.pipe(se(i=>!!i.length),me()).subscribe(i=>Ui("tracks",i)),this.events.fatalError$.subscribe(new Ke("fatalError")),this.events.managedError$.subscribe(new Ke("managedError")),t.position$.subscribe(new Ke("position")),t.currentVideoTrack$.pipe(w(i=>i==null?void 0:i.quality)).subscribe(new Ke("quality")),this.info.currentBuffer$.subscribe(new Ke("buffer")),t.isBuffering$.subscribe(new Ke("isBuffering"))].forEach(i=>this.subscription.add(i)),Ui("codecs",Rv())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:C.DOM,message:String(r)})})};this.subscription.add(U(B(document,"visibilitychange"),B(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",a=this.desiredState.playbackState.getState()===p.PLAYING,n=!!e&&!(e!=null&&e.released);r&&a?n||i():t()})).add(this.events.willDestruct$.subscribe(t))}}const Kv=`@vkontakte/videoplayer-core@${yd}`;export{ye as ChromecastState,gi as HttpConnectionType,Zv as Observable,p as PlaybackState,Qv as Player,Kv as SDK_VERSION,eg as Subject,tg as Subscription,gt as Surface,yd as VERSION,ig as ValueSubject,y as VideoFormat,sg as VideoQuality};