@vkontakte/videoplayer-core 2.0.99 → 2.0.100
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +10 -10
- package/es2015.esm.js +10 -10
- package/es2018.cjs.js +10 -10
- package/es2018.esm.js +10 -10
- package/esnext.cjs.js +10 -10
- package/esnext.esm.js +11 -11
- package/evergreen.esm.js +11 -11
- package/package.json +1 -1
package/es2018.esm.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.100
|
|
3
|
+
* Fri, 12 Apr 2024 14:49:51 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-100/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{ValueSubject as b,Subject as x,Subscription as ie,isNonNullable as P,ErrorCategory as I,isNullable as Q,fromEvent as C,assertNever as G,merge as N,tap as fi,map as A,observableFrom as Le,filterChanged as ce,assertNonNullable as D,debounce as ze,getHighestQuality as cd,timeout as hd,getCurrentBrowser as Mr,CurrentClientBrowser as Bn,combine as We,once as Ee,mapTo as Ki,filter as ue,VideoQuality as Ae,now as ne,assertNotEmptyArray as fd,videoSizeToQuality as gi,isInvariantQuality as At,isHigher as Qt,isLower as Yi,isHigherOrEqual as Sr,isLowerOrEqual as Ji,interval as Xi,videoQualityToHeight as pd,Observable as os,debounceFn as md,abortable as $e,getExponentialDelay as ji,isIOS as vd,CurrentClientDevice as gd,safeStorage as xs,fillWithDefault as Sd,Logger as bd}from"@vkontakte/videoplayer-shared/es2018.esm.js";import{Observable as sg,Subject as rg,Subscription as ag,ValueSubject as ng,VideoQuality as og}from"@vkontakte/videoplayer-shared/es2018.esm.js";const yd="2.0.99";var p;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(p||(p={}));var y;(function(i){i.MPEG="MPEG",i.DASH="DASH_SEP",i.DASH_SEP="DASH_SEP",i.DASH_SEP_VK="DASH_SEP",i.DASH_WEBM="DASH_WEBM",i.DASH_WEBM_AV1="DASH_WEBM_AV1",i.DASH_WEBM_VK="DASH_WEBM",i.DASH_ONDEMAND="DASH_ONDEMAND",i.DASH_ONDEMAND_VK="DASH_ONDEMAND",i.DASH_LIVE="DASH_LIVE",i.DASH_LIVE_CMAF="DASH_LIVE_CMAF",i.DASH_LIVE_WEBM="DASH_LIVE_WEBM",i.HLS="HLS",i.HLS_ONDEMAND="HLS_ONDEMAND",i.HLS_JS="HLS",i.HLS_LIVE="HLS_LIVE",i.HLS_LIVE_CMAF="HLS_LIVE_CMAF",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(y||(y={}));var be;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(be||(be={}));var ve;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(ve||(ve={}));var br;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(br||(br={}));var q;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(q||(q={}));var ut;(function(i){i.NONE="none",i.INLINE="inline",i.FULLSCREEN="fullscreen",i.SECOND_SCREEN="second_screen",i.PIP="pip"})(ut||(ut={}));var Td=i=>new Promise((e,t)=>{const s=document.createElement("script");s.setAttribute("src",i),s.onload=()=>e,s.onerror=()=>t,document.body.appendChild(s)});class Ed{constructor(e){var t;this.connection$=new b(void 0),this.castState$=new b(ve.NOT_AVAILABLE),this.errorEvent$=new x,this.realCastState$=new b(ve.NOT_AVAILABLE),this.subscription=new ie,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const s="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)return;const r=P((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:I.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var s,r,a;(a=(r=(s=cast.framework.CastContext.getInstance())===null||s===void 0?void 0:s.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||a===void 0||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){P(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();Q(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();Q(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),s=cast.framework.CastContext.getInstance();this.subscription.add(C(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(a=s.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return G(r.sessionState)}})).add(N(C(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(fi(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),A(r=>r.castState)),Le([s.getCastState()])).pipe(ce(),A($d),fi(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===ve.CONNECTED,o=P(this.connection$.getValue());if(n&&!o){const l=s.getCurrentSession();D(l);const d=l.getCastDevice(),u=(a=l.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(Q(u)||u===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:d}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===ve.CONNECTED?P(this.connection$.getValue())?ve.CONNECTED:ve.AVAILABLE:r)}))}initializeCastApi(){var e;let t,s,r;try{t=cast.framework.CastContext.getInstance(),s=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:s,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:I.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const $d=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return ve.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return ve.AVAILABLE;case cast.framework.CastState.CONNECTING:return ve.CONNECTING;case cast.framework.CastState.CONNECTED:return ve.CONNECTED;default:return G(i)}};var _s=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Br(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var st=function(i){try{return!!i()}catch(e){return!0}},wd=st,ds=!wd(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),Nn=ds,Fn=Function.prototype,yr=Fn.call,Ad=Nn&&Fn.bind.bind(yr,yr),rt=Nn?Ad:function(i){return function(){return yr.apply(i,arguments)}},Vn=rt,kd=Vn({}.toString),Pd=Vn("".slice),ls=function(i){return Pd(kd(i),8,-1)},Dd=rt,Rd=st,Ld=ls,Cs=Object,Id=Dd("".split),xd=Rd(function(){return!Cs("z").propertyIsEnumerable(0)})?function(i){return Ld(i)=="String"?Id(i,""):Cs(i)}:Cs,us=function(i){return i==null},_d=us,Cd=TypeError,Nr=function(i){if(_d(i))throw Cd("Can't call method on "+i);return i},Od=xd,Md=Nr,Si=function(i){return Od(Md(i))},Zt={},Di=function(i){return i&&i.Math==Math&&i},Be=Di(typeof globalThis=="object"&&globalThis)||Di(typeof window=="object"&&window)||Di(typeof self=="object"&&self)||Di(typeof _s=="object"&&_s)||function(){return this}()||_s||Function("return this")(),Tr=typeof document=="object"&&document.all,Bd=typeof Tr=="undefined"&&Tr!==void 0,Un={all:Tr,IS_HTMLDDA:Bd},Hn=Un,Nd=Hn.all,Ie=Hn.IS_HTMLDDA?function(i){return typeof i=="function"||i===Nd}:function(i){return typeof i=="function"},Fd=Be,Vd=Ie,ma=Fd.WeakMap,Ud=Vd(ma)&&/native code/.test(String(ma)),va=Ie,Gn=Un,Hd=Gn.all,kt=Gn.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:va(i)||i===Hd}:function(i){return typeof i=="object"?i!==null:va(i)},Gd=st,Pt=!Gd(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),ei={},Yd=Be,ga=kt,Er=Yd.document,jd=ga(Er)&&ga(Er.createElement),Yn=function(i){return jd?Er.createElement(i):{}},qd=Pt,zd=st,Wd=Yn,jn=!qd&&!zd(function(){return Object.defineProperty(Wd("div"),"a",{get:function(){return 7}}).a!=7}),Qd=Pt,Kd=st,qn=Qd&&Kd(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Jd=kt,Xd=String,Zd=TypeError,Dt=function(i){if(Jd(i))return i;throw Zd(Xd(i)+" is not an object")},el=ds,Ri=Function.prototype.call,at=el?Ri.bind(Ri):function(){return Ri.apply(Ri,arguments)},Fr={},Os=Fr,Ms=Be,tl=Ie,Sa=function(i){return tl(i)?i:void 0},Vr=function(i,e){return arguments.length<2?Sa(Os[i])||Sa(Ms[i]):Os[i]&&Os[i][e]||Ms[i]&&Ms[i][e]},il=rt,Ur=il({}.isPrototypeOf),sl=typeof navigator!="undefined"&&String(navigator.userAgent)||"",zn=Be,Bs=sl,ba=zn.process,ya=zn.Deno,Ta=ba&&ba.versions||ya&&ya.version,Ea=Ta&&Ta.v8,Oe,Zi;Ea&&(Oe=Ea.split("."),Zi=Oe[0]>0&&Oe[0]<4?1:+(Oe[0]+Oe[1]));!Zi&&Bs&&(Oe=Bs.match(/Edge\/(\d+)/),(!Oe||Oe[1]>=74)&&(Oe=Bs.match(/Chrome\/(\d+)/),Oe&&(Zi=+Oe[1])));var rl=Zi,$a=rl,al=st,nl=Be,ol=nl.String,Wn=!!Object.getOwnPropertySymbols&&!al(function(){var i=Symbol();return!ol(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&$a&&$a<41}),dl=Wn,Qn=dl&&!Symbol.sham&&typeof Symbol.iterator=="symbol",ll=Vr,ul=Ie,cl=Ur,hl=Qn,fl=Object,Kn=hl?function(i){return typeof i=="symbol"}:function(i){var e=ll("Symbol");return ul(e)&&cl(e.prototype,fl(i))},pl=String,Hr=function(i){try{return pl(i)}catch(e){return"Object"}},ml=Ie,vl=Hr,gl=TypeError,Gr=function(i){if(ml(i))return i;throw gl(vl(i)+" is not a function")},Sl=Gr,bl=us,cs=function(i,e){var t=i[e];return bl(t)?void 0:Sl(t)},Ns=at,Fs=Ie,Vs=kt,yl=TypeError,Tl=function(i,e){var t,s;if(e==="string"&&Fs(t=i.toString)&&!Vs(s=Ns(t,i))||Fs(t=i.valueOf)&&!Vs(s=Ns(t,i))||e!=="string"&&Fs(t=i.toString)&&!Vs(s=Ns(t,i)))return s;throw yl("Can't convert object to primitive value")},Jn={exports:{}},wa=Be,El=Object.defineProperty,$l=function(i,e){try{El(wa,i,{value:e,configurable:!0,writable:!0})}catch(t){wa[i]=e}return e},wl=Be,Al=$l,Aa="__core-js_shared__",kl=wl[Aa]||Al(Aa,{}),Xn=kl,ka=Xn;(Jn.exports=function(i,e){return ka[i]||(ka[i]=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 Zn=Jn.exports,Pl=Nr,Dl=Object,hs=function(i){return Dl(Pl(i))},Rl=rt,Ll=hs,Il=Rl({}.hasOwnProperty),nt=Object.hasOwn||function(e,t){return Il(Ll(e),t)},xl=rt,_l=0,Cl=Math.random(),Ol=xl(1 .toString),eo=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Ol(++_l+Cl,36)},Ml=Be,Bl=Zn,Pa=nt,Nl=eo,Fl=Wn,Vl=Qn,qt=Ml.Symbol,Us=Bl("wks"),Ul=Vl?qt.for||qt:qt&&qt.withoutSetter||Nl,Ne=function(i){return Pa(Us,i)||(Us[i]=Fl&&Pa(qt,i)?qt[i]:Ul("Symbol."+i)),Us[i]},Hl=at,Da=kt,Ra=Kn,Gl=cs,Yl=Tl,jl=Ne,ql=TypeError,zl=jl("toPrimitive"),Wl=function(i,e){if(!Da(i)||Ra(i))return i;var t=Gl(i,zl),s;if(t){if(e===void 0&&(e="default"),s=Hl(t,i,e),!Da(s)||Ra(s))return s;throw ql("Can't convert object to primitive value")}return e===void 0&&(e="number"),Yl(i,e)},Ql=Wl,Kl=Kn,Yr=function(i){var e=Ql(i,"string");return Kl(e)?e:e+""},Jl=Pt,Xl=jn,Zl=qn,Li=Dt,La=Yr,eu=TypeError,Hs=Object.defineProperty,tu=Object.getOwnPropertyDescriptor,Gs="enumerable",Ys="configurable",js="writable";ei.f=Jl?Zl?function(e,t,s){if(Li(e),t=La(t),Li(s),typeof e=="function"&&t==="prototype"&&"value"in s&&js in s&&!s[js]){var r=tu(e,t);r&&r[js]&&(e[t]=s.value,s={configurable:Ys in s?s[Ys]:r[Ys],enumerable:Gs in s?s[Gs]:r[Gs],writable:!1})}return Hs(e,t,s)}:Hs:function(e,t,s){if(Li(e),t=La(t),Li(s),Xl)try{return Hs(e,t,s)}catch(r){}if("get"in s||"set"in s)throw eu("Accessors not supported");return"value"in s&&(e[t]=s.value),e};var fs=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},iu=Pt,su=ei,ru=fs,bi=iu?function(i,e,t){return su.f(i,e,ru(1,t))}:function(i,e,t){return i[e]=t,i},au=Zn,nu=eo,Ia=au("keys"),jr=function(i){return Ia[i]||(Ia[i]=nu(i))},qr={},ou=Ud,to=Be,du=kt,lu=bi,qs=nt,zs=Xn,uu=jr,cu=qr,xa="Object already initialized",$r=to.TypeError,hu=to.WeakMap,es,pi,ts,fu=function(i){return ts(i)?pi(i):es(i,{})},pu=function(i){return function(e){var t;if(!du(e)||(t=pi(e)).type!==i)throw $r("Incompatible receiver, "+i+" required");return t}};if(ou||zs.state){var Ue=zs.state||(zs.state=new hu);Ue.get=Ue.get,Ue.has=Ue.has,Ue.set=Ue.set,es=function(i,e){if(Ue.has(i))throw $r(xa);return e.facade=i,Ue.set(i,e),e},pi=function(i){return Ue.get(i)||{}},ts=function(i){return Ue.has(i)}}else{var Vt=uu("state");cu[Vt]=!0,es=function(i,e){if(qs(i,Vt))throw $r(xa);return e.facade=i,lu(i,Vt,e),e},pi=function(i){return qs(i,Vt)?i[Vt]:{}},ts=function(i){return qs(i,Vt)}}var mu={set:es,get:pi,has:ts,enforce:fu,getterFor:pu},vu=ds,io=Function.prototype,_a=io.apply,Ca=io.call,gu=typeof Reflect=="object"&&Reflect.apply||(vu?Ca.bind(_a):function(){return Ca.apply(_a,arguments)}),Su=ls,bu=rt,so=function(i){if(Su(i)==="Function")return bu(i)},ro={},ao={},no={}.propertyIsEnumerable,oo=Object.getOwnPropertyDescriptor,yu=oo&&!no.call({1:2},1);ao.f=yu?function(e){var t=oo(this,e);return!!t&&t.enumerable}:no;var Tu=Pt,Eu=at,$u=ao,wu=fs,Au=Si,ku=Yr,Pu=nt,Du=jn,Oa=Object.getOwnPropertyDescriptor;ro.f=Tu?Oa:function(e,t){if(e=Au(e),t=ku(t),Du)try{return Oa(e,t)}catch(s){}if(Pu(e,t))return wu(!Eu($u.f,e,t),e[t])};var Ru=st,Lu=Ie,Iu=/#|\.prototype\./,yi=function(i,e){var t=_u[xu(i)];return t==Ou?!0:t==Cu?!1:Lu(e)?Ru(e):!!e},xu=yi.normalize=function(i){return String(i).replace(Iu,".").toLowerCase()},_u=yi.data={},Cu=yi.NATIVE="N",Ou=yi.POLYFILL="P",Mu=yi,Ma=so,Bu=Gr,Nu=ds,Fu=Ma(Ma.bind),lo=function(i,e){return Bu(i),e===void 0?i:Nu?Fu(i,e):function(){return i.apply(e,arguments)}},Ii=Be,Vu=gu,Uu=so,Hu=Ie,Gu=ro.f,Yu=Mu,Ut=Fr,ju=lo,Ht=bi,Ba=nt,qu=function(i){var e=function(t,s,r){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,s)}return new i(t,s,r)}return Vu(i,this,arguments)};return e.prototype=i.prototype,e},ps=function(i,e){var t=i.target,s=i.global,r=i.stat,a=i.proto,n=s?Ii:r?Ii[t]:(Ii[t]||{}).prototype,o=s?Ut:Ut[t]||Ht(Ut,t,{})[t],l=o.prototype,d,u,c,h,f,g,m,v,S;for(h in e)d=Yu(s?h:t+(r?".":"#")+h,i.forced),u=!d&&n&&Ba(n,h),g=o[h],u&&(i.dontCallGetSet?(S=Gu(n,h),m=S&&S.value):m=n[h]),f=u&&m?m:e[h],!(u&&typeof g==typeof f)&&(i.bind&&u?v=ju(f,Ii):i.wrap&&u?v=qu(f):a&&Hu(f)?v=Uu(f):v=f,(i.sham||f&&f.sham||g&&g.sham)&&Ht(v,"sham",!0),Ht(o,h,v),a&&(c=t+"Prototype",Ba(Ut,c)||Ht(Ut,c,{}),Ht(Ut[c],h,f),i.real&&l&&(d||!l[h])&&Ht(l,h,f)))},wr=Pt,zu=nt,uo=Function.prototype,Wu=wr&&Object.getOwnPropertyDescriptor,zr=zu(uo,"name"),Qu=zr&&function(){}.name==="something",Ku=zr&&(!wr||wr&&Wu(uo,"name").configurable),Ju={EXISTS:zr,PROPER:Qu,CONFIGURABLE:Ku},co={},Xu=Math.ceil,Zu=Math.floor,ec=Math.trunc||function(e){var t=+e;return(t>0?Zu:Xu)(t)},tc=ec,Wr=function(i){var e=+i;return e!==e||e===0?0:tc(e)},ic=Wr,sc=Math.max,rc=Math.min,ac=function(i,e){var t=ic(i);return t<0?sc(t+e,0):rc(t,e)},nc=Wr,oc=Math.min,dc=function(i){return i>0?oc(nc(i),9007199254740991):0},lc=dc,Qr=function(i){return lc(i.length)},uc=Si,cc=ac,hc=Qr,Na=function(i){return function(e,t,s){var r=uc(e),a=hc(r),n=cc(s,a),o;if(i&&t!=t){for(;a>n;)if(o=r[n++],o!=o)return!0}else for(;a>n;n++)if((i||n in r)&&r[n]===t)return i||n||0;return!i&&-1}},fc={includes:Na(!0),indexOf:Na(!1)},pc=rt,Ws=nt,mc=Si,vc=fc.indexOf,gc=qr,Fa=pc([].push),Sc=function(i,e){var t=mc(i),s=0,r=[],a;for(a in t)!Ws(gc,a)&&Ws(t,a)&&Fa(r,a);for(;e.length>s;)Ws(t,a=e[s++])&&(~vc(r,a)||Fa(r,a));return r},ho=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],bc=Sc,yc=ho,Tc=Object.keys||function(e){return bc(e,yc)},Ec=Pt,$c=qn,wc=ei,Ac=Dt,kc=Si,Pc=Tc;co.f=Ec&&!$c?Object.defineProperties:function(e,t){Ac(e);for(var s=kc(t),r=Pc(t),a=r.length,n=0,o;a>n;)wc.f(e,o=r[n++],s[o]);return e};var Dc=Vr,Rc=Dc("document","documentElement"),Lc=Dt,Ic=co,Va=ho,xc=qr,_c=Rc,Cc=Yn,Oc=jr,Ua=">",Ha="<",Ar="prototype",kr="script",fo=Oc("IE_PROTO"),Qs=function(){},po=function(i){return Ha+kr+Ua+i+Ha+"/"+kr+Ua},Ga=function(i){i.write(po("")),i.close();var e=i.parentWindow.Object;return i=null,e},Mc=function(){var i=Cc("iframe"),e="java"+kr+":",t;return i.style.display="none",_c.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(po("document.F=Object")),t.close(),t.F},xi,qi=function(){try{xi=new ActiveXObject("htmlfile")}catch(e){}qi=typeof document!="undefined"?document.domain&&xi?Ga(xi):Mc():Ga(xi);for(var i=Va.length;i--;)delete qi[Ar][Va[i]];return qi()};xc[fo]=!0;var mo=Object.create||function(e,t){var s;return e!==null?(Qs[Ar]=Lc(e),s=new Qs,Qs[Ar]=null,s[fo]=e):s=qi(),t===void 0?s:Ic.f(s,t)},Bc=st,Nc=!Bc(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),Fc=nt,Vc=Ie,Uc=hs,Hc=jr,Gc=Nc,Ya=Hc("IE_PROTO"),Pr=Object,Yc=Pr.prototype,vo=Gc?Pr.getPrototypeOf:function(i){var e=Uc(i);if(Fc(e,Ya))return e[Ya];var t=e.constructor;return Vc(t)&&e instanceof t?t.prototype:e instanceof Pr?Yc:null},jc=bi,go=function(i,e,t,s){return s&&s.enumerable?i[e]=t:jc(i,e,t),i},qc=st,zc=Ie,Wc=kt,Qc=mo,ja=vo,Kc=go,Jc=Ne,Dr=Jc("iterator"),So=!1,et,Ks,Js;[].keys&&(Js=[].keys(),"next"in Js?(Ks=ja(ja(Js)),Ks!==Object.prototype&&(et=Ks)):So=!0);var Xc=!Wc(et)||qc(function(){var i={};return et[Dr].call(i)!==i});Xc?et={}:et=Qc(et);zc(et[Dr])||Kc(et,Dr,function(){return this});var bo={IteratorPrototype:et,BUGGY_SAFARI_ITERATORS:So},Zc=Ne,eh=Zc("toStringTag"),yo={};yo[eh]="z";var Kr=String(yo)==="[object z]",th=Kr,ih=Ie,zi=ls,sh=Ne,rh=sh("toStringTag"),ah=Object,nh=zi(function(){return arguments}())=="Arguments",oh=function(i,e){try{return i[e]}catch(t){}},ms=th?zi:function(i){var e,t,s;return i===void 0?"Undefined":i===null?"Null":typeof(t=oh(e=ah(i),rh))=="string"?t:nh?zi(e):(s=zi(e))=="Object"&&ih(e.callee)?"Arguments":s},dh=Kr,lh=ms,uh=dh?{}.toString:function(){return"[object "+lh(this)+"]"},ch=Kr,hh=ei.f,fh=bi,ph=nt,mh=uh,vh=Ne,qa=vh("toStringTag"),To=function(i,e,t,s){if(i){var r=t?i:i.prototype;ph(r,qa)||hh(r,qa,{configurable:!0,value:e}),s&&!ch&&fh(r,"toString",mh)}},gh=bo.IteratorPrototype,Sh=mo,bh=fs,yh=To,Th=Zt,Eh=function(){return this},$h=function(i,e,t,s){var r=e+" Iterator";return i.prototype=Sh(gh,{next:bh(+!s,t)}),yh(i,r,!1,!0),Th[r]=Eh,i},wh=ps,Ah=at,Eo=Ju,kh=$h,Ph=vo,Dh=To,za=go,Rh=Ne,Wa=Zt,$o=bo,Lh=Eo.PROPER;Eo.CONFIGURABLE;$o.IteratorPrototype;var _i=$o.BUGGY_SAFARI_ITERATORS,Xs=Rh("iterator"),Qa="keys",Ci="values",Ka="entries",Ih=function(){return this},xh=function(i,e,t,s,r,a,n){kh(t,e,s);var o=function(S){if(S===r&&h)return h;if(!_i&&S in u)return u[S];switch(S){case Qa:return function(){return new t(this,S)};case Ci:return function(){return new t(this,S)};case Ka:return function(){return new t(this,S)}}return function(){return new t(this)}},l=e+" Iterator",d=!1,u=i.prototype,c=u[Xs]||u["@@iterator"]||r&&u[r],h=!_i&&c||o(r),f=e=="Array"&&u.entries||c,g,m,v;if(f&&(g=Ph(f.call(new i)),g!==Object.prototype&&g.next&&(Dh(g,l,!0,!0),Wa[l]=Ih)),Lh&&r==Ci&&c&&c.name!==Ci&&(d=!0,h=function(){return Ah(c,this)}),r)if(m={values:o(Ci),keys:a?h:o(Qa),entries:o(Ka)},n)for(v in m)(_i||d||!(v in u))&&za(u,v,m[v]);else wh({target:e,proto:!0,forced:_i||d},m);return n&&u[Xs]!==h&&za(u,Xs,h,{name:r}),Wa[e]=h,m},_h=function(i,e){return{value:i,done:e}},Ch=Si,Ja=Zt,wo=mu;ei.f;var Oh=xh,Oi=_h,Ao="Array Iterator",Mh=wo.set,Bh=wo.getterFor(Ao);Oh(Array,"Array",function(i,e){Mh(this,{type:Ao,target:Ch(i),index:0,kind:e})},function(){var i=Bh(this),e=i.target,t=i.kind,s=i.index++;return!e||s>=e.length?(i.target=void 0,Oi(void 0,!0)):t=="keys"?Oi(s,!1):t=="values"?Oi(e[s],!1):Oi([s,e[s]],!1)},"values");Ja.Arguments=Ja.Array;var Nh=Ne,Fh=Zt,Vh=Nh("iterator"),Uh=Array.prototype,Hh=function(i){return i!==void 0&&(Fh.Array===i||Uh[Vh]===i)},Gh=ms,Xa=cs,Yh=us,jh=Zt,qh=Ne,zh=qh("iterator"),ko=function(i){if(!Yh(i))return Xa(i,zh)||Xa(i,"@@iterator")||jh[Gh(i)]},Wh=at,Qh=Gr,Kh=Dt,Jh=Hr,Xh=ko,Zh=TypeError,ef=function(i,e){var t=arguments.length<2?Xh(i):e;if(Qh(t))return Kh(Wh(t,i));throw Zh(Jh(i)+" is not iterable")},tf=at,Za=Dt,sf=cs,rf=function(i,e,t){var s,r;Za(i);try{if(s=sf(i,"return"),!s){if(e==="throw")throw t;return t}s=tf(s,i)}catch(a){r=!0,s=a}if(e==="throw")throw t;if(r)throw s;return Za(s),t},af=lo,nf=at,of=Dt,df=Hr,lf=Hh,uf=Qr,en=Ur,cf=ef,hf=ko,tn=rf,ff=TypeError,Wi=function(i,e){this.stopped=i,this.result=e},sn=Wi.prototype,pf=function(i,e,t){var s=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),l=af(e,s),d,u,c,h,f,g,m,v=function(E){return d&&tn(d,"normal",E),new Wi(!0,E)},S=function(E){return r?(of(E),o?l(E[0],E[1],v):l(E[0],E[1])):o?l(E,v):l(E)};if(a)d=i.iterator;else if(n)d=i;else{if(u=hf(i),!u)throw ff(df(i)+" is not iterable");if(lf(u)){for(c=0,h=uf(i);h>c;c++)if(f=S(i[c]),f&&en(sn,f))return f;return new Wi(!1)}d=cf(i,u)}for(g=a?i.next:d.next;!(m=nf(g,d)).done;){try{f=S(m.value)}catch(E){tn(d,"throw",E)}if(typeof f=="object"&&f&&en(sn,f))return f}return new Wi(!1)},mf=Yr,vf=ei,gf=fs,Sf=function(i,e,t){var s=mf(e);s in i?vf.f(i,s,gf(0,t)):i[s]=t},bf=ps,yf=pf,Tf=Sf;bf({target:"Object",stat:!0},{fromEntries:function(e){var t={};return yf(e,function(s,r){Tf(t,s,r)},{AS_ENTRIES:!0}),t}});var Ef=Fr,$f=Ef.Object.fromEntries,wf={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},Af=wf,kf=Be,Pf=ms,Df=bi,rn=Zt,Rf=Ne,an=Rf("toStringTag");for(var Zs in Af){var nn=kf[Zs],er=nn&&nn.prototype;er&&Pf(er)!==an&&Df(er,an,Zs),rn[Zs]=rn.Array}var Lf=$f,If=Lf,xf=If,_f=xf,is=Br(_f),pe;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",i[i.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(pe||(pe={}));var Me=(i,e=0,t=pe.OFFSET_P)=>{switch(t){case pe.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case pe.PLAYBACK_SHIFT:{if(e===0)return i;const s=new URL(i);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}case pe.DASH_CMAF_OFFSET_P:{const s=new URL(i);return!s.searchParams.get("offset_p")&&e===0?i:(s.searchParams.set("offset_p",e.toFixed(0)),s.toString())}default:G(t)}return i};const on=(i,e)=>{var t;switch(e){case pe.OFFSET_P:return NaN;case pe.PLAYBACK_SHIFT:{const s=new URL(i);return Number(s.searchParams.get("playback_shift"))}case pe.DASH_CMAF_OFFSET_P:{const s=new URL(i);return Number((t=s.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:G(e)}};var O=(i,e,t=!1)=>{const s=i.getTransition();(t||!s||s.to===e)&&i.setState(e)};class le{constructor(e){this.transitionStarted$=new x,this.transitionEnded$=new x,this.transitionUpdated$=new x,this.forceChanged$=new x,this.stateChangeStarted$=N(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=N(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,s=this.state;this.transition=void 0,this.prevState=s,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:s,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,s=this.state;s===e||P(t)&&t.to===e||(this.prevState=s,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const Cf=i=>{switch(i){case y.MPEG: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 G(i)}};var F;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(F||(F={}));const Of=5,Mf=5,Bf=500,dn=7e3;class Nf{constructor(e){this.subscription=new ie,this.loadMediaTimeoutSubscription=new ie,this.videoState=new le(F.STOPPED),this.syncPlayback=()=>{const s=this.videoState.getState(),r=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${s}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${a}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(o)};`}),a===p.STOPPED){s!==F.STOPPED&&(this.videoState.startTransitionTo(F.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==p.PAUSED&&o.state===q.Requested&&s!==F.STOPPED){this.seek(o.position/1e3);return}switch(a){case p.READY:{switch(s){case F.PLAYING:case F.PAUSED:case F.READY:break;case F.STOPPED:this.videoState.startTransitionTo(F.READY),this.prepare();break;default:G(s)}break}case p.PLAYING:{switch(s){case F.PLAYING:break;case F.PAUSED:this.videoState.startTransitionTo(F.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case F.READY:this.videoState.startTransitionTo(F.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case F.STOPPED:this.videoState.startTransitionTo(F.READY),this.prepare();break;default:G(s)}break}case p.PAUSED:{switch(s){case F.PLAYING:this.videoState.startTransitionTo(F.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case F.PAUSED:break;case F.READY:this.videoState.startTransitionTo(F.PAUSED),this.videoState.setState(F.PAUSED);break;case F.STOPPED:this.videoState.startTransitionTo(F.READY),this.prepare();break;default:G(s)}break}default:G(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 ie;this.subscription.add(e),this.subscription.add(N(this.videoState.stateChangeStarted$.pipe(A(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(A(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 x;e.add(r.pipe(ze(Bf)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(C(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===q.Applying||Math.abs(o-a)>Of)&&r.next(o),a=o})),e.add(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(C(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(),l=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==l&&this.params.output.isBuffering$.next(l),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<Mf&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),O(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:G(n)}}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const s=N(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Le(["init"])).pipe(ze(0));t(s,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(F.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):(this.videoState.setState(F.PLAYING),O(this.params.desiredState.playbackState,p.PLAYING));const s=this.params.output.isLive$.getValue();this.params.output.duration$.next(s?0:t.duration),this.params.output.position$.next(s?0:t.currentTime),this.params.desiredState.seekState.setState({state:q.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),s=this.createLoadRequest(t);this.loadMedia(s)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===F.PAUSED||e===F.PLAYING)&&(this.videoState.setState(F.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===F.PLAYING||e===F.PAUSED)&&(this.videoState.setState(F.PLAYING),O(this.params.desiredState.playbackState,p.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===F.READY&&this.videoState.setState(F.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===p.READY&&O(this.params.desiredState.playbackState,p.READY)}handleRemoteStop(){this.videoState.getState()!==F.STOPPED&&this.videoState.setState(F.STOPPED)}handleRemoteVolumeChange(e){var t,s;const r=this.params.output.volume$.getValue(),a={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(s=e.muted)!==null&&s!==void 0?s:r.muted};(a.volume!==r.volume||a.muted!==a.muted)&&this.params.output.volume$.next(a)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:s}=this.params.connection;t.currentTime=e,s.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const s=this.params.source;let r,a,n;switch(e){case y.MPEG:{const u=s[e];D(u);const c=cd(Object.keys(u));D(c);const h=u[c];D(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case y.HLS:case y.HLS_ONDEMAND:{const u=s[e];D(u),r=u.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 u=s[e];D(u),r=u.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_LIVE_CMAF:{const u=s[e];D(u),r=u.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const u=s[e];D(u),r=Me(u.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case y.DASH_LIVE:case y.WEB_RTC_LIVE:{const u="Unsupported format for Chromecast",c=new Error(u);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:I.VIDEO_PIPELINE,message:u,thrown:c}),c}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return G(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:l,subtitle:d}=this.params.meta;return P(l)&&(o.metadata.title=l),P(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const s=this.params.desiredState.seekState.getState();return s.state===q.Applying||s.state===q.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:s.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),s=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(hd(dn).subscribe(()=>a(`timeout(${dn})`)))});Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===q.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:I.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}const Jr=i=>{i.removeAttribute("src"),i.load()},Ff=i=>{try{i.pause(),i.playbackRate=0,Jr(i),i.remove()}catch(e){console.error(e)}};class Vf{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 Rr=window.WeakMap?new WeakMap:new Vf,Rt=i=>{let e=i.querySelector("video");const t=!!e;return e?Jr(e):(e=document.createElement("video"),i.appendChild(e)),Rr.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},Lt=i=>{const e=Rr.get(i);Rr.delete(i),e?Jr(i):Ff(i)},Xe=(i,e,t,{equal:s=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=i.getState(),o=e(),l=Q(r),d=new ie;return r&&d.add(r.subscribe(u=>{const c=i.getState();s(u,c)&&i.setState(u)},a)),s(o,n)||(t(n),l&&i.setState(n)),d.add(i.stateChangeStarted$.subscribe(u=>{t(u.to),l&&i.setState(u.to)},a)),d},Ti=(i,e,t)=>Xe(e,()=>i.loop,s=>{P(s)&&(i.loop=s)},{onError:t}),It=(i,e,t,s)=>Xe(e,()=>({muted:i.muted,volume:i.volume}),r=>{P(r)&&(i.muted=r.muted,i.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:s}),ti=(i,e,t,s)=>Xe(e,()=>i.playbackRate,r=>{P(r)&&(i.playbackRate=r)},{changed$:t,onError:s}),Uf=i=>["__",i.language,i.label].join("|"),Hf=(i,e)=>{if(i.id===e)return!0;const[t,s,r]=e.split("|");return i.language===s&&i.label===r};class ft{constructor(){this.available$=new x,this.current$=new b(void 0),this.error$=new x,this.subscription=new ie,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:I.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(Xe(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{P(a)&&this.setInternal(a)},{equal:(a,n)=>P(a)&&P(n)&&a.length===n.length&&a.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe(A(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Xe(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{P(a)&&this.setExternal(a)},{equal:(a,n)=>P(a)&&P(n)&&a.length===n.length&&a.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe(A(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Xe(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(Xe(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){D(this.video);const{textTracks:e}=this.video;this.subscription.add(C(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();s&&this.select(s)})),this.subscription.add(N(C(e,"addtrack"),C(e,"removetrack"),Le(["init"])).pipe(A(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),ce((s,r)=>s.length===r.length&&s.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(N(C(e,"change"),Le(["init"])).pipe(A(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),A(s=>s&&this.htmlTextTrackToITextTrack(s).id),ce()).subscribe(this.current$));const t=s=>{var r,a;return this.applyCueSettings((a=(r=s.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(C(e,"addtrack").subscribe(s=>{var r,a;(r=s.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var l,d,u,c,h;const f=(d=(l=o.target)===null||l===void 0?void 0:l.cues)!==null&&d!==void 0?d:null;f&&f.length&&(this.applyCueSettings((c=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&c!==void 0?c:null),(h=o.target)===null||h===void 0||h.removeEventListener("cuechange",n))};(a=s.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(C(e,"removetrack").subscribe(s=>{var r;(r=s.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const s of Array.from(e)){const r=s;P(t.align)&&(r.align=t.align),P(t.position)&&(r.position=t.position),P(t.size)&&(r.size=t.size),P(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){D(this.video);const t=[...this.video.textTracks];return e?t:t.filter(ft.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,s;const{language:r,label:a}=e,n=e.id?e.id:Uf(e),o=this.externalTracks.has(n),l=n.includes("auto");return o?{id:n,type:"external",isAuto:l,language:r,label:a,url:(t=this.externalTracks.get(n))===null||t===void 0?void 0:t.url}:{id:n,type:"internal",isAuto:l,language:r,label:a,url:(s=this.internalTracks.get(n))===null||s===void 0?void 0:s.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(s=>s.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:s,language:r,isAuto:a})=>!this.internalTracks.has(s)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(s=>this.attach(s)),Array.from(this.internalTracks).filter(([s])=>!e.find(r=>r.id===s)).forEach(([,s])=>this.detach(s))}select(e){D(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(Q(e)||!Hf(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){D(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){D(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),s=>s.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)}}class Xr{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=i=>{var e;let t=i;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},ln=i=>{const e=Po(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Gf=i=>{const e=Po(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)},Yf=3;var jf=(i,e,t=Yf)=>{let s=0,r=0;for(let a=0;a<i.length;a++){const n=i.start(a),o=i.end(a);if(n<=e&&e<=o){if(s=n,r=o,!t)return{from:s,to:r};for(let l=a-1;l>=0;l--)i.end(l)+t>=s&&(s=i.start(l));for(let l=a+1;l<i.length;l++)i.start(l)-t<=r&&(r=i.end(l))}}return{from:s,to:r}};const xt=i=>{const e=w=>C(i,w).pipe(Ki(void 0)),s=N(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map(w=>C(i,w))).pipe(A(w=>w.type==="ended"?i.readyState<2:i.readyState<3),ce()),r=N(C(i,"progress"),C(i,"timeupdate")).pipe(A(()=>jf(i.buffered,i.currentTime))),n=Mr().browser===Bn.Safari?We({play:e("play").pipe(Ee()),playing:e("playing")}).pipe(Ki(void 0)):e("playing"),o=C(i,"volumechange").pipe(A(()=>({muted:i.muted,volume:i.volume}))),l=C(i,"ratechange").pipe(A(()=>i.playbackRate)),d=C(i,"error").pipe(ue(()=>!!(i.error||i.played.length)),A(()=>{var w;const $=i.error;return{id:$?`MediaError#${$.code}`:"HtmlVideoError",category:I.VIDEO_PIPELINE,message:$?$.message:"Error event from HTML video element",thrown:(w=i.error)!==null&&w!==void 0?w:void 0}})),u=C(i,"timeupdate").pipe(A(()=>i.currentTime)),c=new x,h=.3;let f;u.subscribe(w=>{i.loop&&P(f)&&P(w)&&f>=i.duration-h&&w<=h&&c.next(f),f=w});const g=C(i,"enterpictureinpicture"),m=C(i,"leavepictureinpicture"),v=new b(Gf(i));g.subscribe(()=>v.next(!0)),m.subscribe(()=>v.next(!1));const S=new b(ln(i));return C(i,"fullscreenchange").pipe(A(()=>ln(i))).subscribe(S),{playing$:n,pause$:e("pause").pipe(ue(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:u,durationChange$:C(i,"durationchange").pipe(A(()=>i.duration)),isBuffering$:s,currentBuffer$:r,volumeState$:o,playbackRateState$:l,inPiP$:v,inFullscreen$:S}};var vs=i=>{switch(i){case"mobile":return Ae.Q_144P;case"lowest":return Ae.Q_240P;case"low":return Ae.Q_360P;case"sd":case"medium":return Ae.Q_480P;case"hd":case"high":return Ae.Q_720P;case"fullhd":case"full":return Ae.Q_1080P;case"quadhd":case"quad":return Ae.Q_1440P;case"ultrahd":case"ultra":return Ae.Q_2160P}},qf=ps,zf=hs,Wf=Qr,Qf=Wr;qf({target:"Array",proto:!0},{at:function(e){var t=zf(this),s=Wf(t),r=Qf(e),a=r>=0?r:s+r;return a<0||a>=s?void 0:t[a]}});var Kf=Vr,Do=Kf,Jf=Do,Xf=Jf("Array","at"),Zf=Xf,ep=Zf,tp=ep,ip=tp,Je=Br(ip);let Zr=!1,Ze={};const sp=i=>{Zr=i},rp=()=>{Ze={}},ap=i=>{i(Ze)},Mi=(i,e)=>{var t;Zr&&(Ze.meta=(t=Ze.meta)!==null&&t!==void 0?t:{},Ze.meta[i]=e)};class Ye{constructor(e){this.name=e}next(e){var t,s;if(!Zr)return;Ze.series=(t=Ze.series)!==null&&t!==void 0?t:{};const r=(s=Ze.series[this.name])!==null&&s!==void 0?s:[];r.push([Date.now(),e]),Ze.series[this.name]=r}}var $t;(function(i){i.FitsContainer="FitsContainer",i.FitsThroughput="FitsThroughput",i.Buffer="Buffer",i.DroppedFramesLimit="DroppedFramesLimit",i.FitsQualityLimits="FitsQualityLimits"})($t||($t={}));const np=new Ye("best_bitrate"),op=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class dp{constructor(){this.history={}}recordSelection(e){this.history[e.id]=ne()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const lp='Assertion "ABR Tracks is empty array" failed',gs=(i,{container:e,throughput:t,tuning:s,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:l,history:d,droppedVideoMaxQualityLimit:u,abrLogger:c})=>{var h,f,g,m,v;fd(i,lp);const S=s.usePixelRatio&&(h=window.devicePixelRatio)!==null&&h!==void 0?h:1,E=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*S*s.containerSizeFactor,height:e.height*S*s.containerSizeFactor},w=E&&gi(E),$=s.considerPlaybackRate&&P(o)?o:1,k=i.filter(B=>!At(B.quality)).sort((B,L)=>Qt(B.quality,L.quality)?-1:1),H=(f=Je(k,-1))===null||f===void 0?void 0:f.quality,Y=(g=Je(k,0))===null||g===void 0?void 0:g.quality,K=Q(r)||P(r.min)&&P(r.max)&&Yi(r.max,r.min)||P(r.min)&&Y&&Qt(r.min,Y)||P(r.max)&&H&&Yi(r.max,H),j=$*op(n!=null?n:.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),J={},M=k.filter(B=>(w?Yi(B.quality,w):!0)?(P(t)&&isFinite(t)&&P(B.bitrate)?t-a>=B.bitrate*j:!0)?s.lazyQualitySwitch&&P(s.minBufferToSwitchUp)&&l&&!At(l.quality)&&(n!=null?n:0)<s.minBufferToSwitchUp&&Qt(B.quality,l.quality)?(J[B.quality]=$t.Buffer,!1):!!u&&Sr(B.quality,u)?(J[B.quality]=$t.DroppedFramesLimit,!1):K||(Q(r.max)||Ji(B.quality,r.max))&&(Q(r.min)||Sr(B.quality,r.min))?!0:(J[B.quality]=$t.FitsQualityLimits,!1):(J[B.quality]=$t.FitsThroughput,!1):(J[B.quality]=$t.FitsContainer,!1))[0];M&&M.bitrate&&np.next(M.bitrate);const _=(m=M!=null?M:k[Math.ceil((k.length-1)/2)])!==null&&m!==void 0?m:i[0];_.quality!==((v=d==null?void 0:d.last)===null||v===void 0?void 0:v.quality)&&c({message:`
|
|
6
|
+
import{ValueSubject as b,Subject as x,Subscription as ie,isNonNullable as k,ErrorCategory as I,isNullable as Q,fromEvent as C,assertNever as H,merge as N,tap as pi,map as w,observableFrom as Le,filterChanged as ce,assertNonNullable as D,debounce as ze,getHighestQuality as cd,timeout as hd,getCurrentBrowser as Mr,CurrentClientBrowser as Bn,combine as We,once as Ee,mapTo as Ki,filter as ue,VideoQuality as Ae,now as ne,assertNotEmptyArray as fd,videoSizeToQuality as At,isInvariantQuality as kt,isHigher as Kt,isLower as Yi,isHigherOrEqual as Sr,isLowerOrEqual as Ji,interval as Xi,videoQualityToHeight as pd,Observable as os,debounceFn as md,abortable as $e,getExponentialDelay as qi,isIOS as vd,CurrentClientDevice as gd,safeStorage as xs,fillWithDefault as Sd,Logger as bd}from"@vkontakte/videoplayer-shared/es2018.esm.js";import{Observable as sg,Subject as rg,Subscription as ag,ValueSubject as ng,VideoQuality as og}from"@vkontakte/videoplayer-shared/es2018.esm.js";const yd="2.0.100";var p;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(p||(p={}));var y;(function(i){i.MPEG="MPEG",i.DASH="DASH_SEP",i.DASH_SEP="DASH_SEP",i.DASH_SEP_VK="DASH_SEP",i.DASH_WEBM="DASH_WEBM",i.DASH_WEBM_AV1="DASH_WEBM_AV1",i.DASH_WEBM_VK="DASH_WEBM",i.DASH_ONDEMAND="DASH_ONDEMAND",i.DASH_ONDEMAND_VK="DASH_ONDEMAND",i.DASH_LIVE="DASH_LIVE",i.DASH_LIVE_CMAF="DASH_LIVE_CMAF",i.DASH_LIVE_WEBM="DASH_LIVE_WEBM",i.HLS="HLS",i.HLS_ONDEMAND="HLS_ONDEMAND",i.HLS_JS="HLS",i.HLS_LIVE="HLS_LIVE",i.HLS_LIVE_CMAF="HLS_LIVE_CMAF",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(y||(y={}));var be;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(be||(be={}));var ve;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(ve||(ve={}));var br;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(br||(br={}));var Y;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(Y||(Y={}));var ut;(function(i){i.NONE="none",i.INLINE="inline",i.FULLSCREEN="fullscreen",i.SECOND_SCREEN="second_screen",i.PIP="pip"})(ut||(ut={}));var Td=i=>new Promise((e,t)=>{const s=document.createElement("script");s.setAttribute("src",i),s.onload=()=>e,s.onerror=()=>t,document.body.appendChild(s)});class Ed{constructor(e){var t;this.connection$=new b(void 0),this.castState$=new b(ve.NOT_AVAILABLE),this.errorEvent$=new x,this.realCastState$=new b(ve.NOT_AVAILABLE),this.subscription=new ie,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const s="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)return;const r=k((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:I.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var s,r,a;(a=(r=(s=cast.framework.CastContext.getInstance())===null||s===void 0?void 0:s.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||a===void 0||a.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){k(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();Q(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();Q(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),s=cast.framework.CastContext.getInstance();this.subscription.add(C(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var a,n;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(n=(a=s.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0?void 0:n.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return H(r.sessionState)}})).add(N(C(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(pi(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),w(r=>r.castState)),Le([s.getCastState()])).pipe(ce(),w($d),pi(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var a;const n=r===ve.CONNECTED,o=k(this.connection$.getValue());if(n&&!o){const l=s.getCurrentSession();D(l);const d=l.getCastDevice(),u=(a=l.getMediaSession())===null||a===void 0?void 0:a.media.contentId;(Q(u)||u===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:l,castDevice:d}))}else!n&&o&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===ve.CONNECTED?k(this.connection$.getValue())?ve.CONNECTED:ve.AVAILABLE:r)}))}initializeCastApi(){var e;let t,s,r;try{t=cast.framework.CastContext.getInstance(),s=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(a){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:s,autoJoinPolicy:r}),this.initListeners()}catch(a){this.errorEvent$.next({id:"ChromecastInitializer",category:I.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:a})}}}const $d=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return ve.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return ve.AVAILABLE;case cast.framework.CastState.CONNECTING:return ve.CONNECTING;case cast.framework.CastState.CONNECTED:return ve.CONNECTED;default:return H(i)}};var _s=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Br(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var st=function(i){try{return!!i()}catch(e){return!0}},wd=st,ds=!wd(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),Nn=ds,Fn=Function.prototype,yr=Fn.call,Ad=Nn&&Fn.bind.bind(yr,yr),rt=Nn?Ad:function(i){return function(){return yr.apply(i,arguments)}},Vn=rt,kd=Vn({}.toString),Pd=Vn("".slice),ls=function(i){return Pd(kd(i),8,-1)},Dd=rt,Rd=st,Ld=ls,Cs=Object,Id=Dd("".split),xd=Rd(function(){return!Cs("z").propertyIsEnumerable(0)})?function(i){return Ld(i)=="String"?Id(i,""):Cs(i)}:Cs,us=function(i){return i==null},_d=us,Cd=TypeError,Nr=function(i){if(_d(i))throw Cd("Can't call method on "+i);return i},Od=xd,Md=Nr,Si=function(i){return Od(Md(i))},ei={},Di=function(i){return i&&i.Math==Math&&i},Be=Di(typeof globalThis=="object"&&globalThis)||Di(typeof window=="object"&&window)||Di(typeof self=="object"&&self)||Di(typeof _s=="object"&&_s)||function(){return this}()||_s||Function("return this")(),Tr=typeof document=="object"&&document.all,Bd=typeof Tr=="undefined"&&Tr!==void 0,Un={all:Tr,IS_HTMLDDA:Bd},Hn=Un,Nd=Hn.all,Ie=Hn.IS_HTMLDDA?function(i){return typeof i=="function"||i===Nd}:function(i){return typeof i=="function"},Fd=Be,Vd=Ie,ma=Fd.WeakMap,Ud=Vd(ma)&&/native code/.test(String(ma)),va=Ie,Gn=Un,Hd=Gn.all,Pt=Gn.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:va(i)||i===Hd}:function(i){return typeof i=="object"?i!==null:va(i)},Gd=st,Dt=!Gd(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),ti={},Yd=Be,ga=Pt,Er=Yd.document,qd=ga(Er)&&ga(Er.createElement),Yn=function(i){return qd?Er.createElement(i):{}},jd=Dt,zd=st,Wd=Yn,qn=!jd&&!zd(function(){return Object.defineProperty(Wd("div"),"a",{get:function(){return 7}}).a!=7}),Qd=Dt,Kd=st,jn=Qd&&Kd(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Jd=Pt,Xd=String,Zd=TypeError,Rt=function(i){if(Jd(i))return i;throw Zd(Xd(i)+" is not an object")},el=ds,Ri=Function.prototype.call,at=el?Ri.bind(Ri):function(){return Ri.apply(Ri,arguments)},Fr={},Os=Fr,Ms=Be,tl=Ie,Sa=function(i){return tl(i)?i:void 0},Vr=function(i,e){return arguments.length<2?Sa(Os[i])||Sa(Ms[i]):Os[i]&&Os[i][e]||Ms[i]&&Ms[i][e]},il=rt,Ur=il({}.isPrototypeOf),sl=typeof navigator!="undefined"&&String(navigator.userAgent)||"",zn=Be,Bs=sl,ba=zn.process,ya=zn.Deno,Ta=ba&&ba.versions||ya&&ya.version,Ea=Ta&&Ta.v8,Oe,Zi;Ea&&(Oe=Ea.split("."),Zi=Oe[0]>0&&Oe[0]<4?1:+(Oe[0]+Oe[1]));!Zi&&Bs&&(Oe=Bs.match(/Edge\/(\d+)/),(!Oe||Oe[1]>=74)&&(Oe=Bs.match(/Chrome\/(\d+)/),Oe&&(Zi=+Oe[1])));var rl=Zi,$a=rl,al=st,nl=Be,ol=nl.String,Wn=!!Object.getOwnPropertySymbols&&!al(function(){var i=Symbol();return!ol(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&$a&&$a<41}),dl=Wn,Qn=dl&&!Symbol.sham&&typeof Symbol.iterator=="symbol",ll=Vr,ul=Ie,cl=Ur,hl=Qn,fl=Object,Kn=hl?function(i){return typeof i=="symbol"}:function(i){var e=ll("Symbol");return ul(e)&&cl(e.prototype,fl(i))},pl=String,Hr=function(i){try{return pl(i)}catch(e){return"Object"}},ml=Ie,vl=Hr,gl=TypeError,Gr=function(i){if(ml(i))return i;throw gl(vl(i)+" is not a function")},Sl=Gr,bl=us,cs=function(i,e){var t=i[e];return bl(t)?void 0:Sl(t)},Ns=at,Fs=Ie,Vs=Pt,yl=TypeError,Tl=function(i,e){var t,s;if(e==="string"&&Fs(t=i.toString)&&!Vs(s=Ns(t,i))||Fs(t=i.valueOf)&&!Vs(s=Ns(t,i))||e!=="string"&&Fs(t=i.toString)&&!Vs(s=Ns(t,i)))return s;throw yl("Can't convert object to primitive value")},Jn={exports:{}},wa=Be,El=Object.defineProperty,$l=function(i,e){try{El(wa,i,{value:e,configurable:!0,writable:!0})}catch(t){wa[i]=e}return e},wl=Be,Al=$l,Aa="__core-js_shared__",kl=wl[Aa]||Al(Aa,{}),Xn=kl,ka=Xn;(Jn.exports=function(i,e){return ka[i]||(ka[i]=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 Zn=Jn.exports,Pl=Nr,Dl=Object,hs=function(i){return Dl(Pl(i))},Rl=rt,Ll=hs,Il=Rl({}.hasOwnProperty),nt=Object.hasOwn||function(e,t){return Il(Ll(e),t)},xl=rt,_l=0,Cl=Math.random(),Ol=xl(1 .toString),eo=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Ol(++_l+Cl,36)},Ml=Be,Bl=Zn,Pa=nt,Nl=eo,Fl=Wn,Vl=Qn,zt=Ml.Symbol,Us=Bl("wks"),Ul=Vl?zt.for||zt:zt&&zt.withoutSetter||Nl,Ne=function(i){return Pa(Us,i)||(Us[i]=Fl&&Pa(zt,i)?zt[i]:Ul("Symbol."+i)),Us[i]},Hl=at,Da=Pt,Ra=Kn,Gl=cs,Yl=Tl,ql=Ne,jl=TypeError,zl=ql("toPrimitive"),Wl=function(i,e){if(!Da(i)||Ra(i))return i;var t=Gl(i,zl),s;if(t){if(e===void 0&&(e="default"),s=Hl(t,i,e),!Da(s)||Ra(s))return s;throw jl("Can't convert object to primitive value")}return e===void 0&&(e="number"),Yl(i,e)},Ql=Wl,Kl=Kn,Yr=function(i){var e=Ql(i,"string");return Kl(e)?e:e+""},Jl=Dt,Xl=qn,Zl=jn,Li=Rt,La=Yr,eu=TypeError,Hs=Object.defineProperty,tu=Object.getOwnPropertyDescriptor,Gs="enumerable",Ys="configurable",qs="writable";ti.f=Jl?Zl?function(e,t,s){if(Li(e),t=La(t),Li(s),typeof e=="function"&&t==="prototype"&&"value"in s&&qs in s&&!s[qs]){var r=tu(e,t);r&&r[qs]&&(e[t]=s.value,s={configurable:Ys in s?s[Ys]:r[Ys],enumerable:Gs in s?s[Gs]:r[Gs],writable:!1})}return Hs(e,t,s)}:Hs:function(e,t,s){if(Li(e),t=La(t),Li(s),Xl)try{return Hs(e,t,s)}catch(r){}if("get"in s||"set"in s)throw eu("Accessors not supported");return"value"in s&&(e[t]=s.value),e};var fs=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},iu=Dt,su=ti,ru=fs,bi=iu?function(i,e,t){return su.f(i,e,ru(1,t))}:function(i,e,t){return i[e]=t,i},au=Zn,nu=eo,Ia=au("keys"),qr=function(i){return Ia[i]||(Ia[i]=nu(i))},jr={},ou=Ud,to=Be,du=Pt,lu=bi,js=nt,zs=Xn,uu=qr,cu=jr,xa="Object already initialized",$r=to.TypeError,hu=to.WeakMap,es,mi,ts,fu=function(i){return ts(i)?mi(i):es(i,{})},pu=function(i){return function(e){var t;if(!du(e)||(t=mi(e)).type!==i)throw $r("Incompatible receiver, "+i+" required");return t}};if(ou||zs.state){var Ue=zs.state||(zs.state=new hu);Ue.get=Ue.get,Ue.has=Ue.has,Ue.set=Ue.set,es=function(i,e){if(Ue.has(i))throw $r(xa);return e.facade=i,Ue.set(i,e),e},mi=function(i){return Ue.get(i)||{}},ts=function(i){return Ue.has(i)}}else{var Ut=uu("state");cu[Ut]=!0,es=function(i,e){if(js(i,Ut))throw $r(xa);return e.facade=i,lu(i,Ut,e),e},mi=function(i){return js(i,Ut)?i[Ut]:{}},ts=function(i){return js(i,Ut)}}var mu={set:es,get:mi,has:ts,enforce:fu,getterFor:pu},vu=ds,io=Function.prototype,_a=io.apply,Ca=io.call,gu=typeof Reflect=="object"&&Reflect.apply||(vu?Ca.bind(_a):function(){return Ca.apply(_a,arguments)}),Su=ls,bu=rt,so=function(i){if(Su(i)==="Function")return bu(i)},ro={},ao={},no={}.propertyIsEnumerable,oo=Object.getOwnPropertyDescriptor,yu=oo&&!no.call({1:2},1);ao.f=yu?function(e){var t=oo(this,e);return!!t&&t.enumerable}:no;var Tu=Dt,Eu=at,$u=ao,wu=fs,Au=Si,ku=Yr,Pu=nt,Du=qn,Oa=Object.getOwnPropertyDescriptor;ro.f=Tu?Oa:function(e,t){if(e=Au(e),t=ku(t),Du)try{return Oa(e,t)}catch(s){}if(Pu(e,t))return wu(!Eu($u.f,e,t),e[t])};var Ru=st,Lu=Ie,Iu=/#|\.prototype\./,yi=function(i,e){var t=_u[xu(i)];return t==Ou?!0:t==Cu?!1:Lu(e)?Ru(e):!!e},xu=yi.normalize=function(i){return String(i).replace(Iu,".").toLowerCase()},_u=yi.data={},Cu=yi.NATIVE="N",Ou=yi.POLYFILL="P",Mu=yi,Ma=so,Bu=Gr,Nu=ds,Fu=Ma(Ma.bind),lo=function(i,e){return Bu(i),e===void 0?i:Nu?Fu(i,e):function(){return i.apply(e,arguments)}},Ii=Be,Vu=gu,Uu=so,Hu=Ie,Gu=ro.f,Yu=Mu,Ht=Fr,qu=lo,Gt=bi,Ba=nt,ju=function(i){var e=function(t,s,r){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,s)}return new i(t,s,r)}return Vu(i,this,arguments)};return e.prototype=i.prototype,e},ps=function(i,e){var t=i.target,s=i.global,r=i.stat,a=i.proto,n=s?Ii:r?Ii[t]:(Ii[t]||{}).prototype,o=s?Ht:Ht[t]||Gt(Ht,t,{})[t],l=o.prototype,d,u,c,h,f,g,m,v,S;for(h in e)d=Yu(s?h:t+(r?".":"#")+h,i.forced),u=!d&&n&&Ba(n,h),g=o[h],u&&(i.dontCallGetSet?(S=Gu(n,h),m=S&&S.value):m=n[h]),f=u&&m?m:e[h],!(u&&typeof g==typeof f)&&(i.bind&&u?v=qu(f,Ii):i.wrap&&u?v=ju(f):a&&Hu(f)?v=Uu(f):v=f,(i.sham||f&&f.sham||g&&g.sham)&&Gt(v,"sham",!0),Gt(o,h,v),a&&(c=t+"Prototype",Ba(Ht,c)||Gt(Ht,c,{}),Gt(Ht[c],h,f),i.real&&l&&(d||!l[h])&&Gt(l,h,f)))},wr=Dt,zu=nt,uo=Function.prototype,Wu=wr&&Object.getOwnPropertyDescriptor,zr=zu(uo,"name"),Qu=zr&&function(){}.name==="something",Ku=zr&&(!wr||wr&&Wu(uo,"name").configurable),Ju={EXISTS:zr,PROPER:Qu,CONFIGURABLE:Ku},co={},Xu=Math.ceil,Zu=Math.floor,ec=Math.trunc||function(e){var t=+e;return(t>0?Zu:Xu)(t)},tc=ec,Wr=function(i){var e=+i;return e!==e||e===0?0:tc(e)},ic=Wr,sc=Math.max,rc=Math.min,ac=function(i,e){var t=ic(i);return t<0?sc(t+e,0):rc(t,e)},nc=Wr,oc=Math.min,dc=function(i){return i>0?oc(nc(i),9007199254740991):0},lc=dc,Qr=function(i){return lc(i.length)},uc=Si,cc=ac,hc=Qr,Na=function(i){return function(e,t,s){var r=uc(e),a=hc(r),n=cc(s,a),o;if(i&&t!=t){for(;a>n;)if(o=r[n++],o!=o)return!0}else for(;a>n;n++)if((i||n in r)&&r[n]===t)return i||n||0;return!i&&-1}},fc={includes:Na(!0),indexOf:Na(!1)},pc=rt,Ws=nt,mc=Si,vc=fc.indexOf,gc=jr,Fa=pc([].push),Sc=function(i,e){var t=mc(i),s=0,r=[],a;for(a in t)!Ws(gc,a)&&Ws(t,a)&&Fa(r,a);for(;e.length>s;)Ws(t,a=e[s++])&&(~vc(r,a)||Fa(r,a));return r},ho=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],bc=Sc,yc=ho,Tc=Object.keys||function(e){return bc(e,yc)},Ec=Dt,$c=jn,wc=ti,Ac=Rt,kc=Si,Pc=Tc;co.f=Ec&&!$c?Object.defineProperties:function(e,t){Ac(e);for(var s=kc(t),r=Pc(t),a=r.length,n=0,o;a>n;)wc.f(e,o=r[n++],s[o]);return e};var Dc=Vr,Rc=Dc("document","documentElement"),Lc=Rt,Ic=co,Va=ho,xc=jr,_c=Rc,Cc=Yn,Oc=qr,Ua=">",Ha="<",Ar="prototype",kr="script",fo=Oc("IE_PROTO"),Qs=function(){},po=function(i){return Ha+kr+Ua+i+Ha+"/"+kr+Ua},Ga=function(i){i.write(po("")),i.close();var e=i.parentWindow.Object;return i=null,e},Mc=function(){var i=Cc("iframe"),e="java"+kr+":",t;return i.style.display="none",_c.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(po("document.F=Object")),t.close(),t.F},xi,ji=function(){try{xi=new ActiveXObject("htmlfile")}catch(e){}ji=typeof document!="undefined"?document.domain&&xi?Ga(xi):Mc():Ga(xi);for(var i=Va.length;i--;)delete ji[Ar][Va[i]];return ji()};xc[fo]=!0;var mo=Object.create||function(e,t){var s;return e!==null?(Qs[Ar]=Lc(e),s=new Qs,Qs[Ar]=null,s[fo]=e):s=ji(),t===void 0?s:Ic.f(s,t)},Bc=st,Nc=!Bc(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),Fc=nt,Vc=Ie,Uc=hs,Hc=qr,Gc=Nc,Ya=Hc("IE_PROTO"),Pr=Object,Yc=Pr.prototype,vo=Gc?Pr.getPrototypeOf:function(i){var e=Uc(i);if(Fc(e,Ya))return e[Ya];var t=e.constructor;return Vc(t)&&e instanceof t?t.prototype:e instanceof Pr?Yc:null},qc=bi,go=function(i,e,t,s){return s&&s.enumerable?i[e]=t:qc(i,e,t),i},jc=st,zc=Ie,Wc=Pt,Qc=mo,qa=vo,Kc=go,Jc=Ne,Dr=Jc("iterator"),So=!1,et,Ks,Js;[].keys&&(Js=[].keys(),"next"in Js?(Ks=qa(qa(Js)),Ks!==Object.prototype&&(et=Ks)):So=!0);var Xc=!Wc(et)||jc(function(){var i={};return et[Dr].call(i)!==i});Xc?et={}:et=Qc(et);zc(et[Dr])||Kc(et,Dr,function(){return this});var bo={IteratorPrototype:et,BUGGY_SAFARI_ITERATORS:So},Zc=Ne,eh=Zc("toStringTag"),yo={};yo[eh]="z";var Kr=String(yo)==="[object z]",th=Kr,ih=Ie,zi=ls,sh=Ne,rh=sh("toStringTag"),ah=Object,nh=zi(function(){return arguments}())=="Arguments",oh=function(i,e){try{return i[e]}catch(t){}},ms=th?zi:function(i){var e,t,s;return i===void 0?"Undefined":i===null?"Null":typeof(t=oh(e=ah(i),rh))=="string"?t:nh?zi(e):(s=zi(e))=="Object"&&ih(e.callee)?"Arguments":s},dh=Kr,lh=ms,uh=dh?{}.toString:function(){return"[object "+lh(this)+"]"},ch=Kr,hh=ti.f,fh=bi,ph=nt,mh=uh,vh=Ne,ja=vh("toStringTag"),To=function(i,e,t,s){if(i){var r=t?i:i.prototype;ph(r,ja)||hh(r,ja,{configurable:!0,value:e}),s&&!ch&&fh(r,"toString",mh)}},gh=bo.IteratorPrototype,Sh=mo,bh=fs,yh=To,Th=ei,Eh=function(){return this},$h=function(i,e,t,s){var r=e+" Iterator";return i.prototype=Sh(gh,{next:bh(+!s,t)}),yh(i,r,!1,!0),Th[r]=Eh,i},wh=ps,Ah=at,Eo=Ju,kh=$h,Ph=vo,Dh=To,za=go,Rh=Ne,Wa=ei,$o=bo,Lh=Eo.PROPER;Eo.CONFIGURABLE;$o.IteratorPrototype;var _i=$o.BUGGY_SAFARI_ITERATORS,Xs=Rh("iterator"),Qa="keys",Ci="values",Ka="entries",Ih=function(){return this},xh=function(i,e,t,s,r,a,n){kh(t,e,s);var o=function(S){if(S===r&&h)return h;if(!_i&&S in u)return u[S];switch(S){case Qa:return function(){return new t(this,S)};case Ci:return function(){return new t(this,S)};case Ka:return function(){return new t(this,S)}}return function(){return new t(this)}},l=e+" Iterator",d=!1,u=i.prototype,c=u[Xs]||u["@@iterator"]||r&&u[r],h=!_i&&c||o(r),f=e=="Array"&&u.entries||c,g,m,v;if(f&&(g=Ph(f.call(new i)),g!==Object.prototype&&g.next&&(Dh(g,l,!0,!0),Wa[l]=Ih)),Lh&&r==Ci&&c&&c.name!==Ci&&(d=!0,h=function(){return Ah(c,this)}),r)if(m={values:o(Ci),keys:a?h:o(Qa),entries:o(Ka)},n)for(v in m)(_i||d||!(v in u))&&za(u,v,m[v]);else wh({target:e,proto:!0,forced:_i||d},m);return n&&u[Xs]!==h&&za(u,Xs,h,{name:r}),Wa[e]=h,m},_h=function(i,e){return{value:i,done:e}},Ch=Si,Ja=ei,wo=mu;ti.f;var Oh=xh,Oi=_h,Ao="Array Iterator",Mh=wo.set,Bh=wo.getterFor(Ao);Oh(Array,"Array",function(i,e){Mh(this,{type:Ao,target:Ch(i),index:0,kind:e})},function(){var i=Bh(this),e=i.target,t=i.kind,s=i.index++;return!e||s>=e.length?(i.target=void 0,Oi(void 0,!0)):t=="keys"?Oi(s,!1):t=="values"?Oi(e[s],!1):Oi([s,e[s]],!1)},"values");Ja.Arguments=Ja.Array;var Nh=Ne,Fh=ei,Vh=Nh("iterator"),Uh=Array.prototype,Hh=function(i){return i!==void 0&&(Fh.Array===i||Uh[Vh]===i)},Gh=ms,Xa=cs,Yh=us,qh=ei,jh=Ne,zh=jh("iterator"),ko=function(i){if(!Yh(i))return Xa(i,zh)||Xa(i,"@@iterator")||qh[Gh(i)]},Wh=at,Qh=Gr,Kh=Rt,Jh=Hr,Xh=ko,Zh=TypeError,ef=function(i,e){var t=arguments.length<2?Xh(i):e;if(Qh(t))return Kh(Wh(t,i));throw Zh(Jh(i)+" is not iterable")},tf=at,Za=Rt,sf=cs,rf=function(i,e,t){var s,r;Za(i);try{if(s=sf(i,"return"),!s){if(e==="throw")throw t;return t}s=tf(s,i)}catch(a){r=!0,s=a}if(e==="throw")throw t;if(r)throw s;return Za(s),t},af=lo,nf=at,of=Rt,df=Hr,lf=Hh,uf=Qr,en=Ur,cf=ef,hf=ko,tn=rf,ff=TypeError,Wi=function(i,e){this.stopped=i,this.result=e},sn=Wi.prototype,pf=function(i,e,t){var s=t&&t.that,r=!!(t&&t.AS_ENTRIES),a=!!(t&&t.IS_RECORD),n=!!(t&&t.IS_ITERATOR),o=!!(t&&t.INTERRUPTED),l=af(e,s),d,u,c,h,f,g,m,v=function(E){return d&&tn(d,"normal",E),new Wi(!0,E)},S=function(E){return r?(of(E),o?l(E[0],E[1],v):l(E[0],E[1])):o?l(E,v):l(E)};if(a)d=i.iterator;else if(n)d=i;else{if(u=hf(i),!u)throw ff(df(i)+" is not iterable");if(lf(u)){for(c=0,h=uf(i);h>c;c++)if(f=S(i[c]),f&&en(sn,f))return f;return new Wi(!1)}d=cf(i,u)}for(g=a?i.next:d.next;!(m=nf(g,d)).done;){try{f=S(m.value)}catch(E){tn(d,"throw",E)}if(typeof f=="object"&&f&&en(sn,f))return f}return new Wi(!1)},mf=Yr,vf=ti,gf=fs,Sf=function(i,e,t){var s=mf(e);s in i?vf.f(i,s,gf(0,t)):i[s]=t},bf=ps,yf=pf,Tf=Sf;bf({target:"Object",stat:!0},{fromEntries:function(e){var t={};return yf(e,function(s,r){Tf(t,s,r)},{AS_ENTRIES:!0}),t}});var Ef=Fr,$f=Ef.Object.fromEntries,wf={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},Af=wf,kf=Be,Pf=ms,Df=bi,rn=ei,Rf=Ne,an=Rf("toStringTag");for(var Zs in Af){var nn=kf[Zs],er=nn&&nn.prototype;er&&Pf(er)!==an&&Df(er,an,Zs),rn[Zs]=rn.Array}var Lf=$f,If=Lf,xf=If,_f=xf,is=Br(_f),pe;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",i[i.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(pe||(pe={}));var Me=(i,e=0,t=pe.OFFSET_P)=>{switch(t){case pe.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case pe.PLAYBACK_SHIFT:{if(e===0)return i;const s=new URL(i);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}case pe.DASH_CMAF_OFFSET_P:{const s=new URL(i);return!s.searchParams.get("offset_p")&&e===0?i:(s.searchParams.set("offset_p",e.toFixed(0)),s.toString())}default:H(t)}return i};const on=(i,e)=>{var t;switch(e){case pe.OFFSET_P:return NaN;case pe.PLAYBACK_SHIFT:{const s=new URL(i);return Number(s.searchParams.get("playback_shift"))}case pe.DASH_CMAF_OFFSET_P:{const s=new URL(i);return Number((t=s.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:H(e)}};var O=(i,e,t=!1)=>{const s=i.getTransition();(t||!s||s.to===e)&&i.setState(e)};class le{constructor(e){this.transitionStarted$=new x,this.transitionEnded$=new x,this.transitionUpdated$=new x,this.forceChanged$=new x,this.stateChangeStarted$=N(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=N(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,s=this.state;this.transition=void 0,this.prevState=s,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:s,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,s=this.state;s===e||k(t)&&t.to===e||(this.prevState=s,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const Cf=i=>{switch(i){case y.MPEG: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 H(i)}};var F;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(F||(F={}));const Of=5,Mf=5,Bf=500,dn=7e3;class Nf{constructor(e){this.subscription=new ie,this.loadMediaTimeoutSubscription=new ie,this.videoState=new le(F.STOPPED),this.syncPlayback=()=>{const s=this.videoState.getState(),r=this.videoState.getTransition(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${s}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${a}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(o)};`}),a===p.STOPPED){s!==F.STOPPED&&(this.videoState.startTransitionTo(F.STOPPED),this.stop());return}if(!r){if((n==null?void 0:n.to)!==p.PAUSED&&o.state===Y.Requested&&s!==F.STOPPED){this.seek(o.position/1e3);return}switch(a){case p.READY:{switch(s){case F.PLAYING:case F.PAUSED:case F.READY:break;case F.STOPPED:this.videoState.startTransitionTo(F.READY),this.prepare();break;default:H(s)}break}case p.PLAYING:{switch(s){case F.PLAYING:break;case F.PAUSED:this.videoState.startTransitionTo(F.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case F.READY:this.videoState.startTransitionTo(F.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case F.STOPPED:this.videoState.startTransitionTo(F.READY),this.prepare();break;default:H(s)}break}case p.PAUSED:{switch(s){case F.PLAYING:this.videoState.startTransitionTo(F.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case F.PAUSED:break;case F.READY:this.videoState.startTransitionTo(F.PAUSED),this.videoState.setState(F.PAUSED);break;case F.STOPPED:this.videoState.startTransitionTo(F.READY),this.prepare();break;default:H(s)}break}default:H(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 ie;this.subscription.add(e),this.subscription.add(N(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 x;e.add(r.pipe(ze(Bf)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let a=NaN;e.add(C(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===Y.Applying||Math.abs(o-a)>Of)&&r.next(o),a=o})),e.add(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(n=>{this.logRemoteEvent(n),this.params.output.duration$.next(n.value)}))}t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(C(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(),l=n===chrome.cast.media.PlayerState.BUFFERING;switch(o!==l&&this.params.output.isBuffering$.next(l),n){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&a.duration-a.currentTime<Mf&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),O(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:H(n)}}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(C(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const s=N(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Le(["init"])).pipe(ze(0));t(s,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(F.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):(this.videoState.setState(F.PLAYING),O(this.params.desiredState.playbackState,p.PLAYING));const s=this.params.output.isLive$.getValue();this.params.output.duration$.next(s?0:t.duration),this.params.output.position$.next(s?0:t.currentTime),this.params.desiredState.seekState.setState({state:Y.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),s=this.createLoadRequest(t);this.loadMedia(s)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===F.PAUSED||e===F.PLAYING)&&(this.videoState.setState(F.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===F.PLAYING||e===F.PAUSED)&&(this.videoState.setState(F.PLAYING),O(this.params.desiredState.playbackState,p.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===F.READY&&this.videoState.setState(F.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===p.READY&&O(this.params.desiredState.playbackState,p.READY)}handleRemoteStop(){this.videoState.getState()!==F.STOPPED&&this.videoState.setState(F.STOPPED)}handleRemoteVolumeChange(e){var t,s;const r=this.params.output.volume$.getValue(),a={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(s=e.muted)!==null&&s!==void 0?s:r.muted};(a.volume!==r.volume||a.muted!==a.muted)&&this.params.output.volume$.next(a)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:s}=this.params.connection;t.currentTime=e,s.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const s=this.params.source;let r,a,n;switch(e){case y.MPEG:{const u=s[e];D(u);const c=cd(Object.keys(u));D(c);const h=u[c];D(h),r=h,a="video/mp4",n=chrome.cast.media.StreamType.BUFFERED;break}case y.HLS:case y.HLS_ONDEMAND:{const u=s[e];D(u),r=u.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 u=s[e];D(u),r=u.url,a="application/dash+xml",n=chrome.cast.media.StreamType.BUFFERED;break}case y.DASH_LIVE_CMAF:{const u=s[e];D(u),r=u.url,a="application/dash+xml",n=chrome.cast.media.StreamType.LIVE;break}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const u=s[e];D(u),r=Me(u.url),a="application/x-mpegurl",n=chrome.cast.media.StreamType.LIVE;break}case y.DASH_LIVE:case y.WEB_RTC_LIVE:{const u="Unsupported format for Chromecast",c=new Error(u);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:I.VIDEO_PIPELINE,message:u,thrown:c}),c}case y.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return H(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:l,subtitle:d}=this.params.meta;return k(l)&&(o.metadata.title=l),k(d)&&(o.metadata.subtitle=d),o}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const s=this.params.desiredState.seekState.getState();return s.state===Y.Applying||s.state===Y.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:s.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),s=new Promise((r,a)=>{this.loadMediaTimeoutSubscription.add(hd(dn).subscribe(()=>a(`timeout(${dn})`)))});Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===Y.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:I.VIDEO_PIPELINE,message:a,thrown:r})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}const Jr=i=>{i.removeAttribute("src"),i.load()},Ff=i=>{try{i.pause(),i.playbackRate=0,Jr(i),i.remove()}catch(e){console.error(e)}};class Vf{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 Rr=window.WeakMap?new WeakMap:new Vf,Lt=i=>{let e=i.querySelector("video");const t=!!e;return e?Jr(e):(e=document.createElement("video"),i.appendChild(e)),Rr.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},It=i=>{const e=Rr.get(i);Rr.delete(i),e?Jr(i):Ff(i)},Xe=(i,e,t,{equal:s=(n,o)=>n===o,changed$:r,onError:a}={})=>{const n=i.getState(),o=e(),l=Q(r),d=new ie;return r&&d.add(r.subscribe(u=>{const c=i.getState();s(u,c)&&i.setState(u)},a)),s(o,n)||(t(n),l&&i.setState(n)),d.add(i.stateChangeStarted$.subscribe(u=>{t(u.to),l&&i.setState(u.to)},a)),d},Ti=(i,e,t)=>Xe(e,()=>i.loop,s=>{k(s)&&(i.loop=s)},{onError:t}),xt=(i,e,t,s)=>Xe(e,()=>({muted:i.muted,volume:i.volume}),r=>{k(r)&&(i.muted=r.muted,i.volume=r.volume)},{equal:(r,a)=>r===a||(r==null?void 0:r.muted)===(a==null?void 0:a.muted)&&(r==null?void 0:r.volume)===(a==null?void 0:a.volume),changed$:t,onError:s}),ii=(i,e,t,s)=>Xe(e,()=>i.playbackRate,r=>{k(r)&&(i.playbackRate=r)},{changed$:t,onError:s}),Uf=i=>["__",i.language,i.label].join("|"),Hf=(i,e)=>{if(i.id===e)return!0;const[t,s,r]=e.split("|");return i.language===s&&i.label===r};class ft{constructor(){this.available$=new x,this.current$=new b(void 0),this.error$=new x,this.subscription=new ie,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=a=>{this.error$.next({id:"TextTracksManager",category:I.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:a})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(Xe(t.internalTextTracks,()=>Object.values(this.internalTracks),a=>{k(a)&&this.setInternal(a)},{equal:(a,n)=>k(a)&&k(n)&&a.length===n.length&&a.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe(w(a=>a.filter(({type:n})=>n==="internal"))),onError:r})),this.subscription.add(Xe(t.externalTextTracks,()=>Object.values(this.externalTracks),a=>{k(a)&&this.setExternal(a)},{equal:(a,n)=>k(a)&&k(n)&&a.length===n.length&&a.every(({id:o},l)=>o===n[l].id),changed$:this.available$.pipe(w(a=>a.filter(({type:n})=>n==="external"))),onError:r})),this.subscription.add(Xe(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(Xe(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const a of this.htmlTextTracksAsArray())this.applyCueSettings(a.cues),this.applyCueSettings(a.activeCues)}))}subscribe(){D(this.video);const{textTracks:e}=this.video;this.subscription.add(C(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();s&&this.select(s)})),this.subscription.add(N(C(e,"addtrack"),C(e,"removetrack"),Le(["init"])).pipe(w(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),ce((s,r)=>s.length===r.length&&s.every(({id:a},n)=>a===r[n].id))).subscribe(this.available$)),this.subscription.add(N(C(e,"change"),Le(["init"])).pipe(w(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),w(s=>s&&this.htmlTextTrackToITextTrack(s).id),ce()).subscribe(this.current$));const t=s=>{var r,a;return this.applyCueSettings((a=(r=s.target)===null||r===void 0?void 0:r.activeCues)!==null&&a!==void 0?a:null)};this.subscription.add(C(e,"addtrack").subscribe(s=>{var r,a;(r=s.track)===null||r===void 0||r.addEventListener("cuechange",t);const n=o=>{var l,d,u,c,h;const f=(d=(l=o.target)===null||l===void 0?void 0:l.cues)!==null&&d!==void 0?d:null;f&&f.length&&(this.applyCueSettings((c=(u=o.target)===null||u===void 0?void 0:u.cues)!==null&&c!==void 0?c:null),(h=o.target)===null||h===void 0||h.removeEventListener("cuechange",n))};(a=s.track)===null||a===void 0||a.addEventListener("cuechange",n)})),this.subscription.add(C(e,"removetrack").subscribe(s=>{var r;(r=s.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const s of Array.from(e)){const r=s;k(t.align)&&(r.align=t.align),k(t.position)&&(r.position=t.position),k(t.size)&&(r.size=t.size),k(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){D(this.video);const t=[...this.video.textTracks];return e?t:t.filter(ft.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,s;const{language:r,label:a}=e,n=e.id?e.id:Uf(e),o=this.externalTracks.has(n),l=n.includes("auto");return o?{id:n,type:"external",isAuto:l,language:r,label:a,url:(t=this.externalTracks.get(n))===null||t===void 0?void 0:t.url}:{id:n,type:"internal",isAuto:l,language:r,label:a,url:(s=this.internalTracks.get(n))===null||s===void 0?void 0:s.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(s=>s.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:s,language:r,isAuto:a})=>!this.internalTracks.has(s)&&!t.some(([,n])=>n.language===r&&n.isAuto===a)).forEach(s=>this.attach(s)),Array.from(this.internalTracks).filter(([s])=>!e.find(r=>r.id===s)).forEach(([,s])=>this.detach(s))}select(e){D(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(Q(e)||!Hf(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){D(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){D(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),s=>s.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)}}class Xr{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=i=>{var e;let t=i;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},ln=i=>{const e=Po(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Gf=i=>{const e=Po(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)},Yf=3;var qf=(i,e,t=Yf)=>{let s=0,r=0;for(let a=0;a<i.length;a++){const n=i.start(a),o=i.end(a);if(n<=e&&e<=o){if(s=n,r=o,!t)return{from:s,to:r};for(let l=a-1;l>=0;l--)i.end(l)+t>=s&&(s=i.start(l));for(let l=a+1;l<i.length;l++)i.start(l)-t<=r&&(r=i.end(l))}}return{from:s,to:r}};const _t=i=>{const e=$=>C(i,$).pipe(Ki(void 0)),s=N(...["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"].map($=>C(i,$))).pipe(w($=>$.type==="ended"?i.readyState<2:i.readyState<3),ce()),r=N(C(i,"progress"),C(i,"timeupdate")).pipe(w(()=>qf(i.buffered,i.currentTime))),n=Mr().browser===Bn.Safari?We({play:e("play").pipe(Ee()),playing:e("playing")}).pipe(Ki(void 0)):e("playing"),o=C(i,"volumechange").pipe(w(()=>({muted:i.muted,volume:i.volume}))),l=C(i,"ratechange").pipe(w(()=>i.playbackRate)),d=C(i,"error").pipe(ue(()=>!!(i.error||i.played.length)),w(()=>{var $;const A=i.error;return{id:A?`MediaError#${A.code}`:"HtmlVideoError",category:I.VIDEO_PIPELINE,message:A?A.message:"Error event from HTML video element",thrown:($=i.error)!==null&&$!==void 0?$:void 0}})),u=C(i,"timeupdate").pipe(w(()=>i.currentTime)),c=new x,h=.3;let f;u.subscribe($=>{i.loop&&k(f)&&k($)&&f>=i.duration-h&&$<=h&&c.next(f),f=$});const g=C(i,"enterpictureinpicture"),m=C(i,"leavepictureinpicture"),v=new b(Gf(i));g.subscribe(()=>v.next(!0)),m.subscribe(()=>v.next(!1));const S=new b(ln(i));return C(i,"fullscreenchange").pipe(w(()=>ln(i))).subscribe(S),{playing$:n,pause$:e("pause").pipe(ue(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:c,error$:d,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:u,durationChange$:C(i,"durationchange").pipe(w(()=>i.duration)),isBuffering$:s,currentBuffer$:r,volumeState$:o,playbackRateState$:l,inPiP$:v,inFullscreen$:S}};var vs=i=>{switch(i){case"mobile":return Ae.Q_144P;case"lowest":return Ae.Q_240P;case"low":return Ae.Q_360P;case"sd":case"medium":return Ae.Q_480P;case"hd":case"high":return Ae.Q_720P;case"fullhd":case"full":return Ae.Q_1080P;case"quadhd":case"quad":return Ae.Q_1440P;case"ultrahd":case"ultra":return Ae.Q_2160P}},jf=ps,zf=hs,Wf=Qr,Qf=Wr;jf({target:"Array",proto:!0},{at:function(e){var t=zf(this),s=Wf(t),r=Qf(e),a=r>=0?r:s+r;return a<0||a>=s?void 0:t[a]}});var Kf=Vr,Do=Kf,Jf=Do,Xf=Jf("Array","at"),Zf=Xf,ep=Zf,tp=ep,ip=tp,Je=Br(ip);let Zr=!1,Ze={};const sp=i=>{Zr=i},rp=()=>{Ze={}},ap=i=>{i(Ze)},Mi=(i,e)=>{var t;Zr&&(Ze.meta=(t=Ze.meta)!==null&&t!==void 0?t:{},Ze.meta[i]=e)};class Ye{constructor(e){this.name=e}next(e){var t,s;if(!Zr)return;Ze.series=(t=Ze.series)!==null&&t!==void 0?t:{};const r=(s=Ze.series[this.name])!==null&&s!==void 0?s:[];r.push([Date.now(),e]),Ze.series[this.name]=r}}var $t;(function(i){i.FitsContainer="FitsContainer",i.FitsThroughput="FitsThroughput",i.Buffer="Buffer",i.DroppedFramesLimit="DroppedFramesLimit",i.FitsQualityLimits="FitsQualityLimits"})($t||($t={}));const np=new Ye("best_bitrate"),op=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class dp{constructor(){this.history={}}recordSelection(e){this.history[e.id]=ne()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const lp='Assertion "ABR Tracks is empty array" failed',gs=(i,{container:e,throughput:t,tuning:s,limits:r,reserve:a=0,forwardBufferHealth:n,playbackRate:o,current:l,history:d,droppedVideoMaxQualityLimit:u,abrLogger:c})=>{var h,f,g,m,v;fd(i,lp);const S=s.usePixelRatio&&(h=window.devicePixelRatio)!==null&&h!==void 0?h:1,E=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*S*s.containerSizeFactor,height:e.height*S*s.containerSizeFactor},$=E&&At(E),A=s.considerPlaybackRate&&k(o)?o:1,P=i.filter(B=>!kt(B.quality)).sort((B,L)=>Kt(B.quality,L.quality)?-1:1),q=(f=Je(P,-1))===null||f===void 0?void 0:f.quality,j=(g=Je(P,0))===null||g===void 0?void 0:g.quality,K=Q(r)||k(r.min)&&k(r.max)&&Yi(r.max,r.min)||k(r.min)&&j&&Kt(r.min,j)||k(r.max)&&q&&Yi(r.max,q),G=A*op(n!=null?n:.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),J={},M=P.filter(B=>($?Yi(B.quality,$):!0)?(k(t)&&isFinite(t)&&k(B.bitrate)?t-a>=B.bitrate*G:!0)?s.lazyQualitySwitch&&k(s.minBufferToSwitchUp)&&l&&!kt(l.quality)&&(n!=null?n:0)<s.minBufferToSwitchUp&&Kt(B.quality,l.quality)?(J[B.quality]=$t.Buffer,!1):!!u&&Sr(B.quality,u)?(J[B.quality]=$t.DroppedFramesLimit,!1):K||(Q(r.max)||Ji(B.quality,r.max))&&(Q(r.min)||Sr(B.quality,r.min))?!0:(J[B.quality]=$t.FitsQualityLimits,!1):(J[B.quality]=$t.FitsThroughput,!1):(J[B.quality]=$t.FitsContainer,!1))[0];M&&M.bitrate&&np.next(M.bitrate);const _=(m=M!=null?M:P[Math.ceil((P.length-1)/2)])!==null&&m!==void 0?m:i[0];_.quality!==((v=d==null?void 0:d.last)===null||v===void 0?void 0:v.quality)&&c({message:`
|
|
7
7
|
[available tracks]
|
|
8
8
|
${i.map(B=>`{ id: ${B.id}, quality: ${B.quality}, bitrate: ${B.bitrate} }`).join(`
|
|
9
9
|
`)}
|
|
@@ -13,13 +13,13 @@ import{ValueSubject as b,Subject as x,Subscription as ie,isNonNullable as P,Erro
|
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[limit params]
|
|
16
|
-
containerQualityLimit: ${
|
|
16
|
+
containerQualityLimit: ${$},
|
|
17
17
|
throughput: ${t},
|
|
18
18
|
reserve: ${a},
|
|
19
19
|
playbackRate: ${o},
|
|
20
|
-
playbackRateFactor: ${
|
|
20
|
+
playbackRateFactor: ${A},
|
|
21
21
|
forwardBufferHealth: ${n},
|
|
22
|
-
bitrateFactor: ${
|
|
22
|
+
bitrateFactor: ${G},
|
|
23
23
|
minBufferToSwitchUp: ${s.minBufferToSwitchUp},
|
|
24
24
|
droppedVideoMaxQualityLimit: ${u},
|
|
25
25
|
limitsAreInvalid: ${K},
|
|
@@ -34,7 +34,7 @@ import{ValueSubject as b,Subject as x,Subscription as ie,isNonNullable as P,Erro
|
|
|
34
34
|
[selected track] ${_==null?void 0:_.quality}
|
|
35
35
|
`});const se=_&&d&&d.history[_.id]&&ne()-d.history[_.id]<=s.trackCooldown&&(!d.last||_.id!==d.last.id);if(_!=null&&_.id&&d&&!se&&d.recordSelection(_),se&&(d!=null&&d.last)){const B=d.last;return d==null||d.recordSwitch(B),c({message:`
|
|
36
36
|
[last selected] ${B==null?void 0:B.quality}
|
|
37
|
-
`}),B}return d==null||d.recordSwitch(_),_};var Qe=i=>new URL(i).hostname;const un=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))};var _t=async i=>{const e=i.muted;try{await i.play()}catch(t){if(!un(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(s){return un(s)&&(i.muted=!1,console.warn(s)),!1}}return!0};function ye(){return ne()}function Ro(i){return ye()-i}function cn(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),s=/^([a-z]+:)?\/\//i,r=n=>s.test(n);return{resolve:(n,o,l=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let d=n.indexOf("?")>-1?"&":"?";return l&&(n+=d+"lowLat=1",d="&"),o&&(n+=d+"_rnd="+Math.floor(999999999*Math.random())),n}}}function up(i,e,t){const s=(...r)=>{t.apply(null,r),i.removeEventListener(e,s)};i.addEventListener(e,s)}function Qi(i,e,t,s){const r=window.XMLHttpRequest;let a,n,o,l=!1,d=0,u,c,h=!1,f="arraybuffer",g=7e3,m=2e3,v=()=>{if(l)return;D(u);const M=Ro(u);let _;if(M<m){_=m-M,setTimeout(v,_);return}m*=2,m>g&&(m=g),n&&n.abort(),n=new r,H()};const S=M=>(a=M,Z),E=M=>(c=M,Z),w=()=>(f="json",Z),$=()=>{if(!l){if(--d>=0){v(),s&&s();return}l=!0,c&&c(),t&&t()}},k=M=>(h=M,Z),H=()=>{u=ye(),n=new r,n.open("get",i);let M=0,_,se=0;const B=()=>(D(u),Math.max(u,Math.max(_||0,se||0)));if(a&&n.addEventListener("progress",L=>{const X=ye();a.updateChunk&&L.loaded>M&&(a.updateChunk(B(),L.loaded-M),M=L.loaded,_=X)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>$())),n.addEventListener("load",()=>{if(l)return;D(n);const L=n.status;if(L>=200&&L<300){if(n.response.byteLength&&a){const X=n.response.byteLength-M;X&&a.updateChunk&&a.updateChunk(B(),X)}n.responseType==="json"&&!Object.values(n.response).length?$():(c&&c(),e(n.response))}else $()}),n.addEventListener("error",()=>{$()}),h){const L=()=>{D(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(se=ye(),n.removeEventListener("readystatechange",L))};n.addEventListener("readystatechange",L)}return n.responseType=f,n.send(),Z},Z={withBitrateReporting:S,withParallel:k,withJSONResponse:w,withRetryCount:M=>(d=M,Z),withRetryInterval:(M,_)=>(P(M)&&(m=M),P(_)&&(g=_),Z),withTimeout:M=>(o=M,Z),withFinally:E,send:H,abort:()=>{n&&(n.abort(),n=void 0),l=!0,c&&c()}};return Z}const cp=100,hp=2e3,fp=500;let pp=class{constructor(e){this.intervals=[],this.currentRate=0,this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,s){return{start:e,end:t,bytes:s}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-fp;if(t-e>hp){let s=0,r=0;for(;this.intervals.length>0;){const a=this.intervals[0];if(a.end<=t)s+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{const n=t-a.start,o=a.end-a.start;s+=n;const l=a.bytes*n/o;r+=l,a.start=t,a.bytes-=l}}}if(r>0&&s>0){const a=r*8/(s/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(s)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,s){return this.intervals.push(this._createInterval(e,t,s)),this._joinIntervals(),this.intervals.length>cp&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};class mp{constructor(e,t,s,r,a){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const s=ye(),r=l=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=l,e._errorCB?e._errorCB(l):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=l=>{e._complete=1,e._responseData=l,e._downloadTime=ye()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(l,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Qi(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ye()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=ye();if(Object.keys(this.activeRequests).length>=e)return!1;const s=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),s>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),s),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,s,r){const a={};return a.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=s,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),s(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=s,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Bi=1e4,tr=3,vp=6e4,gp=10,Sp=1,bp=500;class yp{constructor(e){this.paused=!1,this.autoQuality=!0,this.maxAutoQuality=void 0,this.buffering=!0,this.destroyed=!1,this.videoPlayStarted=!1,this.lowLatency=!1,this.bitrate=0,this.manifest=[],this.sourceBuffer=0,this.bufferStates=[],this.sourceJitter=-1,this.params=e,this.chunkRateEstimator=new pp(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=cn(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let s=0;s<this.manifest.length;++s)if(t=this.manifest[s],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=cn(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const s=e.buffered.length;return s!==0&&(t=e.buffered.end(s-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var s;!!e.error&&!this.destroyed&&(t(`Video element error: ${(s=e.error)===null||s===void 0?void 0:s.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const s=this._getBufferSizeSec();!this.paused&&s<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(s+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,s=t.buffered.length;let r;s!==0&&(r=t.buffered.start(s-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let s,r,a;const n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!s||s.bitrate>a.bitrate)&&(s=a));return r||s}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||P(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:s,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,s("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const n=()=>{up(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),a({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new mp(tr,Bi,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:s,playerCallback:r}=this.params;let a=!1,n=null,o=null,l=null,d=null,u=!1;const c=()=>{const $=a&&(!u||u===this.rep);return $||t("Not running!"),$},h=($,k,H)=>{l&&l.abort(),l=Qi(this.urlResolver.resolve($,!1),k,H,()=>this._retryCallback()).withTimeout(Bi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(tr).withFinally(()=>{l=null}).send()},f=($,k,H)=>{D(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve($,!1),k,H,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},g=$=>{const k=s.playbackRate;s.playbackRate!==$&&(t(`Playback rate switch: ${k}=>${$}`),s.playbackRate=$)},m=$=>{this.lowLatency=$,t(`lowLatency changed to ${$}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)g(1);else{let $=this._getBufferSizeSec();if(this.bufferStates.length<5){g(1);return}const H=ye()-1e4;let Y=0;for(let j=0;j<this.bufferStates.length;j++){const J=this.bufferStates[j];$=Math.min($,J.buf),J.ts<H&&Y++}this.bufferStates.splice(0,Y),t(`update playback rate; minBuffer=${$} drop=${Y} jitter=${this.sourceJitter}`);let K=$-Sp;this.sourceJitter>=0?K-=this.sourceJitter/2:this.sourceJitter-=1,K>3?g(1.15):K>1?g(1.1):K>.3?g(1.05):g(1)}},S=$=>{let k;const H=()=>k&&k.start?k.start.length:0,Y=L=>k.start[L]/1e3,K=L=>k.dur[L]/1e3,j=L=>k.fragIndex+L,J=(L,X)=>({chunkIdx:j(L),startTS:Y(L),dur:K(L),discontinuity:X}),Z=()=>{let L=0;if(k&&k.dur){let X=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,oe=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,he=X;this.sourceJitter>1&&(he+=this.sourceJitter-1);let me=k.dur.length-1;for(;me>=0&&(he-=k.dur[me],!(he<=0));--me);L=Math.min(me,k.dur.length-1-oe),L=Math.max(L,0)}return J(L,!0)},M=L=>{const X=H();if(!(X<=0)){if(P(L)){for(let oe=0;oe<X;oe++)if(Y(oe)>L)return J(oe)}return Z()}},_=L=>{const X=H(),oe=L?L.chunkIdx+1:0,he=oe-k.fragIndex;if(!(X<=0)){if(!L||he<0||he-X>gp)return t(`Resync: offset=${he} bChunks=${X} chunk=`+JSON.stringify(L)),Z();if(!(he>=X))return J(oe-k.fragIndex,!1)}},se=(L,X,oe)=>{d&&d.abort(),d=Qi(this.urlResolver.resolve(L,!0,this.lowLatency),X,oe,()=>this._retryCallback()).withTimeout(Bi).withRetryCount(tr).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(L,X)=>{se($,oe=>{if(!c())return;k=oe;const he=!!k.lowLatency;he!==this.lowLatency&&m(he);let me=0;for(let Fe=0;Fe<k.dur.length;++Fe)me+=k.dur[Fe];me>0&&(D(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(me/k.dur.length)),r({name:"index",zeroTime:k.zeroTime,shiftDuration:k.shiftDuration}),this.sourceJitter=k.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,k.jitter/1e3)):1,L(M(X))},()=>this._handleNetworkError())},nextChunk:_}},E=()=>{a=!1,o&&o.abort(),l&&l.abort(),d&&d.abort(),D(this.filesFetcher),this.filesFetcher.abortAll()};return u={start:$=>{const{videoElement:k,logger:H}=this.params;let Y=S(e.jidxUrl),K,j,J,Z,M=0,_,se,B;const L=()=>{_&&(clearTimeout(_),_=void 0);const W=Math.max(bp,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Se=M+W,Te=ye(),we=Math.min(1e4,Se-Te);M=Te;const Ot=()=>{d||c()&&Y.seek(()=>{c()&&(M=ye(),X(),L())})};we>0?_=window.setTimeout(()=>{this.paused?L():Ot()},we):Ot()},X=()=>{let W;for(;W=Y.nextChunk(Z);)Z=W,ii(W);const Se=Y.nextChunk(J);if(Se){if(J&&Se.discontinuity){H("Detected discontinuity; restarting playback"),this.paused?L():(E(),this._initPlayerWith(e));return}Fe(Se)}else L()},oe=(W,Se)=>{if(!c()||!this.sourceBuffer)return;let Te,we,Ot;const si=Ke=>{window.setTimeout(()=>{c()&&oe(W,Se)},Ke)};if(this.sourceBuffer.updating)H("Source buffer is updating; delaying appendBuffer"),si(100);else{const Ke=ye(),ke=k.currentTime;!this.paused&&k.buffered.length>1&&se===ke&&Ke-B>500&&(H("Stall suspected; trying to fix"),this._fixupStall()),se!==ke&&(se=ke,B=Ke);const Mt=this._getBufferSizeSec();if(Mt>30)H(`Buffered ${Mt} seconds; delaying appendBuffer`),si(2e3);else try{this.sourceBuffer.appendBuffer(W),this.videoPlayStarted?(this.bufferStates.push({ts:Ke,buf:Mt}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Se&&Se()}catch(ri){if(ri.name==="QuotaExceededError")H("QuotaExceededError; delaying appendBuffer"),Ot=this.sourceBuffer.buffered.length,Ot!==0&&(Te=this.sourceBuffer.buffered.start(0),we=ke,we-Te>4&&this.sourceBuffer.remove(Te,we-3)),si(1e3);else throw ri}}},he=()=>{j&&K&&(H([`Appending chunk, sz=${j.byteLength}:`,JSON.stringify(J)]),oe(j,function(){j=null,X()}))},me=W=>e.fragUrlTemplate.replace("%%id%%",W.chunkIdx),Fe=W=>{c()&&f(me(W),(Se,Te)=>{if(c()){if(Te/=1e3,j=Se,J=W,n=W.startTS,Te){const we=Math.min(10,W.dur/Te);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*we:we}he()}},()=>this._handleNetworkError())},ii=W=>{c()&&(D(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(me(W),!1)))},Ct=W=>{c()&&(e.cachedHeader=W,oe(W,()=>{K=!0,he()}))};a=!0,Y.seek(W=>{if(c()){if(M=ye(),!W){L();return}Z=W,!Q($)||W.startTS>$?Fe(W):(J=W,X())}},$),e.cachedHeader?Ct(e.cachedHeader):h(e.headerUrl,Ct,()=>this._handleNetworkError())},stop:E,getTimestampSec:()=>n},u}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),P(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,D(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),s({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return P(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=c=>{if(!this.autoQuality)return;let h,f,g;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(f=this._getBufferSizeSec(),g=c/this.bitrate,f>10&&g>.8||f>15&&g>.5||f>20&&g>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},a=(()=>({updateChunk:(h,f)=>{const g=ye();if(this.chunkRateEstimator.addInterval(h,g,f)){const v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:g-h,speed:v}),!0}},get:()=>{const h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}}))();let n=-1/0,o,l=!0;const d=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(l&&c>o&&Ro(n)<3e4)return;s(c)}l=this.autoQuality};return{updateChunk:(c,h)=>{const f=a.updateChunk(c,h);return f&&d(),f},notifySwitch:c=>{const h=ye();c<o&&(n=h),o=c}}}_fetchManifest(e,t,s){this.manifestRequest=Qi(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(Bi).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;_t(t).then(s=>{s||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,videoElement:r}=this.params,a=n=>{const o=[];return n!=null&&n.length?(n.forEach((l,d)=>{l.video&&r.canPlayType(l.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(l.codecs)&&(l.index=d,o.push(l))}),o.sort(function(l,d){return l.video&&d.video?d.video.height-l.video.height:d.bitrate-l.bitrate}),o):(s({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),s({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},vp))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}class Lo{constructor(){this.onDroopedVideoFramesLimit$=new x,this.subscription=new ie,this.playing=!1,this.tracks=[],this.forceChecker$=new x,this.isForceCheckCounter=0,this.prevTotalVideoFrames=0,this.prevDroppedVideoFrames=0,this.limitCounts={},this.handleChangeVideoQuality=()=>{const e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!At(e.quality)&&this.onChangeQuality(e.quality)},this.checkDroppedFrames=()=>{var e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality(),r=t-this.prevTotalVideoFrames,a=s-this.prevDroppedVideoFrames,n=1-(r-a)/r;!isNaN(n)&&n>0&&this.log({message:`[dropped]. current dropped percent: ${n}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(n)&&n>=this.droppedFramesChecker.percentLimit&&Qt(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((e=this.limitCounts[this.currentQuality])!==null&&e!==void 0?e:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(t,s)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(C(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=Xi(this.droppedFramesChecker.checkTime).pipe(ue(()=>this.playing),ue(()=>{const r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(ze(this.droppedFramesChecker.checkTime)),s=N(e,t);this.subscription.add(s.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,s),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var t,s;const r=(s=(t=Object.entries(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>Yi(a,n)?-1:1))===null||t===void 0?void 0:t[0])===null||s===void 0?void 0:s[0];return e!=null?e:r}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}}var U;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(U||(U={}));const Tp=[U.PAUSED,U.PLAYING,U.READY],Ep=[U.PAUSED,U.PLAYING,U.READY];class $p{constructor(e){this.subscription=new ie,this.videoState=new le(U.STOPPED),this.representations$=new b([]),this.textTracksManager=new ft,this.droppedFramesManager=new Lo,this.maxSeekBackTime$=new b(1/0),this.zeroTime$=new b(void 0),this.liveOffset=new Xr,this._dashCb=r=>{var a,n,o,l;switch(r.name){case"buffering":{const d=r.isBuffering;this.params.output.isBuffering$.next(d);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:I.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const d=r.manifest,u=[];for(const c of d){const h=(a=c.name)!==null&&a!==void 0?a:c.index.toString(10),f=(n=vs(c.name))!==null&&n!==void 0?n:gi(c.video),g=c.bitrate/1e3,m={...c.video};if(!f)continue;const v={id:h,quality:f,bitrate:g,size:m};u.push({track:v,representation:c})}this.representations$.next(u),this.params.output.availableVideoTracks$.next(u.map(({track:c})=>c)),((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===U.MANIFEST_READY&&this.videoState.setState(U.MANIFEST_READY);break}case"qualitySwitch":{const d=r.quality,u=(l=this.representations$.getValue().find(({representation:c})=>c===d))===null||l===void 0?void 0:l.track;this.params.output.hostname$.next(new URL(d.headerUrl,this.params.source.url).hostname),P(u)&&this.params.output.currentVideoTrack$.next(u);break}case"bandwidth":{const{size:d,duration:u}=r;this.params.dependencies.throughputEstimator.addRawSpeed(d,u);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration||0),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{const r=this.videoState.getState(),a=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${r}; videoTransition: ${JSON.stringify(a)}; desiredPlaybackState: ${n}; seekState: ${JSON.stringify(l)};`}),n===p.STOPPED){r!==U.STOPPED&&(this.videoState.startTransitionTo(U.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(U.STOPPED));return}if(a)return;const d=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Ep.includes(r)&&(d||u)){this.prepare();return}if((o==null?void 0:o.to)!==p.PAUSED&&l.state===q.Requested&&Tp.includes(r)){this.seek(l.position-this.liveOffset.getTotalPausedTime());return}switch(r){case U.STOPPED:this.videoState.startTransitionTo(U.MANIFEST_READY),this.dash.attachSource(Me(this.params.source.url));return;case U.MANIFEST_READY:this.videoState.startTransitionTo(U.READY),this.prepare();break;case U.READY:if(n===p.PAUSED)this.videoState.setState(U.PAUSED);else if(n===p.PLAYING){this.videoState.startTransitionTo(U.PLAYING);const c=o==null?void 0:o.from;c&&c===p.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(U.PAUSED)})}return;case U.PLAYING:n===p.PAUSED&&(this.videoState.startTransitionTo(U.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case U.PAUSED:if(n===p.PLAYING)if(this.videoState.startTransitionTo(U.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(U.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.dash.reinit(Me(this.params.source.url,c))}return;default:return G(r)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:I.WTF,message:"DashLiveProvider internal logic error",thrown:r})};N(this.videoState.stateChangeStarted$.pipe(A(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(A(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=Rt(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Qe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=xt(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:s.playing$,pause$:s.pause$,tracks$:this.representations$.pipe(A(r=>r.map(({track:a})=>a)))}),this.subscription.add(s.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===U.READY&&this.videoState.setState(U.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(U.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===q.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(U.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(ce(),A(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(We({zeroTime:this.zeroTime$.pipe(ue(P)),position:s.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Ti(this.video,this.params.desiredState.isLooped,t)).add(It(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(ti(this.video,this.params.desiredState.playbackRate,s.playbackRateState$,t)).add(s.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(s.playing$.subscribe(this.params.output.firstFrameEvent$)).add(s.canplay$.subscribe(this.params.output.canplay$)).add(s.inPiP$.subscribe(this.params.output.inPiP$)).add(s.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{const a=r&&pd(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case U.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(p.STOPPED);break;case U.MANIFEST_READY:case U.READY:((a=this.params.desiredState.playbackState.getTransition())===null||a===void 0?void 0:a.to)===p.READY&&this.params.desiredState.playbackState.setState(p.READY);break;case U.PAUSED:this.params.desiredState.playbackState.setState(p.PAUSED);break;case U.PLAYING:this.params.desiredState.playbackState.setState(p.PLAYING);break;default:return G(r.to)}},t)).add(N(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Le(["init"])).pipe(ze(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Lt(this.video)}createLiveDashPlayer(){const e=new yp({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,s,r,a,n;const o=this.representations$.getValue(),l=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),d=(r=(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||s===void 0?void 0:s.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),u=!d&&P(l)?l:gs(o.map(({track:m})=>m),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),c=u==null?void 0:u.id,h=this.params.desiredState.videoTrack.getTransition(),f=(a=this.params.desiredState.videoTrack.getState())===null||a===void 0?void 0:a.id,g=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&(h||c!==f)&&this.setVideoTrack(u),g&&this.setAutoQuality(d),h||g||c!==f){const m=(n=o.find(({track:v})=>v.id===c))===null||n===void 0?void 0:n.representation;D(m,"Representations missing"),this.dash.startPlay(m,d)}}setVideoTrack(e){var t;const s=(t=this.representations$.getValue().find(({track:r})=>r.id===e.id))===null||t===void 0?void 0:t.representation;D(s,`No such representation ${e.id}`),this.dash.switchByName(s.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),r=t===p.PAUSED&&s===U.PAUSED,a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Me(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}}var ge;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(ge||(ge={}));var Ge;(function(i){i[i.ActiveLowLatency=0]="ActiveLowLatency",i[i.LiveWithTargetOffset=1]="LiveWithTargetOffset",i[i.LiveForwardBuffering=2]="LiveForwardBuffering",i[i.None=3]="None"})(Ge||(Ge={}));var ss;(function(i){i.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",i.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(ss||(ss={}));var Re;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(Re||(Re={}));var V;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(V||(V={}));var Jt;(function(i){i.MP4="mp4",i.WEBM="webm"})(Jt||(Jt={}));var rs;(function(i){i[i.RECTANGULAR=0]="RECTANGULAR",i[i.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",i[i.CUBEMAP=2]="CUBEMAP",i[i.MESH=3]="MESH"})(rs||(rs={}));var ae;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(ae||(ae={}));var zt=(i,e)=>{let t=0;for(let s=0;s<i.length;s++){const r=i.start(s)*1e3,a=i.end(s)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};const wp=300,Ap=(i,e=wp)=>new os(t=>{const{width:s,height:r}=i.getBoundingClientRect();if(t.next({width:s,height:r}),!window.ResizeObserver)return;const a=new ResizeObserver(md(n=>{const o=n[0];if(!o)return;let l,d;o.contentBoxSize&&o.contentBoxSize[0]?(d=o.contentBoxSize[0].blockSize,l=o.contentBoxSize[0].inlineSize):o.contentRect&&(l=o.contentRect.width,d=o.contentRect.height),P(l)&&P(d)&&t.next({width:l,height:d})},e));return a.observe(i),()=>a.disconnect()});class hn{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}removeEventListener(e,t){if(!(e in this.listeners))return;const s=this.listeners[e];for(let r=0,a=s.length;r<a;r++)if(s[r].callback===t){s.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let r=0,a=s.length;r<a;r++){const n=s[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}}class Io extends hn{constructor(){super(),this.listeners||hn.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}let xo=class{constructor(){Object.defineProperty(this,"signal",{value:new Io,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let s=e;if(s===void 0)if(typeof document=="undefined")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch(r){s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(xo.prototype[Symbol.toStringTag]="AbortController",Io.prototype[Symbol.toStringTag]="AbortSignal");function _o(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function kp(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!_o({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(d,u){let c;u&&u.signal&&(c=u.signal,delete u.signal);const h=new t(d,u);return c&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),h},a.prototype=t.prototype);const n=e;return{fetch:(l,d)=>{const u=a&&a.prototype.isPrototypeOf(l)?l.signal:d?d.signal:void 0;if(u){let c;try{c=new DOMException("Aborted","AbortError")}catch(f){c=new Error("Aborted"),c.name="AbortError"}if(u.aborted)return Promise.reject(c);const h=new Promise((f,g)=>{u.addEventListener("abort",()=>g(c),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([h,n(l,d)])}return n(l,d)},Request:a}}const Ss=_o({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Co=Ss?kp({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,mi=Ss?Co.fetch:window.fetch;Ss?Co.Request:window.Request;const Kt=Ss?xo:window.AbortController;var Lr=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};const Pp=(i,e={})=>{const s=e.timeout||1,r=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-r-1>s},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},Dp=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",fn=Dp?Pp:window.requestIdleCallback;var ir,sr;const Rp=16;let Oo=!1;try{Oo=Mr().browser===Bn.Safari&&parseInt((sr=(ir=navigator.userAgent.match(/Version\/(\d+)/))===null||ir===void 0?void 0:ir[1])!==null&&sr!==void 0?sr:"",10)<=Rp}catch(i){console.error(i)}class Lp{constructor(e){this.bufferFull$=new x,this.error$=new x,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const s=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!s),this.currentTask=null}this.queue.length&&this.pull()}catch(s){this.error$.next({id:"BufferTaskQueueUnknown",category:I.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:s})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(s=>{const r={operation:"append",data:e,signal:t,callback:s};this.queue.push(r),this.pull()})}async remove(e,t,s){return s&&s.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:s,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let s;Oo&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);s&&(this.queue=[s]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:s}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&s==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${s}`,category:I.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:G(t)}}}var pn=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};class xe{get id(){return this.type}get size(){return this.size32}constructor(e){this.cursor=0,this.source=e,this.children=[];const t=this.readUint32();this.size32=t<=e.buffer.byteLength?t:NaN,this.type=this.readString(4),this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,e.byteOffset+this.cursor,this.size32?this.size32-8:void 0),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}readString(e,t="ascii"){const r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){const e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){const e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){const e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){const e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}}class Mo extends xe{}class Ip extends xe{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const s=this.readString(4);this.compatibleBrands.push(s),t-=4}}}class xp extends xe{parseChildrenBoxes(){return pt(this.content)}}class _p extends xe{parseChildrenBoxes(){return pt(this.content)}}class Cp extends xe{constructor(e){super(e),this.data=this.content}}class ot extends xe{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class Op extends ot{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let s=this.readUint32();const r=s>>>31,a=s<<1>>>1,n=this.readUint32();s=this.readUint32();const o=s>>>28,l=s<<3>>>3;this.segments.push({referenceType:r,referencedSize:a,subsegmentDuration:n,SAPType:o,SAPDeltaTime:l})}}}class Mp extends xe{parseChildrenBoxes(){return pt(this.content)}}class Bp extends xe{parseChildrenBoxes(){return pt(this.content)}}var wt;(function(i){i[i.MONOSCOPIC=0]="MONOSCOPIC",i[i.TOP_BOTTOM=1]="TOP_BOTTOM",i[i.LEFT_RIGHT=2]="LEFT_RIGHT",i[i.STEREO_CUSTOM=3]="STEREO_CUSTOM",i[i.RIGHT_LEFT=4]="RIGHT_LEFT"})(wt||(wt={}));class Np extends ot{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=wt.MONOSCOPIC;break;case 1:this.stereoMode=wt.TOP_BOTTOM;break;case 2:this.stereoMode=wt.LEFT_RIGHT;break;case 3:this.stereoMode=wt.STEREO_CUSTOM;break;case 4:this.stereoMode=wt.RIGHT_LEFT;break}this.cursor+=1}}class Fp extends ot{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class Vp extends ot{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class Up extends xe{parseChildrenBoxes(){return pt(this.content)}}class Hp extends ot{constructor(e){super(e),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}}class Gp extends xe{parseChildrenBoxes(){return pt(this.content)}}class Yp extends xe{parseChildrenBoxes(){return pt(this.content)}}class jp extends ot{constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class qp extends xe{parseChildrenBoxes(){return pt(this.content)}}class zp extends ot{constructor(e){super(e),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}}class Wp extends ot{get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e){super(e),this.baseMediaDecodeTime32=0,this.baseMediaDecodeTime64=BigInt(0),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class Qp extends ot{constructor(e){super(e),this.sampleDuration=[],this.sampleSize=[],this.sampleFlags=[],this.sampleCompositionTimeOffset=[],this.optionalFields=0,this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let t=0;t<this.sampleCount;t++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}}const Kp={ftyp:Ip,moov:xp,moof:_p,mdat:Cp,sidx:Op,trak:Mp,mdia:Up,mfhd:jp,tkhd:Hp,traf:qp,tfhd:zp,tfdt:Wp,trun:Qp,minf:Gp,sv3d:Bp,st3d:Np,prhd:Fp,proj:Yp,equi:Vp,unknown:Mo};class Jp{createBox(e,t){const s=Kp[e];return s?new s(t):new Mo(t)}createFromView(e){const s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return bs.createBox(s,new DataView(e.buffer,e.byteOffset))}}const bs=new Jp;function ci(i,e){const t=new Uint8Array(i.buffer),s=e.split("").map(n=>n.charCodeAt(0));let r=i.byteOffset,a=[];for(;r<t.byteLength;){if(t[r]===s[a.length]?a.push(t[r]):a=[],a.length===4){const o=new DataView(i.buffer,r-7,4).getUint32(0);return r-7+o>i.buffer.byteLength?null:bs.createBox(e,new DataView(i.buffer,r-7))}r++}return null}function Ir(i,e){const t=[];let s=i.byteOffset;for(;s<i.buffer.byteLength;){const r=ci(new DataView(i.buffer,s,i.buffer.byteLength-s),e);if(r)t.push(r),s=r.source.byteOffset+r.size;else break}return t}function pt(i){const e=[];let t=0;for(;t<i.byteLength;){const s=bs.createFromView(new DataView(i.buffer,i.byteOffset+t));if(e.push(s),!s.size)break;t+=s.size}return e}const Xp=new TextDecoder("ascii"),Zp=i=>Xp.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",em=i=>{const e=bs.createFromView(i);let t=e.earliestPresentationTime/e.timescale*1e3,s=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=a.subsegmentDuration/e.timescale*1e3,o={status:V.NONE,time:{from:t,to:t+n},byte:{from:s,to:s+a.referencedSize-1}};return t+=n,s+=a.referencedSize,o})},tm=i=>{const e=Ir(i,"mdat"),t=Ir(i,"moof");if(!(e.length&&t.length))return null;const s=t[0],r=e[e.length-1],a=s.source.byteOffset,o=r.source.byteOffset-s.source.byteOffset+r.size;return new DataView(i.buffer,a,o)},im=(i,e)=>{const t=Ir(i,"traf"),s=t[t.length-1].children.find(l=>l.type==="tfhd"),r=t[t.length-1].children.find(l=>l.type==="tfdt"),a=t[t.length-1].children.find(l=>l.type==="trun");let n=0;return a.sampleDuration.length?n=a.sampleDuration.reduce((l,d)=>l+d,0):n=s.defaultSampleDuration*a.sampleCount,(Number(r.baseMediaDecodeTime)+n)/e*1e3},sm=i=>{const e={is3dVideo:!1,stereoMode:0,projectionType:rs.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(ci(i,"sv3d")){e.is3dVideo=!0;const s=ci(i,"st3d");s&&(e.stereoMode=s.stereoMode);const r=ci(i,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const a=ci(i,"equi");a&&(e.projectionData.bounds.top=a.projectionBoundsTop,e.projectionData.bounds.right=a.projectionBoundsRight,e.projectionData.bounds.bottom=a.projectionBoundsBottom,e.projectionData.bounds.left=a.projectionBoundsLeft)}return e},rm={validateData:Zp,parseInit:sm,getIndexRange:()=>{},parseSegments:em,parseFeedableSegmentChunk:tm,getSegmentEndTime:im};var T;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.TrackEntry=174]="TrackEntry",i[i.Video=224]="Video",i[i.Projection=30320]="Projection",i[i.ProjectionType=30321]="ProjectionType",i[i.ProjectionPrivate=30322]="ProjectionPrivate",i[i.Chapters=272869232]="Chapters",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.SilentTracks=22612]="SilentTracks",i[i.SilentTrackNumber=22743]="SilentTrackNumber",i[i.Position=167]="Position",i[i.PrevSize=171]="PrevSize",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.EncryptedBlock=175]="EncryptedBlock",i[i.Attachments=423732329]="Attachments",i[i.Tags=307544935]="Tags",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.CueRelativePosition=240]="CueRelativePosition",i[i.CueDuration=178]="CueDuration",i[i.CueBlockNumber=21368]="CueBlockNumber",i[i.CueCodecState=234]="CueCodecState",i[i.CueReference=219]="CueReference",i[i.CueRefTime=150]="CueRefTime"})(T||(T={}));var R;(function(i){i.SignedInteger="int",i.UnsignedInteger="uint",i.Float="float",i.String="string",i.UTF8="utf8",i.Date="date",i.Master="master",i.Binary="binary"})(R||(R={}));const mn={[T.EBML]:{type:R.Master},[T.EBMLVersion]:{type:R.UnsignedInteger},[T.EBMLReadVersion]:{type:R.UnsignedInteger},[T.EBMLMaxIDLength]:{type:R.UnsignedInteger},[T.EBMLMaxSizeLength]:{type:R.UnsignedInteger},[T.DocType]:{type:R.String},[T.DocTypeVersion]:{type:R.UnsignedInteger},[T.DocTypeReadVersion]:{type:R.UnsignedInteger},[T.Void]:{type:R.Binary},[T.Segment]:{type:R.Master},[T.SeekHead]:{type:R.Master},[T.Seek]:{type:R.Master},[T.SeekID]:{type:R.Binary},[T.SeekPosition]:{type:R.UnsignedInteger},[T.Info]:{type:R.Master},[T.TimestampScale]:{type:R.UnsignedInteger},[T.Duration]:{type:R.Float},[T.Tracks]:{type:R.Master},[T.TrackEntry]:{type:R.Master},[T.Video]:{type:R.Master},[T.Projection]:{type:R.Master},[T.ProjectionType]:{type:R.UnsignedInteger},[T.ProjectionPrivate]:{type:R.Master},[T.Chapters]:{type:R.Master},[T.Cluster]:{type:R.Master},[T.Timestamp]:{type:R.UnsignedInteger},[T.SilentTracks]:{type:R.Master},[T.SilentTrackNumber]:{type:R.UnsignedInteger},[T.Position]:{type:R.UnsignedInteger},[T.PrevSize]:{type:R.UnsignedInteger},[T.SimpleBlock]:{type:R.Binary},[T.BlockGroup]:{type:R.Master},[T.EncryptedBlock]:{type:R.Binary},[T.Attachments]:{type:R.Master},[T.Tags]:{type:R.Master},[T.Cues]:{type:R.Master},[T.CuePoint]:{type:R.Master},[T.CueTime]:{type:R.UnsignedInteger},[T.CueTrackPositions]:{type:R.Master},[T.CueTrack]:{type:R.UnsignedInteger},[T.CueClusterPosition]:{type:R.UnsignedInteger},[T.CueRelativePosition]:{type:R.UnsignedInteger},[T.CueDuration]:{type:R.UnsignedInteger},[T.CueBlockNumber]:{type:R.UnsignedInteger},[T.CueCodecState]:{type:R.UnsignedInteger},[T.CueReference]:{type:R.Master},[T.CueRefTime]:{type:R.UnsignedInteger}},Bo=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const s=as(i,t),r=s in mn,a=r?mn[s].type:R.Binary,n=i.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const l=new DataView(i.buffer,i.byteOffset+t+1,o-1),d=n&255>>o,u=as(l),c=d*2**((o-1)*8)+u,h=t+o;let f;return h+c>i.byteLength?f=new DataView(i.buffer,i.byteOffset+h):f=new DataView(i.buffer,i.byteOffset+h,c),{tag:r?s:"0x"+s.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:f,valueSize:c}},as=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*2**16+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*2**32+i.getUint32(1);case 6:return i.getUint16(0)*2**32+i.getUint32(2);case 7:{const t=i.getUint8(0)*281474976710656+i.getUint16(1)*4294967296+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},je=(i,e)=>{switch(e){case R.SignedInteger:return i.getInt8(0);case R.UnsignedInteger:return as(i);case R.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case R.String:return new TextDecoder("ascii").decode(i);case R.UTF8:return new TextDecoder("utf-8").decode(i);case R.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case R.Master:return i;case R.Binary:return i;default:G(e)}},Xt=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),r=Bo(s);if(!e(r))return;r.type===R.Master&&Xt(r.value,e),t=r.value.byteOffset-i.byteOffset+r.valueSize}},am=i=>{if(i.getUint32(0)!==T.EBML)return!1;let e,t,s;const r=Bo(i);return Xt(r.value,({tag:a,type:n,value:o})=>(a===T.EBMLReadVersion?e=je(o,n):a===T.DocType?t=je(o,n):a===T.DocTypeReadVersion&&(s=je(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},No=[T.Info,T.SeekHead,T.Tracks,T.TrackEntry,T.Video,T.Projection,T.ProjectionType,T.ProjectionPrivate,T.Chapters,T.Cluster,T.Cues,T.Attachments,T.Tags],nm=[T.Timestamp,T.SilentTracks,T.SilentTrackNumber,T.Position,T.PrevSize,T.SimpleBlock,T.BlockGroup,T.EncryptedBlock],om=i=>{let e,t,s,r,a=!1,n=!1,o=!1,l,d,u=!1;const c=0;return Xt(i,({tag:h,type:f,value:g,valueSize:m})=>{if(h===T.SeekID){const v=je(g,f);d=as(v)}else h!==T.SeekPosition&&(d=void 0);return h===T.Segment?(e=g.byteOffset,t=g.byteOffset+m):h===T.Info?a=!0:h===T.SeekHead?n=!0:h===T.TimestampScale?s=je(g,f):h===T.Duration?r=je(g,f):h===T.SeekPosition&&d===T.Cues?l=je(g,f):h===T.Tracks?Xt(g,({tag:v,type:S,value:E})=>v===T.ProjectionType?(u=je(E,S)===1,!1):!0):a&&n&&No.includes(h)&&(o=!0),!o}),D(e,"Failed to parse webm Segment start"),D(t,"Failed to parse webm Segment end"),D(r,"Failed to parse webm Segment duration"),s=s!=null?s:1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(t/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(r/1e9*s*1e3),cuesSeekPosition:l,is3dVideo:u,stereoMode:c,projectionType:rs.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},dm=i=>{if(Q(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},lm=(i,e)=>{let t=!1,s=!1;const r=o=>P(o.time)&&P(o.position),a=[];let n;return Xt(i,({tag:o,type:l,value:d})=>{switch(o){case T.Cues:t=!0;break;case T.CuePoint:n&&r(n)&&a.push(n),n={};break;case T.CueTime:n&&(n.time=je(d,l));break;case T.CueTrackPositions:break;case T.CueClusterPosition:n&&(n.position=je(d,l));break;default:t&&No.includes(o)&&(s=!0)}return!(t&&s)}),n&&r(n)&&a.push(n),a.map((o,l)=>{const{time:d,position:u}=o,c=a[l+1];return{status:V.NONE,time:{from:d,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+u,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},um=i=>{let e=0,t=!1;try{Xt(i,s=>s.tag===T.Cluster?s.tagSize<=i.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):nm.includes(s.tag)?(e+s.tagSize<=i.byteLength&&(e+=s.tagSize,t||(t=[T.SimpleBlock,T.BlockGroup,T.EncryptedBlock].includes(s.tag))),!0):!1)}catch(s){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},cm={validateData:am,parseInit:om,getIndexRange:dm,parseSegments:lm,parseFeedableSegmentChunk:um};var hm=kt,fm=ls,pm=Ne,mm=pm("match"),vm=function(i){var e;return hm(i)&&((e=i[mm])!==void 0?!!e:fm(i)=="RegExp")},gm=ms,Sm=String,bm=function(i){if(gm(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return Sm(i)},ym=Dt,Tm=function(){var i=ym(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e},Em=at,$m=nt,wm=Ur,Am=Tm,vn=RegExp.prototype,km=function(i){var e=i.flags;return e===void 0&&!("flags"in vn)&&!$m(i,"flags")&&wm(vn,i)?Em(Am,i):e},ea=rt,Pm=hs,Dm=Math.floor,rr=ea("".charAt),Rm=ea("".replace),ar=ea("".slice),Lm=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Im=/\$([$&'`]|\d{1,2})/g,xm=function(i,e,t,s,r,a){var n=t+i.length,o=s.length,l=Im;return r!==void 0&&(r=Pm(r),l=Lm),Rm(a,l,function(d,u){var c;switch(rr(u,0)){case"$":return"$";case"&":return i;case"`":return ar(e,0,t);case"'":return ar(e,n);case"<":c=r[ar(u,1,-1)];break;default:var h=+u;if(h===0)return d;if(h>o){var f=Dm(h/10);return f===0?d:f<=o?s[f-1]===void 0?rr(u,1):s[f-1]+rr(u,1):d}c=s[h-1]}return c===void 0?"":c})},_m=ps,Cm=at,ta=rt,gn=Nr,Om=Ie,Mm=us,Bm=vm,Gt=bm,Nm=cs,Fm=km,Vm=xm,Um=Ne,Hm=Um("replace"),Gm=TypeError,Fo=ta("".indexOf),Ym=ta("".replace),Sn=ta("".slice),jm=Math.max,bn=function(i,e,t){return t>i.length?-1:e===""?t:Fo(i,e,t)};_m({target:"String",proto:!0},{replaceAll:function(e,t){var s=gn(this),r,a,n,o,l,d,u,c,h,f=0,g=0,m="";if(!Mm(e)){if(r=Bm(e),r&&(a=Gt(gn(Fm(e))),!~Fo(a,"g")))throw Gm("`.replaceAll` does not allow non-global regexes");if(n=Nm(e,Hm),n)return Cm(n,e,s,t);if(r)return Ym(Gt(s),e,t)}for(o=Gt(s),l=Gt(e),d=Om(t),d||(t=Gt(t)),u=l.length,c=jm(1,u),f=bn(o,l,0);f!==-1;)h=d?Gt(t(l,f,o)):Vm(l,o,f,[],void 0,t),m+=Sn(o,g,f)+h,g=f+u,f=bn(o,l,f+c);return g<o.length&&(m+=Sn(o,g)),m}});var qm=Do,zm=qm("String","replaceAll"),Wm=zm,Qm=Wm,Km=Qm,Jm=Km,yn=Br(Jm);const Xm=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)},Tn=i=>{if(!i.startsWith("P"))return;const e=(n,o)=>{const l=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(l)?0:l)*o},s=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),r=(s==null?void 0:s[1])==="-"?-1:1,a={days:e(s==null?void 0:s[5],r),hours:e(s==null?void 0:s[6],r),minutes:e(s==null?void 0:s[7],r),seconds:e(s==null?void 0:s[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},jt=(i,e)=>{let t=i;t=yn(t,"$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,a]of Object.entries(s)){const n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=yn(t,n,(o,l)=>Q(a)?o:Q(l)?a:a.padStart(parseInt(l,10),"0"))}return t},Zm=(i,e)=>{var t,s,r,a,n,o,l,d,u,c,h,f,g,m,v,S,E,w,$,k,H,Y,K,j,J,Z,M,_,se,B,L,X,oe,he,me,Fe,ii,Ct,W,Se,Te,we;const si=new DOMParser().parseFromString(i,"application/xml"),Ke={video:[],audio:[],text:[]},ke=si.children[0],Mt=ke.getElementsByTagName("Period")[0],ri=(r=(s=(t=ke.querySelector("BaseURL"))===null||t===void 0?void 0:t.textContent)===null||s===void 0?void 0:s.trim())!==null&&r!==void 0?r:"",qo=Mt.children,zo=ke.getAttribute("type")==="dynamic",ra=ke.getAttribute("availabilityStartTime"),Wo=ra?new Date(ra).getTime():void 0;let mt;const aa=ke.getAttribute("mediaPresentationDuration"),na=Mt.getAttribute("duration"),ys=ke.getElementsByTagName("vk:Attrs")[0],oa=ys==null?void 0:ys.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(aa)mt=Tn(aa);else if(na){const _e=Tn(na);P(_e)&&(mt=_e)}else oa&&(mt=parseInt(oa,10));let Qo=0;const Ts=(n=(a=ke.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],Ko=Ts.includes(ss.WEBM_AS_IN_FFMPEG)||Ts.includes(ss.WEBM_AS_IN_SPEC)?Jt.WEBM:Jt.MP4;for(const _e of qo){const Ei=_e.getAttribute("mimeType"),Jo=_e.getAttribute("codecs"),da=(o=_e.getAttribute("contentType"))!==null&&o!==void 0?o:Ei==null?void 0:Ei.split("/")[0],Xo=(d=(l=_e.getAttribute("profiles"))===null||l===void 0?void 0:l.split(","))!==null&&d!==void 0?d:[],la=_e.querySelectorAll("Representation"),Zo=_e.querySelector("SegmentTemplate");if(da===ge.TEXT){for(const fe of la){const dt=fe.getAttribute("id")||"",$i=_e.getAttribute("lang"),Bt=(h=(c=(u=fe.querySelector("BaseURL"))===null||u===void 0?void 0:u.textContent)===null||c===void 0?void 0:c.trim())!==null&&h!==void 0?h:"",Es=new URL(Bt||ri,e).toString(),$s=dt.includes("_auto");Ke[ge.TEXT].push({id:dt,lang:$i,isAuto:$s,kind:ge.TEXT,url:Es})}continue}for(const fe of la){const dt=(f=fe.getAttribute("mimeType"))!==null&&f!==void 0?f:Ei,$i=(m=(g=fe.getAttribute("codecs"))!==null&&g!==void 0?g:Jo)!==null&&m!==void 0?m:"",Bt=(S=(v=fe.getAttribute("contentType"))!==null&&v!==void 0?v:dt==null?void 0:dt.split("/")[0])!==null&&S!==void 0?S:da,Es=(w=(E=_e.getAttribute("profiles"))===null||E===void 0?void 0:E.split(","))!==null&&w!==void 0?w:[],$s=parseInt(($=fe.getAttribute("width"))!==null&&$!==void 0?$:"",10),ua=parseInt((k=fe.getAttribute("height"))!==null&&k!==void 0?k:"",10),ca=parseInt((H=fe.getAttribute("bandwidth"))!==null&&H!==void 0?H:"",10)/1e3,ha=(Y=fe.getAttribute("frameRate"))!==null&&Y!==void 0?Y:"",ed=(K=fe.getAttribute("quality"))!==null&&K!==void 0?K:void 0,td=ha?Xm(ha):void 0,id=(j=fe.getAttribute("id"))!==null&&j!==void 0?j:(Qo++).toString(10),sd=Bt==="video"?`${ua}p`:Bt==="audio"?`${ca}Kbps`:$i,rd=`${id}@${sd}`,ad=(M=(Z=(J=fe.querySelector("BaseURL"))===null||J===void 0?void 0:J.textContent)===null||Z===void 0?void 0:Z.trim())!==null&&M!==void 0?M:"",fa=new URL(ad||ri,e).toString(),nd=[...Ts,...Xo,...Es];let ws;const od=fe.querySelector("SegmentBase"),vt=(_=fe.querySelector("SegmentTemplate"))!==null&&_!==void 0?_:Zo;if(od){const gt=(B=(se=fe.querySelector("SegmentBase Initialization"))===null||se===void 0?void 0:se.getAttribute("range"))!==null&&B!==void 0?B:"",[St,ks]=gt.split("-").map(Nt=>parseInt(Nt,10)),lt={from:St,to:ks},ai=(L=fe.querySelector("SegmentBase"))===null||L===void 0?void 0:L.getAttribute("indexRange"),[Ps,wi]=ai?ai.split("-").map(Nt=>parseInt(Nt,10)):[],ni=ai?{from:Ps,to:wi}:void 0;ws={type:Re.BYTE_RANGE,url:fa,initRange:lt,indexRange:ni}}else if(vt){const gt={representationId:(X=fe.getAttribute("id"))!==null&&X!==void 0?X:void 0,bandwidth:(oe=fe.getAttribute("bandwidth"))!==null&&oe!==void 0?oe:void 0},St=parseInt((he=vt.getAttribute("timescale"))!==null&&he!==void 0?he:"",10),ks=(me=vt.getAttribute("initialization"))!==null&&me!==void 0?me:"",lt=vt.getAttribute("media"),ai=(ii=parseInt((Fe=vt.getAttribute("startNumber"))!==null&&Fe!==void 0?Fe:"",10))!==null&&ii!==void 0?ii:1,Ps=jt(ks,gt);if(!lt)throw new ReferenceError("No media attribute in SegmentTemplate");const wi=(Ct=vt.querySelectorAll("SegmentTimeline S"))!==null&&Ct!==void 0?Ct:[],ni=[];let Nt=0,Ds="",Rs=0;if(wi.length){let Ai=ai,Ce=0;for(const Ft of wi){const Ve=parseInt((W=Ft.getAttribute("d"))!==null&&W!==void 0?W:"",10),bt=parseInt((Se=Ft.getAttribute("r"))!==null&&Se!==void 0?Se:"",10)||0,ki=parseInt((Te=Ft.getAttribute("t"))!==null&&Te!==void 0?Te:"",10);Ce=Number.isFinite(ki)?ki:Ce;const Ls=Ve/St*1e3,Is=Ce/St*1e3;for(let Pi=0;Pi<bt+1;Pi++){const ld=jt(lt,{...gt,segmentNumber:Ai.toString(10),segmentTime:(Ce+Pi*Ve).toString(10)}),pa=(Is!=null?Is:0)+Pi*Ls,ud=pa+Ls;Ai++,ni.push({time:{from:pa,to:ud},url:ld})}Ce+=(bt+1)*Ve,Nt+=(bt+1)*Ls}Rs=Ce/St*1e3,Ds=jt(lt,{...gt,segmentNumber:Ai.toString(10),segmentTime:Ce.toString(10)})}else if(P(mt)){const Ce=parseInt((we=vt.getAttribute("duration"))!==null&&we!==void 0?we:"",10)/St*1e3,Ft=Math.ceil(mt/Ce);let Ve=0;for(let bt=1;bt<Ft;bt++){const ki=jt(lt,{...gt,segmentNumber:bt.toString(10),segmentTime:Ve.toString(10)});ni.push({time:{from:Ve,to:Ve+Ce},url:ki}),Ve+=Ce}Rs=Ve,Ds=jt(lt,{...gt,segmentNumber:Ft.toString(10),segmentTime:Ve.toString(10)})}const dd={time:{from:Rs,to:1/0},url:Ds};ws={type:Re.TEMPLATE,baseUrl:fa,segmentTemplateUrl:lt,initUrl:Ps,totalSegmentsDurationMs:Nt,segments:ni,nextSegmentBeyondManifest:dd,timescale:St}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Bt||!dt)continue;const As={video:ge.VIDEO,audio:ge.AUDIO,text:ge.TEXT}[Bt];As&&Ke[As].push({id:rd,kind:As,segmentReference:ws,profiles:nd,duration:mt,bitrate:ca,mime:dt,codecs:$i,width:$s,height:ua,fps:td,quality:ed})}}return{dynamic:zo,liveAvailabilityStartTime:Wo,duration:mt,container:Ko,representations:Ke}},ev=({id:i,width:e,height:t,bitrate:s,fps:r,quality:a})=>{var n;const o=(n=a?vs(a):void 0)!==null&&n!==void 0?n:gi({width:e,height:t});return o&&{id:i,quality:o,bitrate:s,size:{width:e,height:t},fps:r}},tv=({id:i,bitrate:e})=>({id:i,bitrate:e}),iv=(i,e,t)=>{var s;const r=e.indexOf(t);return(s=Je(i,Math.round(i.length*r/e.length)))!==null&&s!==void 0?s:Je(i,-1)},sv=({id:i,lang:e,url:t,isAuto:s})=>({id:i,url:t,isAuto:s,type:"internal",language:e}),En=i=>"size"in i,Yt=i=>i.type===Re.TEMPLATE,xr=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);class $n{constructor(e,t,s,r,{fetcher:a,tuning:n,getCurrentPosition:o,isActiveLowLatency:l,compatibilityMode:d=!1,manifest:u}){switch(this.onLastSegment$=new b(!1),this.fullyBuffered$=new b(!1),this.playingRepresentation$=new b(void 0),this.playingRepresentationInit$=new b(void 0),this.error$=new x,this.gaps=[],this.subscription=new ie,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new Kt,this.destroyAbortController=new Kt,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.liveInitialAdditionalOffset=0,this.isSeekingLive=!1,this.index=0,this.startWith=$e(this.destroyAbortController.signal,async function*(c){const h=this.representations.get(c);D(h,`Cannot find representation ${c}`),this.playingRepresentationId=c,this.downloadingRepresentationId=c,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${h.mime}; codecs="${h.codecs}"`),this.sourceBufferTaskQueue=new Lp(this.sourceBuffer),this.subscription.add(C(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},v=>this.error$.next({id:"SegmentEjection",category:I.WTF,message:"Error when trying to clear segments ejected by browser",thrown:v}))),this.subscription.add(C(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:I.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(v=>{if(!this.sourceBuffer)return;const S=Math.min(this.bufferLimit,pn(this.sourceBuffer.buffered)*.8);this.bufferLimit=S,this.pruneBuffer(this.getCurrentPosition(),v)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(v=>this.error$.next(v))),yield this.loadInit(h,"high",!0);const f=this.initData.get(h.id),g=this.segments.get(h.id),m=this.parsedInitData.get(h.id);D(f,"No init buffer for starting representation"),D(g,"No segments for starting representation"),f instanceof ArrayBuffer&&(this.searchGaps(g,h),yield this.sourceBufferTaskQueue.append(f,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(m))}.bind(this)),this.switchTo=$e(this.destroyAbortController.signal,async function*(c){if(c===this.downloadingRepresentationId||c===this.switchingToRepresentationId)return;this.switchingToRepresentationId=c;const h=this.representations.get(c);D(h,`No such representation ${c}`);let f=this.segments.get(c),g=this.initData.get(c);if(Q(g)||Q(f)?yield this.loadInit(h,"high",!1):g instanceof Promise&&(yield g),f=this.segments.get(c),D(f,"No segments for starting representation"),g=this.initData.get(c),!g||!(g instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=c,this.abort(),yield this.sourceBufferTaskQueue.append(g,this.downloadAbortController.signal);const m=this.getCurrentPosition();P(m)&&(this.isLive||(f.forEach(v=>v.status=V.NONE),this.pruneBuffer(m,1/0,!0)),this.maintain(m))}.bind(this)),this.seekLive=$e(this.destroyAbortController.signal,async function*(c){var h;if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!c)return;for(const E of this.representations.keys()){const w=c.find(H=>H.id===E);w&&this.representations.set(E,w);const $=this.representations.get(E);if(!$||!Yt($.segmentReference))return;const k=this.getActualLiveStartingSegments($.segmentReference);this.segments.set($.id,k)}const f=(h=this.switchingToRepresentationId)!==null&&h!==void 0?h:this.downloadingRepresentationId,g=this.representations.get(f);D(g);const m=this.segments.get(f);D(m,"No segments for starting representation");const v=this.initData.get(f);if(D(v,"No init buffer for starting representation"),!(v instanceof ArrayBuffer))return;const S=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),S&&(yield this.sourceBufferTaskQueue.remove(S.from*1e3,S.to*1e3,this.destroyAbortController.signal)),this.searchGaps(m,g),yield this.sourceBufferTaskQueue.append(v,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this)),this.fetcher=a,this.tuning=n,this.compatibilityMode=d,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=l,this.isLive=!!(u!=null&&u.dynamic),this.container=s,s){case Jt.MP4:this.containerParser=rm;break;case Jt.WEBM:this.containerParser=cm;break;default:G(s)}this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Kt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Q(e)||Q(this.downloadingRepresentationId)||Q(this.playingRepresentationId)||Q(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(D(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const r=s.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const u=zt(this.sourceBuffer.buffered,e),c=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&u>=r.time.to-e+100&&(a=c)}if(isFinite(this.bufferLimit)&&pn(this.sourceBuffer.buffered)>=this.bufferLimit){const d=zt(this.sourceBuffer.buffered,e),u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<u);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(s,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{const u=Je(o,0);u&&u.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===V.FED&&!o.length&&zt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const l=Je(s,-1);l&&l.status===V.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===l))}searchGaps(e,t){this.gaps=[];let s=0;const r=this.isLive?this.liveInitialAdditionalOffset:0;for(const a of e)Math.trunc(a.time.from-s)>0&&this.gaps.push({representation:t.id,from:s,to:a.time.from+r}),s=a.time.to;P(t.duration)&&t.duration-s>0&&this.gaps.push({representation:t.id,from:s,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,s=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[];let a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<s&&n>=0);return this.liveInitialAdditionalOffset=a-s,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(r=>r.id===this.downloadingRepresentationId);if(!t)return;const s=this.segments.get(t.id);if(s!=null&&s.length)return{from:s[0].time.from,to:s[s.length-1].time.to}}updateLive(e){var t,s,r,a;for(const n of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!n||!Yt(n.segmentReference))return;const o=n.segmentReference.segments.map(c=>({...c,status:V.NONE,size:void 0})),l=(s=this.segments.get(n.id))!==null&&s!==void 0?s:[],d=(a=(r=Je(l,-1))===null||r===void 0?void 0:r.time.to)!==null&&a!==void 0?a:0,u=o==null?void 0:o.findIndex(c=>Math.floor(d)>=Math.floor(c.time.from)&&Math.floor(d)<=Math.floor(c.time.to));if(u===-1){this.liveUpdateSegmentIndex=0;const c=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,c)}else{const c=o.slice(u+1);this.segments.set(n.id,[...l,...c])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(const s of this.representations.values()){const r=s.segmentReference;if(!Yt(r))return;const a=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),n=jt(r.segmentTemplateUrl,{segmentTime:a}),o=(t=this.segments.get(s.id))!==null&&t!==void 0?t:[],l=o.find(u=>Math.floor(u.time.from)===Math.floor(e.segment.time.from));l&&(l.time.to=e.segment.time.to),!!o.find(u=>Math.floor(u.time.from)===Math.floor(e.segment.time.to))||o.push({status:V.NONE,time:{from:e.segment.time.to,to:1/0},url:n})}}findSegmentStartTime(e){var t,s,r;const a=(s=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&s!==void 0?s:this.playingRepresentationId;if(!a)return;const n=this.segments.get(a);if(!n)return;const o=n.find(l=>l.time.from<=e&&l.time.to>=e);return(r=o==null?void 0:o.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,s){return this.isLive?this.selectForwardBufferSegmentsLive(e,s):this.selectForwardBufferSegmentsRecord(e,t,s)}selectForwardBufferSegmentsLive(e,t){const s=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=s),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,s){const r=e.findIndex(({status:c,time:{from:h,to:f}},g)=>{const m=h<=s&&f>=s,v=h>s||m||g===0&&s===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),E=this.preloadOnly&&h<=s+S||f<=s+S;return(c===V.NONE||c===V.PARTIALLY_EJECTED&&v&&E&&this.sourceBuffer&&!Lr(this.sourceBuffer.buffered,s))&&v&&E});if(r===-1)return[];if(t!==Re.BYTE_RANGE)return e.slice(r,r+1);const a=e;let n=0,o=0;const l=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,u=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=d||o<=u);c++){const h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status===V.NONE||h.status===V.PARTIALLY_EJECTED)l.push(h);else break}return l}async loadSegments(e,t,s="auto"){t.segmentReference.type===Re.TEMPLATE?await this.loadTemplateSegment(e[0],t,s):await this.loadByteRangeSegments(e,t,s)}async loadTemplateSegment(e,t,s="auto"){e.status=V.DOWNLOADING;const r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);const{range:a,url:n,signal:o,onProgress:l,onProgressTasks:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await $e(o,async function*(){const u=ji(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,u))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{const u=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:l,priority:s,isLowLatency:this.isActiveLowLatency()});if(!u)return;const c=new DataView(u);if(this.isActiveLowLatency()){const h=t.segmentReference.timescale;r.segment.time.to=this.containerParser.getSegmentEndTime(c,h)}l&&r.feedingBytes&&d?await Promise.all(d):await this.sourceBufferTaskQueue.append(c,o),r.segment.status=V.DOWNLOADED,this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(u){if(!xr(u))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(u)}}async loadByteRangeSegments(e,t,s="auto"){if(!e.length)return;for(const l of e)l.status=V.DOWNLOADING,this.activeSegments.add({segment:l,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await $e(n,async function*(){const l=ji(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,l))}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:s}),this.failedDownloads=0}catch(l){if(!xr(l))return;this.abortActiveSegments(e),this.onSegmentDownloadError(l)}}prepareByteRangeFetchSegmentParams(e,t){if(Yt(t.segmentReference))throw new Error("Representation is not byte range type");const s=t.segmentReference.url,r={from:Je(e,0).byte.from,to:Je(e,-1).byte.to},{signal:a}=this.downloadAbortController,n=()=>{this.abort()};return{url:s,range:r,signal:a,onProgress:(l,d)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:l,loaded:d,signal:a,onSegmentAppendFailed:n,globalFrom:r?r.from:0,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:I.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Yt(t.segmentReference))throw new Error("Representation is not template type");const s=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&s.searchParams.set("low-latency","yes");const r=s.toString(),{signal:a}=this.downloadAbortController,n=()=>{this.abort()},o=[],d=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(u,c)=>{if(!a.aborted)try{const h=this.onSomeTemplateDataLoaded({dataView:u,loaded:c,signal:a,onSegmentAppendFailed:n,representationId:t.id});o.push(h)}catch(h){this.error$.next({id:"SegmentFeeding",category:I.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}}:void 0;return{url:r,signal:a,onProgress:d,onProgressTasks:o}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSegmentDownloadError(e){var t;let s=!1;const r=this.getCurrentPosition();this.sourceBuffer&&P(r)&&(s=zt((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,s||this.error$.next({id:"SegmentDownload",category:I.NETWORK,message:"Error when fetching segments",thrown:e})}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:s,onSegmentAppendFailed:r,signal:a}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const o of this.activeSegments){const{segment:l}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=s,o.loadedBytes>o.feedingBytes){const d=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),u=this.containerParser.parseFeedableSegmentChunk(d);u!=null&&u.byteLength&&(l.status=V.PARTIALLY_FED,o.feedingBytes+=u.byteLength,await this.sourceBufferTaskQueue.append(u),o.fedBytes+=u.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:s,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;const o=this.representations.get(t);if(!o)return;const l=o.segmentReference.type,d=e.byteLength;for(const u of this.activeSegments){const{segment:c}=u,h=l===Re.BYTE_RANGE,f=h?c.byte.to-c.byte.from+1:d;if(u.representationId!==t||!(!h||c.byte.from>=s&&c.byte.to<s+e.byteLength))continue;if(a.aborted){n();continue}const m=h?c.byte.from-s:0,v=h?c.byte.to-s:e.byteLength,S=m<r,E=v<=r;if(c.status===V.DOWNLOADING&&S&&E){c.status=V.DOWNLOADED;const w=new DataView(e.buffer,e.byteOffset+m,f);this.sourceBufferTaskQueue.append(w,a).then($=>$&&!a.aborted?this.onSegmentFullyAppended(u,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&(u.loadedBytes=Math.min(f,r-m),u.loadedBytes>u.feedingBytes)){const w=new DataView(e.buffer,e.byteOffset+m+u.feedingBytes,u.loadedBytes-u.feedingBytes),$=u.loadedBytes===f?w:this.containerParser.parseFeedableSegmentChunk(w);$!=null&&$.byteLength&&(c.status=V.PARTIALLY_FED,u.feedingBytes+=$.byteLength,this.sourceBufferTaskQueue.append($,a).then(k=>{if(a.aborted)n();else if(k)u.fedBytes+=$.byteLength,u.fedBytes===f&&this.onSegmentFullyAppended(u,t);else{if(u.feedingBytes<f)return;n()}}))}}}onSegmentFullyAppended(e,t){var s;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=V.FED,En(e.segment)&&(e.segment.size=e.fedBytes);for(const r of this.representations.values())if(r.id!==t)for(const a of(s=this.segments.get(r.id))!==null&&s!==void 0?s:[])a.status===V.FED&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status=V.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===V.PARTIALLY_FED||e.status===V.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=V.NONE),e.status=V.PARTIALLY_EJECTED):e.status=V.NONE;for(const s of this.activeSegments.values())if(s.segment===e){this.activeSegments.delete(s);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,a]of this.initData.entries()){const n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=fn(()=>this.loadInit(s,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",s=!1){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!s&&this.failedDownloads>0?$e(this.destroyAbortController.signal,async function*(){const o=ji(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(async o=>{if(!o)return;const{init:l,dataView:d,segments:u}=o,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c);let h=u;this.isLive&&Yt(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),l&&this.parsedInitData.set(e.id,l)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),s&&this.error$.next({id:"LoadInits",category:I.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,s=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Q(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,n=-1/0,o=!1;const l=d=>{var u;a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const c=En(d)?(u=d.size)!==null&&u!==void 0?u:0:d.byte.to-d.byte.from;r+=c};for(const d of this.segments.values())for(const u of d){if(u.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;u.status===V.FED&&l(u)}if(o=isFinite(a)&&isFinite(n),!o){r=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const u of d){if(u.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;u.status===V.FED&&l(u)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const u=this.sourceBuffer.buffered.start(d)*1e3,c=this.sourceBuffer.buffered.end(d)*1e3;for(const h of this.segments.values())for(const f of h)if(f.status===V.NONE&&Math.round(f.time.from)<=Math.round(u)&&Math.round(f.time.to)>=Math.round(c)){a=u,n=c;break}}if(o=isFinite(a)&&isFinite(n),!o&&s){r=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const u of this.segments.values())for(const c of u)c.time.from>e+d&&c.status===V.FED&&l(c)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const s of t){let r={representation:e,from:s.time.from,to:s.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=s.time.from||n>=s.time.to)){if(n<=s.time.from&&o>=s.time.to){r=void 0;break}o>s.time.from&&o<s.time.to&&(r.from=o),n<s.time.to&&n>s.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=fn(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:I.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Q(this.sourceBuffer)||Q(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const r=Math.round(this.sourceBuffer.buffered.start(s)*1e3),a=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:r,to:a})}const t=1;for(const s of this.segments.values())for(const r of s){const{status:a}=r;if(a!==V.FED&&a!==V.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),l=e.some(u=>u.from-t<=n&&u.to+t>=o),d=e.filter(u=>n>=u.from-t&&n<=u.to+t||o>=u.from-t&&o<=u.to+t);l||(d.length===1?r.status=V.PARTIALLY_EJECTED:r.status=V.NONE)}}}var _r=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},rv=i=>{var e,t;const s=i.get("X-Delivery-Type"),r=i.get("X-Reused"),a=s===null?br.HTTP1:(e=s)!==null&&e!==void 0?e:void 0,n=r===null?void 0:(t={1:!0,0:!1}[r])!==null&&t!==void 0?t:void 0;return{type:a,reused:n}},Wt;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(Wt||(Wt={}));class av{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.lastConnectionType$=new b(void 0),this.lastConnectionReused$=new b(void 0),this.lastRequestFirstBytes$=new b(void 0),this.abortAllController=new Kt,this.subscription=new ie,this.fetchManifest=$e(this.abortAllController.signal,async function*(r){let a=r;this.requestQuic&&(a=_r(a));const n=yield mi(a,{signal:this.abortAllController.signal}).catch(oi);return n?(this.onHeadersReceived(n.headers),n.text()):null}.bind(this)),this.fetch=$e(this.abortAllController.signal,async function*(r,{rangeMethod:a=this.compatibilityMode?Wt.HEADER:Wt.PARAM,range:n,onProgress:o,priority:l="auto",signal:d,measureThroughput:u=!0,isLowLatency:c=!1}={}){var h,f;let g=r;const m=new Headers;if(n)switch(a){case Wt.HEADER:{m.append("Range",`bytes=${n.from}-${n.to}`);break}case Wt.PARAM:{const _=new URL(g,location.href);_.searchParams.append("bytes",`${n.from}-${n.to}`),g=_.toString();break}default:G(a)}this.requestQuic&&(g=_r(g));let v=this.abortAllController.signal,S;if(d){const _=new Kt;if(S=N(C(this.abortAllController.signal,"abort"),C(d,"abort")).subscribe(()=>{try{_.abort()}catch(se){oi(se)}}),this.abortAllController.signal.aborted||d.aborted)try{_.abort()}catch(se){oi(se)}v=_.signal}const E=ne(),w=yield mi(g,{priority:l,headers:m,signal:v}).catch(oi),$=ne();if(!w)return S==null||S.unsubscribe(),null;if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt($-E),!w.ok||!w.body)return S==null||S.unsubscribe(),Promise.reject(new Error(`Fetch error ${w.status}: ${w.statusText}`));if(this.onHeadersReceived(w.headers),!o&&!u)return S==null||S.unsubscribe(),w.arrayBuffer();const[k,H]=w.body.tee(),Y=k.getReader();u&&((f=this.throughputEstimator)===null||f===void 0||f.trackStream(H,c));let K=0,j=new Uint8Array(0),J=!1;const Z=_=>{S==null||S.unsubscribe(),J=!0,oi(_)},M=$e(v,async function*({done:_,value:se}){if(K===0&&this.lastRequestFirstBytes$.next(ne()-E),v.aborted){S==null||S.unsubscribe();return}if(!_&&se){const B=new Uint8Array(j.length+se.length);B.set(j),B.set(se,j.length),j=B,K+=se.byteLength,o==null||o(new DataView(j.buffer),K),yield Y==null?void 0:Y.read().then(M,Z)}}.bind(this));return yield Y==null?void 0:Y.read().then(M,Z),S==null||S.unsubscribe(),J?null:j.buffer}.bind(this)),this.fetchByteRangeRepresentation=$e(this.abortAllController.signal,async function*(r,a,n){var o;if(r.type!==Re.BYTE_RANGE)return null;const{from:l,to:d}=r.initRange;let u=l,c=d,h=!1,f,g;r.indexRange&&(f=r.indexRange.from,g=r.indexRange.to,h=d+1===f,h&&(u=Math.min(f,l),c=Math.max(g,d))),u=Math.min(u,0);const m=yield this.fetch(r.url,{range:{from:u,to:c},priority:n,measureThroughput:!1});if(!m)return null;const v=new DataView(m,l-u,d-u+1);if(!a.validateData(v))throw new Error("Invalid media file");const S=a.parseInit(v),E=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(S);if(!E)throw new ReferenceError("No way to load representation index");let w;if(h)w=new DataView(m,E.from-u,E.to-E.from+1);else{const k=yield this.fetch(r.url,{range:E,priority:n,measureThroughput:!1});if(!k)return null;w=new DataView(k)}const $=a.parseSegments(w,S,E);return{init:S,dataView:new DataView(m),segments:$}}.bind(this)),this.fetchTemplateRepresentation=$e(this.abortAllController.signal,async function*(r,a){if(r.type!==Re.TEMPLATE)return null;const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield this.fetch(n,{priority:a,measureThroughput:!1});return o?{init:null,segments:r.segments.map(d=>({...d,status:V.NONE,size:void 0})),dataView:new DataView(o)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=rv(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}async fetchRepresentation(e,t,s="auto"){var r,a;const{type:n}=e;switch(n){case Re.BYTE_RANGE:return(r=await this.fetchByteRangeRepresentation(e,t,s))!==null&&r!==void 0?r:null;case Re.TEMPLATE:return(a=await this.fetchTemplateRepresentation(e,s))!==null&&a!==void 0?a:null;default:G(n)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const oi=i=>{if(!xr(i))throw i},Cr=1e3,ns=(i,e,t)=>t*e+(1-t)*i,Vo=(i,e)=>i.reduce((t,s)=>t+s,0)/e,nv=(i,e,t,s)=>{let r=0,a=t;const n=Vo(i,e),o=e<s?e:s;for(let l=0;l<o;l++)i[a]>n?r++:r--,a=(i.length+a-1)%i.length;return Math.abs(r)===o};class ia{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 b(e.initial),this.debounced$=new b(e.initial);const s=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ye(`raw_${s}`),this.smoothedSeries$=new Ye(`smoothed_${s}`),this.reportedSeries$=new Ye(`reported_${s}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,s=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,s++);this.takenMeasures=s,t/=s;const r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(Q(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 ov extends ia{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ns(this.slow,e,this.params.emaAlphaSlow),this.fast=ns(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class dv extends ia{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Vo(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ns(this.emaSmoothed,e,this.params.emaAlpha);const s=nv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class lv extends ia{constructor(e){super(e),this.furtherValues=[],this.currentTopExtremumValue=0,this.extremumInterval=e.extremumInterval}next(e){this.currentTopExtremumValue<=e?(this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.push(e)}updateSmoothedValue(e){this.smoothed=this.smoothed?ns(this.smoothed,e,this.params.emaAlpha):e}}class Or{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new ov({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new dv({initial:e,emaAlpha:s.emaAlpha,basisTrendChangeCount:s.basisTrendChangeCount,changeThreshold:s.changeThreshold,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new lv({initial:e,label:"liveEdgeDelay",...t})}}const uv=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)},yt=()=>window.ManagedMediaSource||window.MediaSource,Uo=()=>{var i,e;return!!(window.ManagedMediaSource&&(!((e=(i=window.ManagedSourceBuffer)===null||i===void 0?void 0:i.prototype)===null||e===void 0)&&e.appendBuffer))},cv=()=>{var i,e;return!!(window.MediaSource&&window.MediaStreamTrack&&(!((e=(i=window.SourceBuffer)===null||i===void 0?void 0:i.prototype)===null||e===void 0)&&e.appendBuffer))},hv=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource,wn=["timeupdate","progress","play","seeked","stalled","waiting"];var De;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(De||(De={}));let fv=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new ie,this.representationSubscription=new ie,this.state$=new le(De.NONE),this.currentVideoRepresentation$=new b(void 0),this.currentVideoRepresentationInit$=new b(void 0),this.error$=new x,this.lastConnectionType$=new b(void 0),this.lastConnectionReused$=new b(void 0),this.lastRequestFirstBytes$=new b(void 0),this.isLive$=new b(!1),this.liveDuration$=new b(0),this.liveAvailabilityStartTime$=new b(void 0),this.bufferLength$=new b(0),this.liveLoadBufferLength$=new b(0),this.livePositionFromPlayer$=new b(0),this.isActiveLowLatency=!1,this.isUpdatingLive=!1,this.isJumpGapAfterSeekLive=!1,this.liveLastSeekOffset=0,this.forceEnded$=new x,this.gapWatchdogStarted=!1,this.destroyController=new Kt,this.initManifest=$e(this.destroyController.signal,async function*(t,s,r){var a;this.element=t,this.manifestUrlString=Me(s,r,pe.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(De.MANIFEST_READY),this.manifest=yield this.updateManifest(),!((a=this.manifest)===null||a===void 0)&&a.representations.video.length?this.state$.setState(De.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:I.PARSER,message:"No playable video representations"})}.bind(this)),this.updateManifest=$e(this.destroyController.signal,async function*(){var t;const s=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:I.NETWORK,message:"Failed to load manifest",thrown:n})});if(!s)return null;let r;try{r=Zm(s!=null?s:"",this.manifestUrlString)}catch(n){this.error$.next({id:"ManifestParsing",category:I.PARSER,message:"Failed to parse MPD manifest",thrown:n})}if(!r)return null;const a=({kind:n,mime:o,codecs:l})=>{var d,u,c,h;return!!(!((u=(d=this.element)===null||d===void 0?void 0:d.canPlayType)===null||u===void 0)&&u.call(d,o)&&(!((h=(c=yt())===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0)&&h.call(c,`${o}; codecs="${l}"`))||n===ge.TEXT)};return r.dynamic&&this.isLive$.getValue()!==r.dynamic&&(this.isLive$.next(r.dynamic),this.liveDuration$.getValue()!==r.duration&&this.liveDuration$.next(-1*((t=r.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==r.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(r.liveAvailabilityStartTime)),{...r,representations:is(Object.entries(r.representations).map(([n,o])=>[n,o.filter(a)]))}}.bind(this)),this.initRepresentations=$e(this.destroyController.signal,async function*(t,s,r){var a;D(this.manifest),D(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(De.REPRESENTATIOS_READY);const n=m=>{this.representationSubscription.add(C(m,"error").pipe(ue(v=>{var S;return!!(!((S=this.element)===null||S===void 0)&&S.played.length)})).subscribe(v=>{this.error$.next({id:"VideoSource",category:I.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:v})}))};this.source=this.tuning.useManagedMediaSource?hv():new MediaSource;const o=document.createElement("source");if(n(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),this.tuning.useManagedMediaSource&&Uo())if(r){const m=document.createElement("source");n(m),m.type="application/x-mpegurl",m.src=r.url,this.element.appendChild(m)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const l={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency,manifest:this.manifest};if(this.videoBufferManager=new $n(ge.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,l),this.bufferManagers=[this.videoBufferManager],P(s)&&(this.audioBufferManager=new $n(ge.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,l),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Xi(Cr).subscribe(m=>{var v;if(!((v=this.element)===null||v===void 0)&&v.paused){const S=on(this.manifestUrlString,pe.DASH_CMAF_OFFSET_P);this.manifestUrlString=Me(this.manifestUrlString,S+Cr,pe.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(N(...wn.map(m=>C(this.element,m))).pipe(A(m=>this.element?zt(this.element.buffered,this.element.currentTime*1e3):0),ce(),ue(m=>!!m),fi(m=>{this.waitingEventInterval&&(window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=void 0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(ue(v=>this.isActiveLowLatency&&!!v)).subscribe(v=>this.liveEstimatedDelay.next(v))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(v=>{if(!this.isActiveLowLatency)return;const S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,E=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,w=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,$=v-S;let k=1+Math.sign($)*w;Math.abs($)<E?k=1:Math.abs($)>E*2&&(k=1+Math.sign($)*w*2),uv(this.element,k)})),this.representationSubscription.add(this.bufferLength$.subscribe(v=>{var S,E;let w=0;if(v){const $=((E=(S=this.element)===null||S===void 0?void 0:S.currentTime)!==null&&E!==void 0?E:0)*1e3;w=Math.min(...this.bufferManagers.map(H=>{var Y,K;return(K=(Y=H.getLiveSegmentsToLoadState(this.manifest))===null||Y===void 0?void 0:Y.to)!==null&&K!==void 0?K:0}))-$}w&&this.liveLoadBufferLength$.getValue()!==w&&this.liveLoadBufferLength$.next(w)}));let m=0;this.representationSubscription.add(We({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).subscribe(async({liveLoadBufferLength:v,bufferLength:S})=>{if(D(this.element),this.isUpdatingLive)return;const E=this.element.playbackRate,w=on(this.manifestUrlString,pe.DASH_CMAF_OFFSET_P),$=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,k=Math.min($,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*E),H=this.tuning.dashCmafLive.normalizedActualBufferOffset*E,Y=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*E,K=this.isActiveLowLatency?S:v;let j=Ge.None;if(this.isActiveLowLatency?j=Ge.ActiveLowLatency:K<k+Y&&K>=k?j=Ge.LiveWithTargetOffset:w!==0&&K<k&&(j=Ge.LiveForwardBuffering),isFinite(v)&&(m=v>m?v:m),j===Ge.LiveForwardBuffering||j===Ge.LiveWithTargetOffset){const J=m-(k+H),Z=this.normolizeLiveOffset(Math.trunc(w+J/E)),M=Math.abs(Z-w);let _;!v||M<=this.tuning.dashCmafLive.offsetCalculationError?_=w:Z>0&&M>this.tuning.dashCmafLive.offsetCalculationError?_=Z:_=0,this.manifestUrlString=Me(this.manifestUrlString,_,pe.DASH_CMAF_OFFSET_P)}j!==Ge.None&&j!==Ge.ActiveLowLatency&&(m=0,this.updateLive())}))}const d=N(...this.bufferManagers.map(m=>m.fullyBuffered$)).pipe(A(()=>this.bufferManagers.every(m=>m.fullyBuffered$.getValue()))),u=N(...this.bufferManagers.map(m=>m.onLastSegment$)).pipe(A(()=>this.bufferManagers.some(m=>m.onLastSegment$.getValue())));this.representationSubscription.add(N(this.forceEnded$,We({allBuffersFull:d,someBufferEnded:u}).pipe(ue(({allBuffersFull:m,someBufferEnded:v})=>m&&v))).subscribe(()=>{var m;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(v=>!v.updating))try{(m=this.source)===null||m===void 0||m.endOfStream()}catch(v){this.error$.next({id:"EndOfStream",category:I.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:v})}})),this.representationSubscription.add(N(...this.bufferManagers.map(m=>m.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield new Promise(m=>{var v;return(v=this.source)===null||v===void 0?void 0:v.addEventListener("sourceopen",m)}));const c=(a=this.manifest.duration)!==null&&a!==void 0?a:0,h=(m,v)=>{var S;return Math.max(m,(S=v.duration)!==null&&S!==void 0?S:0)},f=this.manifest.representations.audio.reduce(h,c),g=this.manifest.representations.video.reduce(h,c);(f||g)&&(this.source.duration=Math.max(f,g)/1e3),this.audioBufferManager&&P(s)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)]):yield this.videoBufferManager.startWith(t),this.state$.setState(De.REPRESENTATIOS_READY)}.bind(this)),this.tick=()=>{var t,s;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((s=this.audioBufferManager)===null||s===void 0)&&s.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=Xi(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:I.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new av({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Or.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){var t,s,r,a;D(this.element);const n=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&n===0,this.liveLastSeekOffset=n,this.isJumpGapAfterSeekLive=!0,this.manifestUrlString=Me(this.manifestUrlString,n,pe.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),this.manifest&&(await((t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((s=this.manifest)===null||s===void 0?void 0:s.representations.video)),await((r=this.audioBufferManager)===null||r===void 0?void 0:r.seekLive((a=this.manifest)===null||a===void 0?void 0:a.representations.audio)))}initBuffer(){D(this.element),this.state$.setState(De.RUNNING),this.subscription.add(N(...wn.map(e=>C(this.element,e)),C(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:I.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(C(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(C(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Lr(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime),this.waitingEventInterval&&window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=window.setInterval(this.waitingEventCallback.bind(this),this.tuning.dashMaxWaitingDuration)})),this.tick()}async switchRepresentation(e,t){const s={[ge.VIDEO]:this.videoBufferManager,[ge.AUDIO]:this.audioBufferManager,[ge.TEXT]:null}[e];return s==null?void 0:s.switchTo(t)}seek(e,t){var s,r,a,n,o;D(this.element),D(this.videoBufferManager);let l;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?l=e:l=Math.max((s=this.videoBufferManager.findSegmentStartTime(e))!==null&&s!==void 0?s:e,(a=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&a!==void 0?a:e),Lr(this.element.buffered,l)||(this.videoBufferManager.abort(),(n=this.audioBufferManager)===null||n===void 0||n.abort()),this.videoBufferManager.maintain(l),(o=this.audioBufferManager)===null||o===void 0||o.maintain(l),this.element.currentTime=l/1e3}stop(){var e,t,s;(e=this.element)===null||e===void 0||e.querySelectorAll("source").forEach(r=>r.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)===null||t===void 0||t.destroy(),this.videoBufferManager=null,(s=this.audioBufferManager)===null||s===void 0||s.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(De.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),window.clearInterval(this.waitingEventInterval),this.stop(),((e=this.source)===null||e===void 0?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}async waitingEventCallback(){try{if(!this.element)return;this.isLive$.getValue()?await this.seekLive(this.liveLastSeekOffset):this.seek(this.element.currentTime*1e3,!0)}catch(e){this.error$.next({id:"WaitingEventCallback",category:I.WTF,message:"Error in seeking in waiting event callback",thrown:e})}}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)===null||e===void 0||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);const t=this.element.currentTime*1e3,s=[];for(const r of this.bufferManagers)for(const a of r.gaps)r.playingRepresentation$.getValue()===a.representation&&a.from<=t&&a.to>t&&(this.element.duration*1e3-a.to<this.tuning.endGapTolerance?s.push(1/0):s.push(a.to));if(s.length){const r=Math.max(...s);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):Math.trunc(this.element.currentTime*1e3)!==Math.trunc(r)&&(this.element.currentTime=r/1e3)}}};class pv{constructor(e,t){this.fov=e,this.orientation=t}}class mv{constructor(e,t){this.rotating=!1,this.fading=!1,this.lastTickTS=0,this.lastCameraTurnTS=0,this.fadeStartSpeed=null,this.fadeTime=0,this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,s=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+s)}pointCameraTo(e=0,t=0,s=0){t=this.limitCameraRotationY(t);const r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,n=s-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=s,this.lastCameraTurn={x:r,y:a,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,s){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=s!=null?s:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){const e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){const t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,s){this.setRotationSpeed(e,t,s),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}const t=e-this.lastTickTS,s=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*s,this.rotationSpeed.y*this.options.rotationSpeedCorrection*s,this.rotationSpeed.z*this.options.rotationSpeedCorrection*s);else if(this.fading&&this.fadeStartSpeed){const r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*s,this.rotationSpeed.y*this.options.rotationSpeedCorrection*s,this.rotationSpeed.z*this.options.rotationSpeedCorrection*s):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var vv=`#define GLSLIFY 1
|
|
37
|
+
`}),B}return d==null||d.recordSwitch(_),_};var Qe=i=>new URL(i).hostname;const un=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))};var Ct=async i=>{const e=i.muted;try{await i.play()}catch(t){if(!un(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(s){return un(s)&&(i.muted=!1,console.warn(s)),!1}}return!0};function ye(){return ne()}function Ro(i){return ye()-i}function cn(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),s=/^([a-z]+:)?\/\//i,r=n=>s.test(n);return{resolve:(n,o,l=!1)=>{r(n)||(n.startsWith("/")||(n="/"+n),n=t+n);let d=n.indexOf("?")>-1?"&":"?";return l&&(n+=d+"lowLat=1",d="&"),o&&(n+=d+"_rnd="+Math.floor(999999999*Math.random())),n}}}function up(i,e,t){const s=(...r)=>{t.apply(null,r),i.removeEventListener(e,s)};i.addEventListener(e,s)}function Qi(i,e,t,s){const r=window.XMLHttpRequest;let a,n,o,l=!1,d=0,u,c,h=!1,f="arraybuffer",g=7e3,m=2e3,v=()=>{if(l)return;D(u);const M=Ro(u);let _;if(M<m){_=m-M,setTimeout(v,_);return}m*=2,m>g&&(m=g),n&&n.abort(),n=new r,q()};const S=M=>(a=M,Z),E=M=>(c=M,Z),$=()=>(f="json",Z),A=()=>{if(!l){if(--d>=0){v(),s&&s();return}l=!0,c&&c(),t&&t()}},P=M=>(h=M,Z),q=()=>{u=ye(),n=new r,n.open("get",i);let M=0,_,se=0;const B=()=>(D(u),Math.max(u,Math.max(_||0,se||0)));if(a&&n.addEventListener("progress",L=>{const X=ye();a.updateChunk&&L.loaded>M&&(a.updateChunk(B(),L.loaded-M),M=L.loaded,_=X)}),o&&(n.timeout=o,n.addEventListener("timeout",()=>A())),n.addEventListener("load",()=>{if(l)return;D(n);const L=n.status;if(L>=200&&L<300){if(n.response.byteLength&&a){const X=n.response.byteLength-M;X&&a.updateChunk&&a.updateChunk(B(),X)}n.responseType==="json"&&!Object.values(n.response).length?A():(c&&c(),e(n.response))}else A()}),n.addEventListener("error",()=>{A()}),h){const L=()=>{D(n),n.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(se=ye(),n.removeEventListener("readystatechange",L))};n.addEventListener("readystatechange",L)}return n.responseType=f,n.send(),Z},Z={withBitrateReporting:S,withParallel:P,withJSONResponse:$,withRetryCount:M=>(d=M,Z),withRetryInterval:(M,_)=>(k(M)&&(m=M),k(_)&&(g=_),Z),withTimeout:M=>(o=M,Z),withFinally:E,send:q,abort:()=>{n&&(n.abort(),n=void 0),l=!0,c&&c()}};return Z}const cp=100,hp=2e3,fp=500;let pp=class{constructor(e){this.intervals=[],this.currentRate=0,this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,s){return{start:e,end:t,bytes:s}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-fp;if(t-e>hp){let s=0,r=0;for(;this.intervals.length>0;){const a=this.intervals[0];if(a.end<=t)s+=a.end-a.start,r+=a.bytes,this.intervals.splice(0,1);else{if(a.start>=t)break;{const n=t-a.start,o=a.end-a.start;s+=n;const l=a.bytes*n/o;r+=l,a.start=t,a.bytes-=l}}}if(r>0&&s>0){const a=r*8/(s/1e3);return this._updateRate(a),this.logger(`rate updated, new=${Math.round(a/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(s)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,s){return this.intervals.push(this._createInterval(e,t,s)),this._joinIntervals(),this.intervals.length>cp&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};class mp{constructor(e,t,s,r,a){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=r,this.logger=a}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const s=ye(),r=l=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=l,e._errorCB?e._errorCB(l):(this.limitCompleteCount(),this.completeRequests[t]=e)},a=l=>{e._complete=1,e._responseData=l,e._downloadTime=ye()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(l,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=()=>{e._finallyCB&&e._finallyCB()},o=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Qi(t,a,()=>r("error"),o),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(n),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ye()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=ye();if(Object.keys(this.activeRequests).length>=e)return!1;const s=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),s>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),s),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,s,r){const a={};return a.send=()=>{const n=this.activeRequests[e]||this.completeRequests[e];if(n)n._cb=t,n._errorCB=s,n._retryCB=r,n._finallyCB=a._finallyCB,n._error||n._complete?(this._removeFromActive(e),setTimeout(()=>{n._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(n._responseData,n._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),s(n._errorMsg)),a._finallyCB&&a._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const o=this.pendingQueue.indexOf(e);o!==-1&&this.pendingQueue.splice(o,1),this.logger(`Request not prefetched, starting new request, url=${e}${o===-1?"":"; removed pending"}`),this._sendRequest(a,e)}},a._cb=t,a._errorCB=s,a._retryCB=r,a.abort=function(){a.request&&a.request.abort()},a.withFinally=n=>(a._finallyCB=n,a),a}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Bi=1e4,tr=3,vp=6e4,gp=10,Sp=1,bp=500;class yp{constructor(e){this.paused=!1,this.autoQuality=!0,this.maxAutoQuality=void 0,this.buffering=!0,this.destroyed=!1,this.videoPlayStarted=!1,this.lowLatency=!1,this.bitrate=0,this.manifest=[],this.sourceBuffer=0,this.bufferStates=[],this.sourceJitter=-1,this.params=e,this.chunkRateEstimator=new pp(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=cn(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let s=0;s<this.manifest.length;++s)if(t=this.manifest[s],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=cn(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const s=e.buffered.length;return s!==0&&(t=e.buffered.end(s-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var s;!!e.error&&!this.destroyed&&(t(`Video element error: ${(s=e.error)===null||s===void 0?void 0:s.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const s=this._getBufferSizeSec();!this.paused&&s<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(s+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,s=t.buffered.length;let r;s!==0&&(r=t.buffered.start(s-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let s,r,a;const n=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let o=0;o<this.manifest.length;++o)a=this.manifest[o],!(this.maxAutoQuality&&a.video.height>this.maxAutoQuality)&&(a.bitrate<e&&n>Math.min(a.video.height,a.video.width)?(!r||a.bitrate>r.bitrate)&&(r=a):(!s||s.bitrate>a.bitrate)&&(s=a));return r||s}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||k(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:s,videoElement:r,playerCallback:a}=this.params;this.mediaSource=new window.MediaSource,s("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const n=()=>{up(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),a({name:"playing"})):n()})};n()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new mp(tr,Bi,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:s,playerCallback:r}=this.params;let a=!1,n=null,o=null,l=null,d=null,u=!1;const c=()=>{const A=a&&(!u||u===this.rep);return A||t("Not running!"),A},h=(A,P,q)=>{l&&l.abort(),l=Qi(this.urlResolver.resolve(A,!1),P,q,()=>this._retryCallback()).withTimeout(Bi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(tr).withFinally(()=>{l=null}).send()},f=(A,P,q)=>{D(this.filesFetcher),o==null||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(A,!1),P,q,()=>this._retryCallback()).withFinally(()=>{o=null}).send()},g=A=>{const P=s.playbackRate;s.playbackRate!==A&&(t(`Playback rate switch: ${P}=>${A}`),s.playbackRate=A)},m=A=>{this.lowLatency=A,t(`lowLatency changed to ${A}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)g(1);else{let A=this._getBufferSizeSec();if(this.bufferStates.length<5){g(1);return}const q=ye()-1e4;let j=0;for(let G=0;G<this.bufferStates.length;G++){const J=this.bufferStates[G];A=Math.min(A,J.buf),J.ts<q&&j++}this.bufferStates.splice(0,j),t(`update playback rate; minBuffer=${A} drop=${j} jitter=${this.sourceJitter}`);let K=A-Sp;this.sourceJitter>=0?K-=this.sourceJitter/2:this.sourceJitter-=1,K>3?g(1.15):K>1?g(1.1):K>.3?g(1.05):g(1)}},S=A=>{let P;const q=()=>P&&P.start?P.start.length:0,j=L=>P.start[L]/1e3,K=L=>P.dur[L]/1e3,G=L=>P.fragIndex+L,J=(L,X)=>({chunkIdx:G(L),startTS:j(L),dur:K(L),discontinuity:X}),Z=()=>{let L=0;if(P&&P.dur){let X=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,oe=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,he=X;this.sourceJitter>1&&(he+=this.sourceJitter-1);let me=P.dur.length-1;for(;me>=0&&(he-=P.dur[me],!(he<=0));--me);L=Math.min(me,P.dur.length-1-oe),L=Math.max(L,0)}return J(L,!0)},M=L=>{const X=q();if(!(X<=0)){if(k(L)){for(let oe=0;oe<X;oe++)if(j(oe)>L)return J(oe)}return Z()}},_=L=>{const X=q(),oe=L?L.chunkIdx+1:0,he=oe-P.fragIndex;if(!(X<=0)){if(!L||he<0||he-X>gp)return t(`Resync: offset=${he} bChunks=${X} chunk=`+JSON.stringify(L)),Z();if(!(he>=X))return J(oe-P.fragIndex,!1)}},se=(L,X,oe)=>{d&&d.abort(),d=Qi(this.urlResolver.resolve(L,!0,this.lowLatency),X,oe,()=>this._retryCallback()).withTimeout(Bi).withRetryCount(tr).withFinally(()=>{d=null}).withJSONResponse().send()};return{seek:(L,X)=>{se(A,oe=>{if(!c())return;P=oe;const he=!!P.lowLatency;he!==this.lowLatency&&m(he);let me=0;for(let Fe=0;Fe<P.dur.length;++Fe)me+=P.dur[Fe];me>0&&(D(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(me/P.dur.length)),r({name:"index",zeroTime:P.zeroTime,shiftDuration:P.shiftDuration}),this.sourceJitter=P.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,P.jitter/1e3)):1,L(M(X))},()=>this._handleNetworkError())},nextChunk:_}},E=()=>{a=!1,o&&o.abort(),l&&l.abort(),d&&d.abort(),D(this.filesFetcher),this.filesFetcher.abortAll()};return u={start:A=>{const{videoElement:P,logger:q}=this.params;let j=S(e.jidxUrl),K,G,J,Z,M=0,_,se,B;const L=()=>{_&&(clearTimeout(_),_=void 0);const W=Math.max(bp,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Se=M+W,Te=ye(),we=Math.min(1e4,Se-Te);M=Te;const Mt=()=>{d||c()&&j.seek(()=>{c()&&(M=ye(),X(),L())})};we>0?_=window.setTimeout(()=>{this.paused?L():Mt()},we):Mt()},X=()=>{let W;for(;W=j.nextChunk(Z);)Z=W,si(W);const Se=j.nextChunk(J);if(Se){if(J&&Se.discontinuity){q("Detected discontinuity; restarting playback"),this.paused?L():(E(),this._initPlayerWith(e));return}Fe(Se)}else L()},oe=(W,Se)=>{if(!c()||!this.sourceBuffer)return;let Te,we,Mt;const ri=Ke=>{window.setTimeout(()=>{c()&&oe(W,Se)},Ke)};if(this.sourceBuffer.updating)q("Source buffer is updating; delaying appendBuffer"),ri(100);else{const Ke=ye(),ke=P.currentTime;!this.paused&&P.buffered.length>1&&se===ke&&Ke-B>500&&(q("Stall suspected; trying to fix"),this._fixupStall()),se!==ke&&(se=ke,B=Ke);const Bt=this._getBufferSizeSec();if(Bt>30)q(`Buffered ${Bt} seconds; delaying appendBuffer`),ri(2e3);else try{this.sourceBuffer.appendBuffer(W),this.videoPlayStarted?(this.bufferStates.push({ts:Ke,buf:Bt}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Se&&Se()}catch(ai){if(ai.name==="QuotaExceededError")q("QuotaExceededError; delaying appendBuffer"),Mt=this.sourceBuffer.buffered.length,Mt!==0&&(Te=this.sourceBuffer.buffered.start(0),we=ke,we-Te>4&&this.sourceBuffer.remove(Te,we-3)),ri(1e3);else throw ai}}},he=()=>{G&&K&&(q([`Appending chunk, sz=${G.byteLength}:`,JSON.stringify(J)]),oe(G,function(){G=null,X()}))},me=W=>e.fragUrlTemplate.replace("%%id%%",W.chunkIdx),Fe=W=>{c()&&f(me(W),(Se,Te)=>{if(c()){if(Te/=1e3,G=Se,J=W,n=W.startTS,Te){const we=Math.min(10,W.dur/Te);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*we:we}he()}},()=>this._handleNetworkError())},si=W=>{c()&&(D(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(me(W),!1)))},Ot=W=>{c()&&(e.cachedHeader=W,oe(W,()=>{K=!0,he()}))};a=!0,j.seek(W=>{if(c()){if(M=ye(),!W){L();return}Z=W,!Q(A)||W.startTS>A?Fe(W):(J=W,X())}},A),e.cachedHeader?Ot(e.cachedHeader):h(e.headerUrl,Ot,()=>this._handleNetworkError())},stop:E,getTimestampSec:()=>n},u}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),k(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,D(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),s({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return k(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=c=>{if(!this.autoQuality)return;let h,f,g;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&c<this.bitrate&&(f=this._getBufferSizeSec(),g=c/this.bitrate,f>10&&g>.8||f>15&&g>.5||f>20&&g>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(c)}`);return}h=this._selectQuality(c),h?this._switchToQuality(h):e(`Could not find quality by bitrate ${c}`)},a=(()=>({updateChunk:(h,f)=>{const g=ye();if(this.chunkRateEstimator.addInterval(h,g,f)){const v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:g-h,speed:v}),!0}},get:()=>{const h=this.chunkRateEstimator.getBitRate();return h?h*.85:0}}))();let n=-1/0,o,l=!0;const d=()=>{let c=a.get();if(c&&o&&this.autoQuality){if(l&&c>o&&Ro(n)<3e4)return;s(c)}l=this.autoQuality};return{updateChunk:(c,h)=>{const f=a.updateChunk(c,h);return f&&d(),f},notifySwitch:c=>{const h=ye();c<o&&(n=h),o=c}}}_fetchManifest(e,t,s){this.manifestRequest=Qi(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(Bi).withRetryCount(this.params.config.manifestRetryMaxCount).withRetryInterval(this.params.config.manifestRetryInterval,this.params.config.manifestRetryMaxInterval).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;Ct(t).then(s=>{s||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,videoElement:r}=this.params,a=n=>{const o=[];return n!=null&&n.length?(n.forEach((l,d)=>{l.video&&r.canPlayType(l.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(l.codecs)&&(l.index=d,o.push(l))}),o.sort(function(l,d){return l.video&&d.video?d.video.height-l.video.height:d.bitrate-l.bitrate}),o):(s({name:"error",type:"empty_manifest"}),[])};this.manifest=a(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),s({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},vp))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}class Lo{constructor(){this.onDroopedVideoFramesLimit$=new x,this.subscription=new ie,this.playing=!1,this.tracks=[],this.forceChecker$=new x,this.isForceCheckCounter=0,this.prevTotalVideoFrames=0,this.prevDroppedVideoFrames=0,this.limitCounts={},this.handleChangeVideoQuality=()=>{const e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!kt(e.quality)&&this.onChangeQuality(e.quality)},this.checkDroppedFrames=()=>{var e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality(),r=t-this.prevTotalVideoFrames,a=s-this.prevDroppedVideoFrames,n=1-(r-a)/r;!isNaN(n)&&n>0&&this.log({message:`[dropped]. current dropped percent: ${n}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(n)&&n>=this.droppedFramesChecker.percentLimit&&Kt(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((e=this.limitCounts[this.currentQuality])!==null&&e!==void 0?e:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(t,s)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(C(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=Xi(this.droppedFramesChecker.checkTime).pipe(ue(()=>this.playing),ue(()=>{const r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(ze(this.droppedFramesChecker.checkTime)),s=N(e,t);this.subscription.add(s.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,s),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var t,s;const r=(s=(t=Object.entries(this.limitCounts).filter(([,a])=>a>=this.droppedFramesChecker.countLimit).sort(([a],[n])=>Yi(a,n)?-1:1))===null||t===void 0?void 0:t[0])===null||s===void 0?void 0:s[0];return e!=null?e:r}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}}var U;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(U||(U={}));const Tp=[U.PAUSED,U.PLAYING,U.READY],Ep=[U.PAUSED,U.PLAYING,U.READY];class $p{constructor(e){this.subscription=new ie,this.videoState=new le(U.STOPPED),this.representations$=new b([]),this.textTracksManager=new ft,this.droppedFramesManager=new Lo,this.maxSeekBackTime$=new b(1/0),this.zeroTime$=new b(void 0),this.liveOffset=new Xr,this._dashCb=r=>{var a,n,o,l;switch(r.name){case"buffering":{const d=r.isBuffering;this.params.output.isBuffering$.next(d);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:I.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const d=r.manifest,u=[];for(const c of d){const h=(a=c.name)!==null&&a!==void 0?a:c.index.toString(10),f=(n=vs(c.name))!==null&&n!==void 0?n:At(c.video),g=c.bitrate/1e3,m={...c.video};if(!f)continue;const v={id:h,quality:f,bitrate:g,size:m};u.push({track:v,representation:c})}this.representations$.next(u),this.params.output.availableVideoTracks$.next(u.map(({track:c})=>c)),((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===U.MANIFEST_READY&&this.videoState.setState(U.MANIFEST_READY);break}case"qualitySwitch":{const d=r.quality,u=(l=this.representations$.getValue().find(({representation:c})=>c===d))===null||l===void 0?void 0:l.track;this.params.output.hostname$.next(new URL(d.headerUrl,this.params.source.url).hostname),k(u)&&this.params.output.currentVideoTrack$.next(u);break}case"bandwidth":{const{size:d,duration:u}=r;this.params.dependencies.throughputEstimator.addRawSpeed(d,u);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration||0),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{const r=this.videoState.getState(),a=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${r}; videoTransition: ${JSON.stringify(a)}; desiredPlaybackState: ${n}; seekState: ${JSON.stringify(l)};`}),n===p.STOPPED){r!==U.STOPPED&&(this.videoState.startTransitionTo(U.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(U.STOPPED));return}if(a)return;const d=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Ep.includes(r)&&(d||u)){this.prepare();return}if((o==null?void 0:o.to)!==p.PAUSED&&l.state===Y.Requested&&Tp.includes(r)){this.seek(l.position-this.liveOffset.getTotalPausedTime());return}switch(r){case U.STOPPED:this.videoState.startTransitionTo(U.MANIFEST_READY),this.dash.attachSource(Me(this.params.source.url));return;case U.MANIFEST_READY:this.videoState.startTransitionTo(U.READY),this.prepare();break;case U.READY:if(n===p.PAUSED)this.videoState.setState(U.PAUSED);else if(n===p.PLAYING){this.videoState.startTransitionTo(U.PLAYING);const c=o==null?void 0:o.from;c&&c===p.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(U.PAUSED)})}return;case U.PLAYING:n===p.PAUSED&&(this.videoState.startTransitionTo(U.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case U.PAUSED:if(n===p.PLAYING)if(this.videoState.startTransitionTo(U.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(U.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let c=this.liveOffset.getTotalOffset();c>=this.maxSeekBackTime$.getValue()&&(c=0,this.liveOffset.resetTo(c)),this.liveOffset.resume(),this.params.output.position$.next(-c/1e3),this.dash.reinit(Me(this.params.source.url,c))}return;default:return H(r)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:I.WTF,message:"DashLiveProvider internal logic error",thrown:r})};N(this.videoState.stateChangeStarted$.pipe(w(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(w(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:a})=>{this.log({message:`[videoState change] ${a}: ${JSON.stringify(r)}`})}),this.video=Lt(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Qe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=_t(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:s.playing$,pause$:s.pause$,tracks$:this.representations$.pipe(w(r=>r.map(({track:a})=>a)))}),this.subscription.add(s.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===U.READY&&this.videoState.setState(U.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(U.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===Y.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(U.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(ce(),w(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(We({zeroTime:this.zeroTime$.pipe(ue(k)),position:s.timeUpdate$}).subscribe(({zeroTime:r,position:a})=>this.params.output.liveTime$.next(r+a*1e3),t)).add(Ti(this.video,this.params.desiredState.isLooped,t)).add(xt(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(ii(this.video,this.params.desiredState.playbackRate,s.playbackRateState$,t)).add(s.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(s.playing$.subscribe(this.params.output.firstFrameEvent$)).add(s.canplay$.subscribe(this.params.output.canplay$)).add(s.inPiP$.subscribe(this.params.output.inPiP$)).add(s.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{const a=r&&pd(r);this.dash.setMaxAutoQuality(a),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var a;switch(r.to){case U.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(p.STOPPED);break;case U.MANIFEST_READY:case U.READY:((a=this.params.desiredState.playbackState.getTransition())===null||a===void 0?void 0:a.to)===p.READY&&this.params.desiredState.playbackState.setState(p.READY);break;case U.PAUSED:this.params.desiredState.playbackState.setState(p.PAUSED);break;case U.PLAYING:this.params.desiredState.playbackState.setState(p.PLAYING);break;default:return H(r.to)}},t)).add(N(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,Le(["init"])).pipe(ze(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),It(this.video)}createLiveDashPlayer(){const e=new yp({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode,manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,s,r,a,n;const o=this.representations$.getValue(),l=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),d=(r=(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||s===void 0?void 0:s.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),u=!d&&k(l)?l:gs(o.map(({track:m})=>m),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),c=u==null?void 0:u.id,h=this.params.desiredState.videoTrack.getTransition(),f=(a=this.params.desiredState.videoTrack.getState())===null||a===void 0?void 0:a.id,g=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&(h||c!==f)&&this.setVideoTrack(u),g&&this.setAutoQuality(d),h||g||c!==f){const m=(n=o.find(({track:v})=>v.id===c))===null||n===void 0?void 0:n.representation;D(m,"Representations missing"),this.dash.startPlay(m,d)}}setVideoTrack(e){var t;const s=(t=this.representations$.getValue().find(({track:r})=>r.id===e.id))===null||t===void 0?void 0:t.representation;D(s,`No such representation ${e.id}`),this.dash.switchByName(s.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),r=t===p.PAUSED&&s===U.PAUSED,a=-e,n=a<=this.maxSeekBackTime$.getValue()?a:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Me(this.params.source.url,n)),r&&this.dash.pause(),this.liveOffset.resetTo(n,r)}}var ge;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(ge||(ge={}));var Ge;(function(i){i[i.ActiveLowLatency=0]="ActiveLowLatency",i[i.LiveWithTargetOffset=1]="LiveWithTargetOffset",i[i.LiveForwardBuffering=2]="LiveForwardBuffering",i[i.None=3]="None"})(Ge||(Ge={}));var ss;(function(i){i.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",i.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(ss||(ss={}));var Re;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(Re||(Re={}));var V;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(V||(V={}));var Xt;(function(i){i.MP4="mp4",i.WEBM="webm"})(Xt||(Xt={}));var rs;(function(i){i[i.RECTANGULAR=0]="RECTANGULAR",i[i.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",i[i.CUBEMAP=2]="CUBEMAP",i[i.MESH=3]="MESH"})(rs||(rs={}));var ae;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(ae||(ae={}));var Wt=(i,e)=>{let t=0;for(let s=0;s<i.length;s++){const r=i.start(s)*1e3,a=i.end(s)*1e3;r<=e&&e<=a&&(t=a)}return Math.max(t-e,0)};const wp=300,Ap=(i,e=wp)=>new os(t=>{const{width:s,height:r}=i.getBoundingClientRect();if(t.next({width:s,height:r}),!window.ResizeObserver)return;const a=new ResizeObserver(md(n=>{const o=n[0];if(!o)return;let l,d;o.contentBoxSize&&o.contentBoxSize[0]?(d=o.contentBoxSize[0].blockSize,l=o.contentBoxSize[0].inlineSize):o.contentRect&&(l=o.contentRect.width,d=o.contentRect.height),k(l)&&k(d)&&t.next({width:l,height:d})},e));return a.observe(i),()=>a.disconnect()});class hn{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}removeEventListener(e,t){if(!(e in this.listeners))return;const s=this.listeners[e];for(let r=0,a=s.length;r<a;r++)if(s[r].callback===t){s.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let r=0,a=s.length;r<a;r++){const n=s[r];try{n.callback.call(this,e)}catch(o){Promise.resolve().then(()=>{throw o})}n.options&&n.options.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}}class Io extends hn{constructor(){super(),this.listeners||hn.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}let xo=class{constructor(){Object.defineProperty(this,"signal",{value:new Io,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let s=e;if(s===void 0)if(typeof document=="undefined")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch(r){s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(xo.prototype[Symbol.toStringTag]="AbortController",Io.prototype[Symbol.toStringTag]="AbortSignal");function _o(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function kp(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!_o({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=t;(a&&!a.prototype.hasOwnProperty("signal")||r)&&(a=function(d,u){let c;u&&u.signal&&(c=u.signal,delete u.signal);const h=new t(d,u);return c&&Object.defineProperty(h,"signal",{writable:!1,enumerable:!1,configurable:!0,value:c}),h},a.prototype=t.prototype);const n=e;return{fetch:(l,d)=>{const u=a&&a.prototype.isPrototypeOf(l)?l.signal:d?d.signal:void 0;if(u){let c;try{c=new DOMException("Aborted","AbortError")}catch(f){c=new Error("Aborted"),c.name="AbortError"}if(u.aborted)return Promise.reject(c);const h=new Promise((f,g)=>{u.addEventListener("abort",()=>g(c),{once:!0})});return d&&d.signal&&delete d.signal,Promise.race([h,n(l,d)])}return n(l,d)},Request:a}}const Ss=_o({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Co=Ss?kp({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,vi=Ss?Co.fetch:window.fetch;Ss?Co.Request:window.Request;const Jt=Ss?xo:window.AbortController;var Lr=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};const Pp=(i,e={})=>{const s=e.timeout||1,r=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-r-1>s},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},Dp=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",fn=Dp?Pp:window.requestIdleCallback;var ir,sr;const Rp=16;let Oo=!1;try{Oo=Mr().browser===Bn.Safari&&parseInt((sr=(ir=navigator.userAgent.match(/Version\/(\d+)/))===null||ir===void 0?void 0:ir[1])!==null&&sr!==void 0?sr:"",10)<=Rp}catch(i){console.error(i)}class Lp{constructor(e){this.bufferFull$=new x,this.error$=new x,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const s=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!s),this.currentTask=null}this.queue.length&&this.pull()}catch(s){this.error$.next({id:"BufferTaskQueueUnknown",category:I.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:s})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(s=>{const r={operation:"append",data:e,signal:t,callback:s};this.queue.push(r),this.pull()})}async remove(e,t,s){return s&&s.aborted?!1:new Promise(r=>{const a={operation:"remove",from:e,to:t,signal:s,callback:r};this.queue.unshift(a),this.pull()})}async abort(e){return new Promise(t=>{let s;Oo&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);s&&(this.queue=[s]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:s}=this.currentTask;try{this.execute(this.currentTask)}catch(a){a instanceof DOMException&&a.name==="QuotaExceededError"&&s==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):a instanceof DOMException&&a.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${s}`,category:I.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:a}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:H(t)}}}var pn=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};class xe{get id(){return this.type}get size(){return this.size32}constructor(e){this.cursor=0,this.source=e,this.children=[];const t=this.readUint32();this.size32=t<=e.buffer.byteLength?t:NaN,this.type=this.readString(4),this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,e.byteOffset+this.cursor,this.size32?this.size32-8:void 0),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}readString(e,t="ascii"){const r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){const e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){const e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){const e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){const e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}}class Mo extends xe{}class Ip extends xe{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const s=this.readString(4);this.compatibleBrands.push(s),t-=4}}}class xp extends xe{parseChildrenBoxes(){return pt(this.content)}}class _p extends xe{parseChildrenBoxes(){return pt(this.content)}}class Cp extends xe{constructor(e){super(e),this.data=this.content}}class ot extends xe{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class Op extends ot{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let s=this.readUint32();const r=s>>>31,a=s<<1>>>1,n=this.readUint32();s=this.readUint32();const o=s>>>28,l=s<<3>>>3;this.segments.push({referenceType:r,referencedSize:a,subsegmentDuration:n,SAPType:o,SAPDeltaTime:l})}}}class Mp extends xe{parseChildrenBoxes(){return pt(this.content)}}class Bp extends xe{parseChildrenBoxes(){return pt(this.content)}}var wt;(function(i){i[i.MONOSCOPIC=0]="MONOSCOPIC",i[i.TOP_BOTTOM=1]="TOP_BOTTOM",i[i.LEFT_RIGHT=2]="LEFT_RIGHT",i[i.STEREO_CUSTOM=3]="STEREO_CUSTOM",i[i.RIGHT_LEFT=4]="RIGHT_LEFT"})(wt||(wt={}));class Np extends ot{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=wt.MONOSCOPIC;break;case 1:this.stereoMode=wt.TOP_BOTTOM;break;case 2:this.stereoMode=wt.LEFT_RIGHT;break;case 3:this.stereoMode=wt.STEREO_CUSTOM;break;case 4:this.stereoMode=wt.RIGHT_LEFT;break}this.cursor+=1}}class Fp extends ot{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class Vp extends ot{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class Up extends xe{parseChildrenBoxes(){return pt(this.content)}}class Hp extends ot{constructor(e){super(e),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}}class Gp extends xe{parseChildrenBoxes(){return pt(this.content)}}class Yp extends xe{parseChildrenBoxes(){return pt(this.content)}}class qp extends ot{constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class jp extends xe{parseChildrenBoxes(){return pt(this.content)}}class zp extends ot{constructor(e){super(e),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}}class Wp extends ot{get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e){super(e),this.baseMediaDecodeTime32=0,this.baseMediaDecodeTime64=BigInt(0),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class Qp extends ot{constructor(e){super(e),this.sampleDuration=[],this.sampleSize=[],this.sampleFlags=[],this.sampleCompositionTimeOffset=[],this.optionalFields=0,this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let t=0;t<this.sampleCount;t++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}}const Kp={ftyp:Ip,moov:xp,moof:_p,mdat:Cp,sidx:Op,trak:Mp,mdia:Up,mfhd:qp,tkhd:Hp,traf:jp,tfhd:zp,tfdt:Wp,trun:Qp,minf:Gp,sv3d:Bp,st3d:Np,prhd:Fp,proj:Yp,equi:Vp,unknown:Mo};class Jp{createBox(e,t){const s=Kp[e];return s?new s(t):new Mo(t)}createFromView(e){const s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return bs.createBox(s,new DataView(e.buffer,e.byteOffset))}}const bs=new Jp;function hi(i,e){const t=new Uint8Array(i.buffer),s=e.split("").map(n=>n.charCodeAt(0));let r=i.byteOffset,a=[];for(;r<t.byteLength;){if(t[r]===s[a.length]?a.push(t[r]):a.length&&(a=[],r--),a.length===4){const o=new DataView(i.buffer,r-7,4).getUint32(0);return r-7+o>i.buffer.byteLength?null:bs.createBox(e,new DataView(i.buffer,r-7))}r++}return null}function Ir(i,e){const t=[];let s=i.byteOffset;for(;s<i.buffer.byteLength;){const r=hi(new DataView(i.buffer,s,i.buffer.byteLength-s),e);if(r)t.push(r),s=r.source.byteOffset+r.size;else break}return t}function pt(i){const e=[];let t=0;for(;t<i.byteLength;){const s=bs.createFromView(new DataView(i.buffer,i.byteOffset+t));if(e.push(s),!s.size)break;t+=s.size}return e}const Xp=new TextDecoder("ascii"),Zp=i=>Xp.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",em=i=>{const e=bs.createFromView(i);let t=e.earliestPresentationTime/e.timescale*1e3,s=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(a=>{if(a.referenceType!==0)throw new Error("Unsupported multilevel sidx");const n=a.subsegmentDuration/e.timescale*1e3,o={status:V.NONE,time:{from:t,to:t+n},byte:{from:s,to:s+a.referencedSize-1}};return t+=n,s+=a.referencedSize,o})},tm=i=>{const e=Ir(i,"mdat"),t=Ir(i,"moof");if(!(e.length&&t.length))return null;const s=t[0],r=e[e.length-1],a=s.source.byteOffset,o=r.source.byteOffset-s.source.byteOffset+r.size;return new DataView(i.buffer,a,o)},im=(i,e)=>{const t=Ir(i,"traf"),s=t[t.length-1].children.find(l=>l.type==="tfhd"),r=t[t.length-1].children.find(l=>l.type==="tfdt"),a=t[t.length-1].children.find(l=>l.type==="trun");let n=0;return a.sampleDuration.length?n=a.sampleDuration.reduce((l,d)=>l+d,0):n=s.defaultSampleDuration*a.sampleCount,(Number(r.baseMediaDecodeTime)+n)/e*1e3},sm=i=>{const e={is3dVideo:!1,stereoMode:0,projectionType:rs.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(hi(i,"sv3d")){e.is3dVideo=!0;const s=hi(i,"st3d");s&&(e.stereoMode=s.stereoMode);const r=hi(i,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const a=hi(i,"equi");a&&(e.projectionData.bounds.top=a.projectionBoundsTop,e.projectionData.bounds.right=a.projectionBoundsRight,e.projectionData.bounds.bottom=a.projectionBoundsBottom,e.projectionData.bounds.left=a.projectionBoundsLeft)}return e},rm={validateData:Zp,parseInit:sm,getIndexRange:()=>{},parseSegments:em,parseFeedableSegmentChunk:tm,getSegmentEndTime:im};var T;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.TrackEntry=174]="TrackEntry",i[i.Video=224]="Video",i[i.Projection=30320]="Projection",i[i.ProjectionType=30321]="ProjectionType",i[i.ProjectionPrivate=30322]="ProjectionPrivate",i[i.Chapters=272869232]="Chapters",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.SilentTracks=22612]="SilentTracks",i[i.SilentTrackNumber=22743]="SilentTrackNumber",i[i.Position=167]="Position",i[i.PrevSize=171]="PrevSize",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.EncryptedBlock=175]="EncryptedBlock",i[i.Attachments=423732329]="Attachments",i[i.Tags=307544935]="Tags",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.CueRelativePosition=240]="CueRelativePosition",i[i.CueDuration=178]="CueDuration",i[i.CueBlockNumber=21368]="CueBlockNumber",i[i.CueCodecState=234]="CueCodecState",i[i.CueReference=219]="CueReference",i[i.CueRefTime=150]="CueRefTime"})(T||(T={}));var R;(function(i){i.SignedInteger="int",i.UnsignedInteger="uint",i.Float="float",i.String="string",i.UTF8="utf8",i.Date="date",i.Master="master",i.Binary="binary"})(R||(R={}));const mn={[T.EBML]:{type:R.Master},[T.EBMLVersion]:{type:R.UnsignedInteger},[T.EBMLReadVersion]:{type:R.UnsignedInteger},[T.EBMLMaxIDLength]:{type:R.UnsignedInteger},[T.EBMLMaxSizeLength]:{type:R.UnsignedInteger},[T.DocType]:{type:R.String},[T.DocTypeVersion]:{type:R.UnsignedInteger},[T.DocTypeReadVersion]:{type:R.UnsignedInteger},[T.Void]:{type:R.Binary},[T.Segment]:{type:R.Master},[T.SeekHead]:{type:R.Master},[T.Seek]:{type:R.Master},[T.SeekID]:{type:R.Binary},[T.SeekPosition]:{type:R.UnsignedInteger},[T.Info]:{type:R.Master},[T.TimestampScale]:{type:R.UnsignedInteger},[T.Duration]:{type:R.Float},[T.Tracks]:{type:R.Master},[T.TrackEntry]:{type:R.Master},[T.Video]:{type:R.Master},[T.Projection]:{type:R.Master},[T.ProjectionType]:{type:R.UnsignedInteger},[T.ProjectionPrivate]:{type:R.Master},[T.Chapters]:{type:R.Master},[T.Cluster]:{type:R.Master},[T.Timestamp]:{type:R.UnsignedInteger},[T.SilentTracks]:{type:R.Master},[T.SilentTrackNumber]:{type:R.UnsignedInteger},[T.Position]:{type:R.UnsignedInteger},[T.PrevSize]:{type:R.UnsignedInteger},[T.SimpleBlock]:{type:R.Binary},[T.BlockGroup]:{type:R.Master},[T.EncryptedBlock]:{type:R.Binary},[T.Attachments]:{type:R.Master},[T.Tags]:{type:R.Master},[T.Cues]:{type:R.Master},[T.CuePoint]:{type:R.Master},[T.CueTime]:{type:R.UnsignedInteger},[T.CueTrackPositions]:{type:R.Master},[T.CueTrack]:{type:R.UnsignedInteger},[T.CueClusterPosition]:{type:R.UnsignedInteger},[T.CueRelativePosition]:{type:R.UnsignedInteger},[T.CueDuration]:{type:R.UnsignedInteger},[T.CueBlockNumber]:{type:R.UnsignedInteger},[T.CueCodecState]:{type:R.UnsignedInteger},[T.CueReference]:{type:R.Master},[T.CueRefTime]:{type:R.UnsignedInteger}},Bo=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const s=as(i,t),r=s in mn,a=r?mn[s].type:R.Binary,n=i.getUint8(t);let o=0;n&128?o=1:n&64?o=2:n&32?o=3:n&16?o=4:n&8?o=5:n&4?o=6:n&2?o=7:n&1&&(o=8);const l=new DataView(i.buffer,i.byteOffset+t+1,o-1),d=n&255>>o,u=as(l),c=d*2**((o-1)*8)+u,h=t+o;let f;return h+c>i.byteLength?f=new DataView(i.buffer,i.byteOffset+h):f=new DataView(i.buffer,i.byteOffset+h,c),{tag:r?s:"0x"+s.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+c,value:f,valueSize:c}},as=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*2**16+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*2**32+i.getUint32(1);case 6:return i.getUint16(0)*2**32+i.getUint32(2);case 7:{const t=i.getUint8(0)*281474976710656+i.getUint16(1)*4294967296+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},qe=(i,e)=>{switch(e){case R.SignedInteger:return i.getInt8(0);case R.UnsignedInteger:return as(i);case R.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case R.String:return new TextDecoder("ascii").decode(i);case R.UTF8:return new TextDecoder("utf-8").decode(i);case R.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case R.Master:return i;case R.Binary:return i;default:H(e)}},Zt=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),r=Bo(s);if(!e(r))return;r.type===R.Master&&Zt(r.value,e),t=r.value.byteOffset-i.byteOffset+r.valueSize}},am=i=>{if(i.getUint32(0)!==T.EBML)return!1;let e,t,s;const r=Bo(i);return Zt(r.value,({tag:a,type:n,value:o})=>(a===T.EBMLReadVersion?e=qe(o,n):a===T.DocType?t=qe(o,n):a===T.DocTypeReadVersion&&(s=qe(o,n)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},No=[T.Info,T.SeekHead,T.Tracks,T.TrackEntry,T.Video,T.Projection,T.ProjectionType,T.ProjectionPrivate,T.Chapters,T.Cluster,T.Cues,T.Attachments,T.Tags],nm=[T.Timestamp,T.SilentTracks,T.SilentTrackNumber,T.Position,T.PrevSize,T.SimpleBlock,T.BlockGroup,T.EncryptedBlock],om=i=>{let e,t,s,r,a=!1,n=!1,o=!1,l,d,u=!1;const c=0;return Zt(i,({tag:h,type:f,value:g,valueSize:m})=>{if(h===T.SeekID){const v=qe(g,f);d=as(v)}else h!==T.SeekPosition&&(d=void 0);return h===T.Segment?(e=g.byteOffset,t=g.byteOffset+m):h===T.Info?a=!0:h===T.SeekHead?n=!0:h===T.TimestampScale?s=qe(g,f):h===T.Duration?r=qe(g,f):h===T.SeekPosition&&d===T.Cues?l=qe(g,f):h===T.Tracks?Zt(g,({tag:v,type:S,value:E})=>v===T.ProjectionType?(u=qe(E,S)===1,!1):!0):a&&n&&No.includes(h)&&(o=!0),!o}),D(e,"Failed to parse webm Segment start"),D(t,"Failed to parse webm Segment end"),D(r,"Failed to parse webm Segment duration"),s=s!=null?s:1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(t/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(r/1e9*s*1e3),cuesSeekPosition:l,is3dVideo:u,stereoMode:c,projectionType:rs.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},dm=i=>{if(Q(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},lm=(i,e)=>{let t=!1,s=!1;const r=o=>k(o.time)&&k(o.position),a=[];let n;return Zt(i,({tag:o,type:l,value:d})=>{switch(o){case T.Cues:t=!0;break;case T.CuePoint:n&&r(n)&&a.push(n),n={};break;case T.CueTime:n&&(n.time=qe(d,l));break;case T.CueTrackPositions:break;case T.CueClusterPosition:n&&(n.position=qe(d,l));break;default:t&&No.includes(o)&&(s=!0)}return!(t&&s)}),n&&r(n)&&a.push(n),a.map((o,l)=>{const{time:d,position:u}=o,c=a[l+1];return{status:V.NONE,time:{from:d,to:c?c.time:e.segmentDuration},byte:{from:e.segmentStart+u,to:c?e.segmentStart+c.position-1:e.segmentEnd-1}}})},um=i=>{let e=0,t=!1;try{Zt(i,s=>s.tag===T.Cluster?s.tagSize<=i.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):nm.includes(s.tag)?(e+s.tagSize<=i.byteLength&&(e+=s.tagSize,t||(t=[T.SimpleBlock,T.BlockGroup,T.EncryptedBlock].includes(s.tag))),!0):!1)}catch(s){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},cm={validateData:am,parseInit:om,getIndexRange:dm,parseSegments:lm,parseFeedableSegmentChunk:um};var hm=Pt,fm=ls,pm=Ne,mm=pm("match"),vm=function(i){var e;return hm(i)&&((e=i[mm])!==void 0?!!e:fm(i)=="RegExp")},gm=ms,Sm=String,bm=function(i){if(gm(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return Sm(i)},ym=Rt,Tm=function(){var i=ym(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e},Em=at,$m=nt,wm=Ur,Am=Tm,vn=RegExp.prototype,km=function(i){var e=i.flags;return e===void 0&&!("flags"in vn)&&!$m(i,"flags")&&wm(vn,i)?Em(Am,i):e},ea=rt,Pm=hs,Dm=Math.floor,rr=ea("".charAt),Rm=ea("".replace),ar=ea("".slice),Lm=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Im=/\$([$&'`]|\d{1,2})/g,xm=function(i,e,t,s,r,a){var n=t+i.length,o=s.length,l=Im;return r!==void 0&&(r=Pm(r),l=Lm),Rm(a,l,function(d,u){var c;switch(rr(u,0)){case"$":return"$";case"&":return i;case"`":return ar(e,0,t);case"'":return ar(e,n);case"<":c=r[ar(u,1,-1)];break;default:var h=+u;if(h===0)return d;if(h>o){var f=Dm(h/10);return f===0?d:f<=o?s[f-1]===void 0?rr(u,1):s[f-1]+rr(u,1):d}c=s[h-1]}return c===void 0?"":c})},_m=ps,Cm=at,ta=rt,gn=Nr,Om=Ie,Mm=us,Bm=vm,Yt=bm,Nm=cs,Fm=km,Vm=xm,Um=Ne,Hm=Um("replace"),Gm=TypeError,Fo=ta("".indexOf),Ym=ta("".replace),Sn=ta("".slice),qm=Math.max,bn=function(i,e,t){return t>i.length?-1:e===""?t:Fo(i,e,t)};_m({target:"String",proto:!0},{replaceAll:function(e,t){var s=gn(this),r,a,n,o,l,d,u,c,h,f=0,g=0,m="";if(!Mm(e)){if(r=Bm(e),r&&(a=Yt(gn(Fm(e))),!~Fo(a,"g")))throw Gm("`.replaceAll` does not allow non-global regexes");if(n=Nm(e,Hm),n)return Cm(n,e,s,t);if(r)return Ym(Yt(s),e,t)}for(o=Yt(s),l=Yt(e),d=Om(t),d||(t=Yt(t)),u=l.length,c=qm(1,u),f=bn(o,l,0);f!==-1;)h=d?Yt(t(l,f,o)):Vm(l,o,f,[],void 0,t),m+=Sn(o,g,f)+h,g=f+u,f=bn(o,l,f+c);return g<o.length&&(m+=Sn(o,g)),m}});var jm=Do,zm=jm("String","replaceAll"),Wm=zm,Qm=Wm,Km=Qm,Jm=Km,yn=Br(Jm);const Xm=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)},Tn=i=>{if(!i.startsWith("P"))return;const e=(n,o)=>{const l=n?parseFloat(n.replace(",",".")):NaN;return(isNaN(l)?0:l)*o},s=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),r=(s==null?void 0:s[1])==="-"?-1:1,a={days:e(s==null?void 0:s[5],r),hours:e(s==null?void 0:s[6],r),minutes:e(s==null?void 0:s[7],r),seconds:e(s==null?void 0:s[8],r)};return a.days*24*60*60*1e3+a.hours*60*60*1e3+a.minutes*60*1e3+a.seconds*1e3},jt=(i,e)=>{let t=i;t=yn(t,"$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,a]of Object.entries(s)){const n=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=yn(t,n,(o,l)=>Q(a)?o:Q(l)?a:a.padStart(parseInt(l,10),"0"))}return t},Zm=(i,e)=>{var t,s,r,a,n,o,l,d,u,c,h,f,g,m,v,S,E,$,A,P,q,j,K,G,J,Z,M,_,se,B,L,X,oe,he,me,Fe,si,Ot,W,Se,Te,we;const ri=new DOMParser().parseFromString(i,"application/xml"),Ke={video:[],audio:[],text:[]},ke=ri.children[0],Bt=ke.getElementsByTagName("Period")[0],ai=(r=(s=(t=ke.querySelector("BaseURL"))===null||t===void 0?void 0:t.textContent)===null||s===void 0?void 0:s.trim())!==null&&r!==void 0?r:"",jo=Bt.children,zo=ke.getAttribute("type")==="dynamic",ra=ke.getAttribute("availabilityStartTime"),Wo=ra?new Date(ra).getTime():void 0;let mt;const aa=ke.getAttribute("mediaPresentationDuration"),na=Bt.getAttribute("duration"),ys=ke.getElementsByTagName("vk:Attrs")[0],oa=ys==null?void 0:ys.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(aa)mt=Tn(aa);else if(na){const _e=Tn(na);k(_e)&&(mt=_e)}else oa&&(mt=parseInt(oa,10));let Qo=0;const Ts=(n=(a=ke.getAttribute("profiles"))===null||a===void 0?void 0:a.split(","))!==null&&n!==void 0?n:[],Ko=Ts.includes(ss.WEBM_AS_IN_FFMPEG)||Ts.includes(ss.WEBM_AS_IN_SPEC)?Xt.WEBM:Xt.MP4;for(const _e of jo){const Ei=_e.getAttribute("mimeType"),Jo=_e.getAttribute("codecs"),da=(o=_e.getAttribute("contentType"))!==null&&o!==void 0?o:Ei==null?void 0:Ei.split("/")[0],Xo=(d=(l=_e.getAttribute("profiles"))===null||l===void 0?void 0:l.split(","))!==null&&d!==void 0?d:[],la=_e.querySelectorAll("Representation"),Zo=_e.querySelector("SegmentTemplate");if(da===ge.TEXT){for(const fe of la){const dt=fe.getAttribute("id")||"",$i=_e.getAttribute("lang"),Nt=(h=(c=(u=fe.querySelector("BaseURL"))===null||u===void 0?void 0:u.textContent)===null||c===void 0?void 0:c.trim())!==null&&h!==void 0?h:"",Es=new URL(Nt||ai,e).toString(),$s=dt.includes("_auto");Ke[ge.TEXT].push({id:dt,lang:$i,isAuto:$s,kind:ge.TEXT,url:Es})}continue}for(const fe of la){const dt=(f=fe.getAttribute("mimeType"))!==null&&f!==void 0?f:Ei,$i=(m=(g=fe.getAttribute("codecs"))!==null&&g!==void 0?g:Jo)!==null&&m!==void 0?m:"",Nt=(S=(v=fe.getAttribute("contentType"))!==null&&v!==void 0?v:dt==null?void 0:dt.split("/")[0])!==null&&S!==void 0?S:da,Es=($=(E=_e.getAttribute("profiles"))===null||E===void 0?void 0:E.split(","))!==null&&$!==void 0?$:[],$s=parseInt((A=fe.getAttribute("width"))!==null&&A!==void 0?A:"",10),ua=parseInt((P=fe.getAttribute("height"))!==null&&P!==void 0?P:"",10),ca=parseInt((q=fe.getAttribute("bandwidth"))!==null&&q!==void 0?q:"",10)/1e3,ha=(j=fe.getAttribute("frameRate"))!==null&&j!==void 0?j:"",ed=(K=fe.getAttribute("quality"))!==null&&K!==void 0?K:void 0,td=ha?Xm(ha):void 0,id=(G=fe.getAttribute("id"))!==null&&G!==void 0?G:(Qo++).toString(10),sd=Nt==="video"?`${ua}p`:Nt==="audio"?`${ca}Kbps`:$i,rd=`${id}@${sd}`,ad=(M=(Z=(J=fe.querySelector("BaseURL"))===null||J===void 0?void 0:J.textContent)===null||Z===void 0?void 0:Z.trim())!==null&&M!==void 0?M:"",fa=new URL(ad||ai,e).toString(),nd=[...Ts,...Xo,...Es];let ws;const od=fe.querySelector("SegmentBase"),vt=(_=fe.querySelector("SegmentTemplate"))!==null&&_!==void 0?_:Zo;if(od){const gt=(B=(se=fe.querySelector("SegmentBase Initialization"))===null||se===void 0?void 0:se.getAttribute("range"))!==null&&B!==void 0?B:"",[St,ks]=gt.split("-").map(Ft=>parseInt(Ft,10)),lt={from:St,to:ks},ni=(L=fe.querySelector("SegmentBase"))===null||L===void 0?void 0:L.getAttribute("indexRange"),[Ps,wi]=ni?ni.split("-").map(Ft=>parseInt(Ft,10)):[],oi=ni?{from:Ps,to:wi}:void 0;ws={type:Re.BYTE_RANGE,url:fa,initRange:lt,indexRange:oi}}else if(vt){const gt={representationId:(X=fe.getAttribute("id"))!==null&&X!==void 0?X:void 0,bandwidth:(oe=fe.getAttribute("bandwidth"))!==null&&oe!==void 0?oe:void 0},St=parseInt((he=vt.getAttribute("timescale"))!==null&&he!==void 0?he:"",10),ks=(me=vt.getAttribute("initialization"))!==null&&me!==void 0?me:"",lt=vt.getAttribute("media"),ni=(si=parseInt((Fe=vt.getAttribute("startNumber"))!==null&&Fe!==void 0?Fe:"",10))!==null&&si!==void 0?si:1,Ps=jt(ks,gt);if(!lt)throw new ReferenceError("No media attribute in SegmentTemplate");const wi=(Ot=vt.querySelectorAll("SegmentTimeline S"))!==null&&Ot!==void 0?Ot:[],oi=[];let Ft=0,Ds="",Rs=0;if(wi.length){let Ai=ni,Ce=0;for(const Vt of wi){const Ve=parseInt((W=Vt.getAttribute("d"))!==null&&W!==void 0?W:"",10),bt=parseInt((Se=Vt.getAttribute("r"))!==null&&Se!==void 0?Se:"",10)||0,ki=parseInt((Te=Vt.getAttribute("t"))!==null&&Te!==void 0?Te:"",10);Ce=Number.isFinite(ki)?ki:Ce;const Ls=Ve/St*1e3,Is=Ce/St*1e3;for(let Pi=0;Pi<bt+1;Pi++){const ld=jt(lt,{...gt,segmentNumber:Ai.toString(10),segmentTime:(Ce+Pi*Ve).toString(10)}),pa=(Is!=null?Is:0)+Pi*Ls,ud=pa+Ls;Ai++,oi.push({time:{from:pa,to:ud},url:ld})}Ce+=(bt+1)*Ve,Ft+=(bt+1)*Ls}Rs=Ce/St*1e3,Ds=jt(lt,{...gt,segmentNumber:Ai.toString(10),segmentTime:Ce.toString(10)})}else if(k(mt)){const Ce=parseInt((we=vt.getAttribute("duration"))!==null&&we!==void 0?we:"",10)/St*1e3,Vt=Math.ceil(mt/Ce);let Ve=0;for(let bt=1;bt<Vt;bt++){const ki=jt(lt,{...gt,segmentNumber:bt.toString(10),segmentTime:Ve.toString(10)});oi.push({time:{from:Ve,to:Ve+Ce},url:ki}),Ve+=Ce}Rs=Ve,Ds=jt(lt,{...gt,segmentNumber:Vt.toString(10),segmentTime:Ve.toString(10)})}const dd={time:{from:Rs,to:1/0},url:Ds};ws={type:Re.TEMPLATE,baseUrl:fa,segmentTemplateUrl:lt,initUrl:Ps,totalSegmentsDurationMs:Ft,segments:oi,nextSegmentBeyondManifest:dd,timescale:St}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Nt||!dt)continue;const As={video:ge.VIDEO,audio:ge.AUDIO,text:ge.TEXT}[Nt];As&&Ke[As].push({id:rd,kind:As,segmentReference:ws,profiles:nd,duration:mt,bitrate:ca,mime:dt,codecs:$i,width:$s,height:ua,fps:td,quality:ed})}}return{dynamic:zo,liveAvailabilityStartTime:Wo,duration:mt,container:Ko,representations:Ke}},ev=({id:i,width:e,height:t,bitrate:s,fps:r,quality:a})=>{var n;const o=(n=a?vs(a):void 0)!==null&&n!==void 0?n:At({width:e,height:t});return o&&{id:i,quality:o,bitrate:s,size:{width:e,height:t},fps:r}},tv=({id:i,bitrate:e})=>({id:i,bitrate:e}),iv=(i,e,t)=>{var s;const r=e.indexOf(t);return(s=Je(i,Math.round(i.length*r/e.length)))!==null&&s!==void 0?s:Je(i,-1)},sv=({id:i,lang:e,url:t,isAuto:s})=>({id:i,url:t,isAuto:s,type:"internal",language:e}),En=i=>"url"in i,qt=i=>i.type===Re.TEMPLATE,xr=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);class $n{constructor(e,t,s,r,{fetcher:a,tuning:n,getCurrentPosition:o,isActiveLowLatency:l,compatibilityMode:d=!1,manifest:u}){switch(this.onLastSegment$=new b(!1),this.fullyBuffered$=new b(!1),this.playingRepresentation$=new b(void 0),this.playingRepresentationInit$=new b(void 0),this.error$=new x,this.gaps=[],this.subscription=new ie,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new Jt,this.destroyAbortController=new Jt,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.liveInitialAdditionalOffset=0,this.isSeekingLive=!1,this.index=0,this.startWith=$e(this.destroyAbortController.signal,async function*(c){const h=this.representations.get(c);D(h,`Cannot find representation ${c}`),this.playingRepresentationId=c,this.downloadingRepresentationId=c,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${h.mime}; codecs="${h.codecs}"`),this.sourceBufferTaskQueue=new Lp(this.sourceBuffer),this.subscription.add(C(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},v=>this.error$.next({id:"SegmentEjection",category:I.WTF,message:"Error when trying to clear segments ejected by browser",thrown:v}))),this.subscription.add(C(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:I.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(v=>{if(!this.sourceBuffer)return;const S=Math.min(this.bufferLimit,pn(this.sourceBuffer.buffered)*.8);this.bufferLimit=S,this.pruneBuffer(this.getCurrentPosition(),v)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(v=>this.error$.next(v))),yield this.loadInit(h,"high",!0);const f=this.initData.get(h.id),g=this.segments.get(h.id),m=this.parsedInitData.get(h.id);D(f,"No init buffer for starting representation"),D(g,"No segments for starting representation"),f instanceof ArrayBuffer&&(this.searchGaps(g,h),yield this.sourceBufferTaskQueue.append(f,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(m))}.bind(this)),this.switchTo=$e(this.destroyAbortController.signal,async function*(c){if(c===this.downloadingRepresentationId||c===this.switchingToRepresentationId)return;this.switchingToRepresentationId=c;const h=this.representations.get(c);D(h,`No such representation ${c}`);let f=this.segments.get(c),g=this.initData.get(c);if(Q(g)||Q(f)?yield this.loadInit(h,"high",!1):g instanceof Promise&&(yield g),f=this.segments.get(c),D(f,"No segments for starting representation"),g=this.initData.get(c),!g||!(g instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=c,this.abort(),yield this.sourceBufferTaskQueue.append(g,this.downloadAbortController.signal);const m=this.getCurrentPosition();k(m)&&(this.isLive||(f.forEach(v=>v.status=V.NONE),this.pruneBuffer(m,1/0,!0)),this.maintain(m))}.bind(this)),this.seekLive=$e(this.destroyAbortController.signal,async function*(c){var h;if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!c)return;for(const E of this.representations.keys()){const $=c.find(q=>q.id===E);$&&this.representations.set(E,$);const A=this.representations.get(E);if(!A||!qt(A.segmentReference))return;const P=this.getActualLiveStartingSegments(A.segmentReference);this.segments.set(A.id,P)}const f=(h=this.switchingToRepresentationId)!==null&&h!==void 0?h:this.downloadingRepresentationId,g=this.representations.get(f);D(g);const m=this.segments.get(f);D(m,"No segments for starting representation");const v=this.initData.get(f);if(D(v,"No init buffer for starting representation"),!(v instanceof ArrayBuffer))return;const S=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),S&&(yield this.sourceBufferTaskQueue.remove(S.from*1e3,S.to*1e3,this.destroyAbortController.signal)),this.searchGaps(m,g),yield this.sourceBufferTaskQueue.append(v,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this)),this.fetcher=a,this.tuning=n,this.compatibilityMode=d,this.forwardBufferTarget=n.dash.forwardBufferTargetAuto,this.getCurrentPosition=o,this.isActiveLowLatency=l,this.isLive=!!(u!=null&&u.dynamic),this.container=s,s){case Xt.MP4:this.containerParser=rm;break;case Xt.WEBM:this.containerParser=cm;break;default:H(s)}this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Jt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(Q(e)||Q(this.downloadingRepresentationId)||Q(this.playingRepresentationId)||Q(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(D(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const r=s.find(d=>e>=d.time.from&&e<d.time.to);let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const u=Wt(this.sourceBuffer.buffered,e),c=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&u>=r.time.to-e+100&&(a=c)}if(isFinite(this.bufferLimit)&&pn(this.sourceBuffer.buffered)>=this.bufferLimit){const d=Wt(this.sourceBuffer.buffered,e),u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,d<u);return}let o=[];if(!this.activeSegments.size&&(o=this.selectForwardBufferSegments(s,t.segmentReference.type,a),o.length)){let d="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(o.includes(r))d="high";else{const u=Je(o,0);u&&u.time.from-r.time.to>=this.forwardBufferTarget/2&&(d="low")}this.loadSegments(o,t,d)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===V.FED&&!o.length&&Wt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const l=Je(s,-1);l&&l.status===V.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===l))}searchGaps(e,t){this.gaps=[];let s=0;const r=this.isLive?this.liveInitialAdditionalOffset:0;for(const a of e)Math.trunc(a.time.from-s)>0&&this.gaps.push({representation:t.id,from:s,to:a.time.from+r}),s=a.time.to;k(t.duration)&&t.duration-s>0&&this.gaps.push({representation:t.id,from:s,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,s=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[];let a=0,n=t.length-1;do r.unshift(t[n]),a+=t[n].time.to-t[n].time.from,n--;while(a<s&&n>=0);return this.liveInitialAdditionalOffset=a-s,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(r=>r.id===this.downloadingRepresentationId);if(!t)return;const s=this.segments.get(t.id);if(s!=null&&s.length)return{from:s[0].time.from,to:s[s.length-1].time.to}}updateLive(e){var t,s,r,a;for(const n of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!n||!qt(n.segmentReference))return;const o=n.segmentReference.segments.map(c=>({...c,status:V.NONE,size:void 0})),l=(s=this.segments.get(n.id))!==null&&s!==void 0?s:[],d=(a=(r=Je(l,-1))===null||r===void 0?void 0:r.time.to)!==null&&a!==void 0?a:0,u=o==null?void 0:o.findIndex(c=>Math.floor(d)>=Math.floor(c.time.from)&&Math.floor(d)<=Math.floor(c.time.to));if(u===-1){this.liveUpdateSegmentIndex=0;const c=this.getActualLiveStartingSegments(n.segmentReference);this.segments.set(n.id,c)}else{const c=o.slice(u+1);this.segments.set(n.id,[...l,...c])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(const s of this.representations.values()){const r=s.segmentReference;if(!qt(r))return;const a=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),n=jt(r.segmentTemplateUrl,{segmentTime:a}),o=(t=this.segments.get(s.id))!==null&&t!==void 0?t:[],l=o.find(u=>Math.floor(u.time.from)===Math.floor(e.segment.time.from));l&&(l.time.to=e.segment.time.to),!!o.find(u=>Math.floor(u.time.from)===Math.floor(e.segment.time.to))||o.push({status:V.NONE,time:{from:e.segment.time.to,to:1/0},url:n})}}findSegmentStartTime(e){var t,s,r;const a=(s=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&s!==void 0?s:this.playingRepresentationId;if(!a)return;const n=this.segments.get(a);if(!n)return;const o=n.find(l=>l.time.from<=e&&l.time.to>=e);return(r=o==null?void 0:o.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,s){return this.isLive?this.selectForwardBufferSegmentsLive(e,s):this.selectForwardBufferSegmentsRecord(e,t,s)}selectForwardBufferSegmentsLive(e,t){const s=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=s),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,s){const r=e.findIndex(({status:c,time:{from:h,to:f}},g)=>{const m=h<=s&&f>=s,v=h>s||m||g===0&&s===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),E=this.preloadOnly&&h<=s+S||f<=s+S;return(c===V.NONE||c===V.PARTIALLY_EJECTED&&v&&E&&this.sourceBuffer&&!Lr(this.sourceBuffer.buffered,s))&&v&&E});if(r===-1)return[];if(t!==Re.BYTE_RANGE)return e.slice(r,r+1);const a=e;let n=0,o=0;const l=[],d=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,u=this.preloadOnly?this.forwardBufferTarget:0;for(let c=r;c<a.length&&(n<=d||o<=u);c++){const h=a[c];if(n+=h.byte.to+1-h.byte.from,o+=h.time.to+1-h.time.from,h.status===V.NONE||h.status===V.PARTIALLY_EJECTED)l.push(h);else break}return l}async loadSegments(e,t,s="auto"){t.segmentReference.type===Re.TEMPLATE?await this.loadTemplateSegment(e[0],t,s):await this.loadByteRangeSegments(e,t,s)}async loadTemplateSegment(e,t,s="auto"){e.status=V.DOWNLOADING;const r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);const{range:a,url:n,signal:o,onProgress:l,onProgressTasks:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&o&&(await $e(o,async function*(){const u=qi(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,u))}.bind(this))(),o.aborted&&this.abortActiveSegments([e]));try{const u=await this.fetcher.fetch(n,{range:a,signal:o,onProgress:l,priority:s,isLowLatency:this.isActiveLowLatency()});if(!u)return;const c=new DataView(u);if(this.isActiveLowLatency()){const h=t.segmentReference.timescale;r.segment.time.to=this.containerParser.getSegmentEndTime(c,h)}l&&r.feedingBytes&&d?await Promise.all(d):await this.sourceBufferTaskQueue.append(c,o),r.segment.status=V.DOWNLOADED,this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(u){if(!xr(u))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(u)}}async loadByteRangeSegments(e,t,s="auto"){if(!e.length)return;for(const l of e)l.status=V.DOWNLOADING,this.activeSegments.add({segment:l,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:r,url:a,signal:n,onProgress:o}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&n&&(await $e(n,async function*(){const l=qi(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,l))}.bind(this))(),n.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(a,{range:r,onProgress:o,signal:n,priority:s}),this.failedDownloads=0}catch(l){if(!xr(l))return;this.abortActiveSegments(e),this.onSegmentDownloadError(l)}}prepareByteRangeFetchSegmentParams(e,t){if(qt(t.segmentReference))throw new Error("Representation is not byte range type");const s=t.segmentReference.url,r={from:Je(e,0).byte.from,to:Je(e,-1).byte.to},{signal:a}=this.downloadAbortController,n=()=>{this.abort()};return{url:s,range:r,signal:a,onProgress:(l,d)=>{if(!a.aborted)try{this.onSomeByteRangesDataLoaded({dataView:l,loaded:d,signal:a,onSegmentAppendFailed:n,globalFrom:r?r.from:0,representationId:t.id})}catch(u){this.error$.next({id:"SegmentFeeding",category:I.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:u})}}}}prepareTemplateFetchSegmentParams(e,t){if(!qt(t.segmentReference))throw new Error("Representation is not template type");const s=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&s.searchParams.set("low-latency","yes");const r=s.toString(),{signal:a}=this.downloadAbortController,n=()=>{this.abort()},o=[],d=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(u,c)=>{if(!a.aborted)try{const h=this.onSomeTemplateDataLoaded({dataView:u,loaded:c,signal:a,onSegmentAppendFailed:n,representationId:t.id});o.push(h)}catch(h){this.error$.next({id:"SegmentFeeding",category:I.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}}:void 0;return{url:r,signal:a,onProgress:d,onProgressTasks:o}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSegmentDownloadError(e){var t;let s=!1;const r=this.getCurrentPosition();this.sourceBuffer&&k(r)&&(s=Wt((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,s||this.error$.next({id:"SegmentDownload",category:I.NETWORK,message:"Error when fetching segments",thrown:e})}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:s,onSegmentAppendFailed:r,signal:a}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const o of this.activeSegments){const{segment:l}=o;if(o.representationId===t){if(a.aborted){r();continue}if(o.loadedBytes=s,o.loadedBytes>o.feedingBytes){const d=new DataView(e.buffer,e.byteOffset+o.feedingBytes,o.loadedBytes-o.feedingBytes),u=this.containerParser.parseFeedableSegmentChunk(d);u!=null&&u.byteLength&&(l.status=V.PARTIALLY_FED,o.feedingBytes+=u.byteLength,await this.sourceBufferTaskQueue.append(u),o.fedBytes+=u.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:s,loaded:r,signal:a,onSegmentAppendFailed:n}){if(!this.activeSegments.size)return;const o=this.representations.get(t);if(!o)return;const l=o.segmentReference.type,d=e.byteLength;for(const u of this.activeSegments){const{segment:c}=u,h=l===Re.BYTE_RANGE,f=h?c.byte.to-c.byte.from+1:d;if(u.representationId!==t||!(!h||c.byte.from>=s&&c.byte.to<s+e.byteLength))continue;if(a.aborted){n();continue}const m=h?c.byte.from-s:0,v=h?c.byte.to-s:e.byteLength,S=m<r,E=v<=r;if(c.status===V.DOWNLOADING&&S&&E){c.status=V.DOWNLOADED;const $=new DataView(e.buffer,e.byteOffset+m,f);this.sourceBufferTaskQueue.append($,a).then(A=>A&&!a.aborted?this.onSegmentFullyAppended(u,t):n())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&(u.loadedBytes=Math.min(f,r-m),u.loadedBytes>u.feedingBytes)){const $=new DataView(e.buffer,e.byteOffset+m+u.feedingBytes,u.loadedBytes-u.feedingBytes),A=u.loadedBytes===f?$:this.containerParser.parseFeedableSegmentChunk($);A!=null&&A.byteLength&&(c.status=V.PARTIALLY_FED,u.feedingBytes+=A.byteLength,this.sourceBufferTaskQueue.append(A,a).then(P=>{if(a.aborted)n();else if(P)u.fedBytes+=A.byteLength,u.fedBytes===f&&this.onSegmentFullyAppended(u,t);else{if(u.feedingBytes<f)return;n()}}))}}}onSegmentFullyAppended(e,t){var s;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=V.FED,En(e.segment)&&(e.segment.size=e.fedBytes);for(const r of this.representations.values())if(r.id!==t)for(const a of(s=this.segments.get(r.id))!==null&&s!==void 0?s:[])a.status===V.FED&&a.time.from===e.segment.time.from&&a.time.to===e.segment.time.to&&(a.status=V.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===V.PARTIALLY_FED||e.status===V.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=V.NONE),e.status=V.PARTIALLY_EJECTED):e.status=V.NONE;for(const s of this.activeSegments.values())if(s.segment===e){this.activeSegments.delete(s);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,a]of this.initData.entries()){const n=a instanceof Promise;t||(t=n),a===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=fn(()=>this.loadInit(s,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",s=!1){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",n=(!s&&this.failedDownloads>0?$e(this.destroyAbortController.signal,async function*(){const o=qi(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(l=>setTimeout(l,o))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(async o=>{if(!o)return;const{init:l,dataView:d,segments:u}=o,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c);let h=u;this.isLive&&qt(e.segmentReference)&&(h=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,h),l&&this.parsedInitData.set(e.id,l)}).then(()=>this.failedDownloads=0,o=>{this.initData.set(e.id,null),s&&this.error$.next({id:"LoadInits",category:I.WTF,message:"loadInit threw",thrown:o})});return this.initData.set(e.id,n),n}async pruneBuffer(e,t,s=!1){if(!this.sourceBuffer||!this.playingRepresentationId||Q(e)||this.sourceBuffer.updating)return!1;let r=0,a=1/0,n=-1/0,o=!1;const l=d=>{var u;a=Math.min(a,d.time.from),n=Math.max(n,d.time.to);const c=En(d)?(u=d.size)!==null&&u!==void 0?u:0:d.byte.to-d.byte.from;r+=c};for(const d of this.segments.values())for(const u of d){if(u.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;u.status===V.FED&&l(u)}if(o=isFinite(a)&&isFinite(n),!o){r=0,a=1/0,n=-1/0;for(const d of this.segments.values())for(const u of d){if(u.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;u.status===V.FED&&l(u)}}if(o=isFinite(a)&&isFinite(n),!o)for(let d=0;d<this.sourceBuffer.buffered.length;d++){const u=this.sourceBuffer.buffered.start(d)*1e3,c=this.sourceBuffer.buffered.end(d)*1e3;for(const h of this.segments.values())for(const f of h)if(f.status===V.NONE&&Math.round(f.time.from)<=Math.round(u)&&Math.round(f.time.to)>=Math.round(c)){a=u,n=c;break}}if(o=isFinite(a)&&isFinite(n),!o&&s){r=0,a=1/0,n=-1/0;const d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const u of this.segments.values())for(const c of u)c.time.from>e+d&&c.status===V.FED&&l(c)}return o=isFinite(a)&&isFinite(n),o?this.sourceBufferTaskQueue.remove(a,n):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const s of t){let r={representation:e,from:s.time.from,to:s.time.to};for(let a=0;a<this.sourceBuffer.buffered.length;a++){const n=this.sourceBuffer.buffered.start(a)*1e3,o=this.sourceBuffer.buffered.end(a)*1e3;if(!(o<=s.time.from||n>=s.time.to)){if(n<=s.time.from&&o>=s.time.to){r=void 0;break}o>s.time.from&&o<s.time.to&&(r.from=o),n<s.time.to&&n>s.time.from&&(r.to=n)}}r&&r.to-r.from>1&&!this.gaps.some(a=>r&&a.from===r.from&&a.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=fn(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:I.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(Q(this.sourceBuffer)||Q(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const r=Math.round(this.sourceBuffer.buffered.start(s)*1e3),a=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:r,to:a})}const t=1;for(const s of this.segments.values())for(const r of s){const{status:a}=r;if(a!==V.FED&&a!==V.PARTIALLY_EJECTED)continue;const n=Math.floor(r.time.from),o=Math.ceil(r.time.to),l=e.some(u=>u.from-t<=n&&u.to+t>=o),d=e.filter(u=>n>=u.from-t&&n<=u.to+t||o>=u.from-t&&o<=u.to+t);l||(d.length===1?r.status=V.PARTIALLY_EJECTED:r.status=V.NONE)}}}var _r=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},rv=i=>{var e,t;const s=i.get("X-Delivery-Type"),r=i.get("X-Reused"),a=s===null?br.HTTP1:(e=s)!==null&&e!==void 0?e:void 0,n=r===null?void 0:(t={1:!0,0:!1}[r])!==null&&t!==void 0?t:void 0;return{type:a,reused:n}},Qt;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(Qt||(Qt={}));class av{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.lastConnectionType$=new b(void 0),this.lastConnectionReused$=new b(void 0),this.lastRequestFirstBytes$=new b(void 0),this.abortAllController=new Jt,this.subscription=new ie,this.fetchManifest=$e(this.abortAllController.signal,async function*(r){let a=r;this.requestQuic&&(a=_r(a));const n=yield vi(a,{signal:this.abortAllController.signal}).catch(di);return n?(this.onHeadersReceived(n.headers),n.text()):null}.bind(this)),this.fetch=$e(this.abortAllController.signal,async function*(r,{rangeMethod:a=this.compatibilityMode?Qt.HEADER:Qt.PARAM,range:n,onProgress:o,priority:l="auto",signal:d,measureThroughput:u=!0,isLowLatency:c=!1}={}){var h,f;let g=r;const m=new Headers;if(n)switch(a){case Qt.HEADER:{m.append("Range",`bytes=${n.from}-${n.to}`);break}case Qt.PARAM:{const _=new URL(g,location.href);_.searchParams.append("bytes",`${n.from}-${n.to}`),g=_.toString();break}default:H(a)}this.requestQuic&&(g=_r(g));let v=this.abortAllController.signal,S;if(d){const _=new Jt;if(S=N(C(this.abortAllController.signal,"abort"),C(d,"abort")).subscribe(()=>{try{_.abort()}catch(se){di(se)}}),this.abortAllController.signal.aborted||d.aborted)try{_.abort()}catch(se){di(se)}v=_.signal}const E=ne(),$=yield vi(g,{priority:l,headers:m,signal:v}).catch(di),A=ne();if(!$)return S==null||S.unsubscribe(),null;if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(A-E),!$.ok||!$.body)return S==null||S.unsubscribe(),Promise.reject(new Error(`Fetch error ${$.status}: ${$.statusText}`));if(this.onHeadersReceived($.headers),!o&&!u)return S==null||S.unsubscribe(),$.arrayBuffer();const[P,q]=$.body.tee(),j=P.getReader();u&&((f=this.throughputEstimator)===null||f===void 0||f.trackStream(q,c));let K=0,G=new Uint8Array(0),J=!1;const Z=_=>{S==null||S.unsubscribe(),J=!0,di(_)},M=$e(v,async function*({done:_,value:se}){if(K===0&&this.lastRequestFirstBytes$.next(ne()-E),v.aborted){S==null||S.unsubscribe();return}if(!_&&se){const B=new Uint8Array(G.length+se.length);B.set(G),B.set(se,G.length),G=B,K+=se.byteLength,o==null||o(new DataView(G.buffer),K),yield j==null?void 0:j.read().then(M,Z)}}.bind(this));return yield j==null?void 0:j.read().then(M,Z),S==null||S.unsubscribe(),J?null:G.buffer}.bind(this)),this.fetchByteRangeRepresentation=$e(this.abortAllController.signal,async function*(r,a,n){var o;if(r.type!==Re.BYTE_RANGE)return null;const{from:l,to:d}=r.initRange;let u=l,c=d,h=!1,f,g;r.indexRange&&(f=r.indexRange.from,g=r.indexRange.to,h=d+1===f,h&&(u=Math.min(f,l),c=Math.max(g,d))),u=Math.min(u,0);const m=yield this.fetch(r.url,{range:{from:u,to:c},priority:n,measureThroughput:!1});if(!m)return null;const v=new DataView(m,l-u,d-u+1);if(!a.validateData(v))throw new Error("Invalid media file");const S=a.parseInit(v),E=(o=r.indexRange)!==null&&o!==void 0?o:a.getIndexRange(S);if(!E)throw new ReferenceError("No way to load representation index");let $;if(h)$=new DataView(m,E.from-u,E.to-E.from+1);else{const P=yield this.fetch(r.url,{range:E,priority:n,measureThroughput:!1});if(!P)return null;$=new DataView(P)}const A=a.parseSegments($,S,E);return{init:S,dataView:new DataView(m),segments:A}}.bind(this)),this.fetchTemplateRepresentation=$e(this.abortAllController.signal,async function*(r,a){if(r.type!==Re.TEMPLATE)return null;const n=new URL(r.initUrl,r.baseUrl).toString(),o=yield this.fetch(n,{priority:a,measureThroughput:!1});return o?{init:null,segments:r.segments.map(d=>({...d,status:V.NONE,size:void 0})),dataView:new DataView(o)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=rv(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}async fetchRepresentation(e,t,s="auto"){var r,a;const{type:n}=e;switch(n){case Re.BYTE_RANGE:return(r=await this.fetchByteRangeRepresentation(e,t,s))!==null&&r!==void 0?r:null;case Re.TEMPLATE:return(a=await this.fetchTemplateRepresentation(e,s))!==null&&a!==void 0?a:null;default:H(n)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const di=i=>{if(!xr(i))throw i},Cr=1e3,ns=(i,e,t)=>t*e+(1-t)*i,Vo=(i,e)=>i.reduce((t,s)=>t+s,0)/e,nv=(i,e,t,s)=>{let r=0,a=t;const n=Vo(i,e),o=e<s?e:s;for(let l=0;l<o;l++)i[a]>n?r++:r--,a=(i.length+a-1)%i.length;return Math.abs(r)===o};class ia{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 b(e.initial),this.debounced$=new b(e.initial);const s=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ye(`raw_${s}`),this.smoothedSeries$=new Ye(`smoothed_${s}`),this.reportedSeries$=new Ye(`reported_${s}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,s=0;for(let o=0;o<this.pastMeasures.length;o++)this.pastMeasures[o]!==void 0&&(t+=(this.pastMeasures[o]-this.smoothed)**2,s++);this.takenMeasures=s,t/=s;const r=Math.sqrt(t),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>a||this.smoothed<n)&&(Q(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 ov extends ia{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ns(this.slow,e,this.params.emaAlphaSlow),this.fast=ns(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class dv extends ia{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Vo(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ns(this.emaSmoothed,e,this.params.emaAlpha);const s=nv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class lv extends ia{constructor(e){super(e),this.furtherValues=[],this.currentTopExtremumValue=0,this.extremumInterval=e.extremumInterval}next(e){this.currentTopExtremumValue<=e?(this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.push(e)}updateSmoothedValue(e){this.smoothed=this.smoothed?ns(this.smoothed,e,this.params.emaAlpha):e}}class Or{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new ov({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new dv({initial:e,emaAlpha:s.emaAlpha,basisTrendChangeCount:s.basisTrendChangeCount,changeThreshold:s.changeThreshold,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new lv({initial:e,label:"liveEdgeDelay",...t})}}const uv=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)},yt=()=>window.ManagedMediaSource||window.MediaSource,Uo=()=>{var i,e;return!!(window.ManagedMediaSource&&(!((e=(i=window.ManagedSourceBuffer)===null||i===void 0?void 0:i.prototype)===null||e===void 0)&&e.appendBuffer))},cv=()=>{var i,e;return!!(window.MediaSource&&window.MediaStreamTrack&&(!((e=(i=window.SourceBuffer)===null||i===void 0?void 0:i.prototype)===null||e===void 0)&&e.appendBuffer))},hv=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource,wn=["timeupdate","progress","play","seeked","stalled","waiting"];var De;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(De||(De={}));let fv=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new ie,this.representationSubscription=new ie,this.state$=new le(De.NONE),this.currentVideoRepresentation$=new b(void 0),this.currentVideoRepresentationInit$=new b(void 0),this.error$=new x,this.lastConnectionType$=new b(void 0),this.lastConnectionReused$=new b(void 0),this.lastRequestFirstBytes$=new b(void 0),this.isLive$=new b(!1),this.liveDuration$=new b(0),this.liveAvailabilityStartTime$=new b(void 0),this.bufferLength$=new b(0),this.liveLoadBufferLength$=new b(0),this.livePositionFromPlayer$=new b(0),this.isActiveLowLatency=!1,this.isUpdatingLive=!1,this.isJumpGapAfterSeekLive=!1,this.liveLastSeekOffset=0,this.forceEnded$=new x,this.gapWatchdogStarted=!1,this.destroyController=new Jt,this.initManifest=$e(this.destroyController.signal,async function*(t,s,r){var a;this.element=t,this.manifestUrlString=Me(s,r,pe.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(De.MANIFEST_READY),this.manifest=yield this.updateManifest(),!((a=this.manifest)===null||a===void 0)&&a.representations.video.length?this.state$.setState(De.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:I.PARSER,message:"No playable video representations"})}.bind(this)),this.updateManifest=$e(this.destroyController.signal,async function*(){var t;const s=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(n=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:I.NETWORK,message:"Failed to load manifest",thrown:n})});if(!s)return null;let r;try{r=Zm(s!=null?s:"",this.manifestUrlString)}catch(n){this.error$.next({id:"ManifestParsing",category:I.PARSER,message:"Failed to parse MPD manifest",thrown:n})}if(!r)return null;const a=({kind:n,mime:o,codecs:l})=>{var d,u,c,h;return!!(!((u=(d=this.element)===null||d===void 0?void 0:d.canPlayType)===null||u===void 0)&&u.call(d,o)&&(!((h=(c=yt())===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0)&&h.call(c,`${o}; codecs="${l}"`))||n===ge.TEXT)};return r.dynamic&&this.isLive$.getValue()!==r.dynamic&&(this.isLive$.next(r.dynamic),this.liveDuration$.getValue()!==r.duration&&this.liveDuration$.next(-1*((t=r.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==r.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(r.liveAvailabilityStartTime)),{...r,representations:is(Object.entries(r.representations).map(([n,o])=>[n,o.filter(a)]))}}.bind(this)),this.initRepresentations=$e(this.destroyController.signal,async function*(t,s,r){var a;D(this.manifest),D(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(De.REPRESENTATIOS_READY);const n=m=>{this.representationSubscription.add(C(m,"error").pipe(ue(v=>{var S;return!!(!((S=this.element)===null||S===void 0)&&S.played.length)})).subscribe(v=>{this.error$.next({id:"VideoSource",category:I.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:v})}))};this.source=this.tuning.useManagedMediaSource?hv():new MediaSource;const o=document.createElement("source");if(n(o),o.src=URL.createObjectURL(this.source),this.element.appendChild(o),this.tuning.useManagedMediaSource&&Uo())if(r){const m=document.createElement("source");n(m),m.type="application/x-mpegurl",m.src=r.url,this.element.appendChild(m)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const l={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency,manifest:this.manifest};if(this.videoBufferManager=new $n(ge.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,l),this.bufferManagers=[this.videoBufferManager],k(s)&&(this.audioBufferManager=new $n(ge.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,l),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(Xi(Cr).subscribe(m=>{var v;if(!((v=this.element)===null||v===void 0)&&v.paused){const S=on(this.manifestUrlString,pe.DASH_CMAF_OFFSET_P);this.manifestUrlString=Me(this.manifestUrlString,S+Cr,pe.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(N(...wn.map(m=>C(this.element,m))).pipe(w(m=>this.element?Wt(this.element.buffered,this.element.currentTime*1e3):0),ce(),ue(m=>!!m),pi(m=>{this.waitingEventInterval&&(window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=void 0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(ue(v=>this.isActiveLowLatency&&!!v)).subscribe(v=>this.liveEstimatedDelay.next(v))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(v=>{if(!this.isActiveLowLatency)return;const S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,E=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,$=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,A=v-S;let P=1+Math.sign(A)*$;Math.abs(A)<E?P=1:Math.abs(A)>E*2&&(P=1+Math.sign(A)*$*2),uv(this.element,P)})),this.representationSubscription.add(this.bufferLength$.subscribe(v=>{var S,E;let $=0;if(v){const A=((E=(S=this.element)===null||S===void 0?void 0:S.currentTime)!==null&&E!==void 0?E:0)*1e3;$=Math.min(...this.bufferManagers.map(q=>{var j,K;return(K=(j=q.getLiveSegmentsToLoadState(this.manifest))===null||j===void 0?void 0:j.to)!==null&&K!==void 0?K:0}))-A}$&&this.liveLoadBufferLength$.getValue()!==$&&this.liveLoadBufferLength$.next($)}));let m=0;this.representationSubscription.add(We({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).subscribe(async({liveLoadBufferLength:v,bufferLength:S})=>{if(D(this.element),this.isUpdatingLive)return;const E=this.element.playbackRate,$=on(this.manifestUrlString,pe.DASH_CMAF_OFFSET_P),A=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,P=Math.min(A,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*E),q=this.tuning.dashCmafLive.normalizedActualBufferOffset*E,j=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*E,K=this.isActiveLowLatency?S:v;let G=Ge.None;if(this.isActiveLowLatency?G=Ge.ActiveLowLatency:K<P+j&&K>=P?G=Ge.LiveWithTargetOffset:$!==0&&K<P&&(G=Ge.LiveForwardBuffering),isFinite(v)&&(m=v>m?v:m),G===Ge.LiveForwardBuffering||G===Ge.LiveWithTargetOffset){const J=m-(P+q),Z=this.normolizeLiveOffset(Math.trunc($+J/E)),M=Math.abs(Z-$);let _;!v||M<=this.tuning.dashCmafLive.offsetCalculationError?_=$:Z>0&&M>this.tuning.dashCmafLive.offsetCalculationError?_=Z:_=0,this.manifestUrlString=Me(this.manifestUrlString,_,pe.DASH_CMAF_OFFSET_P)}G!==Ge.None&&G!==Ge.ActiveLowLatency&&(m=0,this.updateLive())}))}const d=N(...this.bufferManagers.map(m=>m.fullyBuffered$)).pipe(w(()=>this.bufferManagers.every(m=>m.fullyBuffered$.getValue()))),u=N(...this.bufferManagers.map(m=>m.onLastSegment$)).pipe(w(()=>this.bufferManagers.some(m=>m.onLastSegment$.getValue())));this.representationSubscription.add(N(this.forceEnded$,We({allBuffersFull:d,someBufferEnded:u}).pipe(ue(({allBuffersFull:m,someBufferEnded:v})=>m&&v))).subscribe(()=>{var m;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(v=>!v.updating))try{(m=this.source)===null||m===void 0||m.endOfStream()}catch(v){this.error$.next({id:"EndOfStream",category:I.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:v})}})),this.representationSubscription.add(N(...this.bufferManagers.map(m=>m.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield new Promise(m=>{var v;return(v=this.source)===null||v===void 0?void 0:v.addEventListener("sourceopen",m)}));const c=(a=this.manifest.duration)!==null&&a!==void 0?a:0,h=(m,v)=>{var S;return Math.max(m,(S=v.duration)!==null&&S!==void 0?S:0)},f=this.manifest.representations.audio.reduce(h,c),g=this.manifest.representations.video.reduce(h,c);(f||g)&&(this.source.duration=Math.max(f,g)/1e3),this.audioBufferManager&&k(s)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)]):yield this.videoBufferManager.startWith(t),this.state$.setState(De.REPRESENTATIOS_READY)}.bind(this)),this.tick=()=>{var t,s;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((s=this.audioBufferManager)===null||s===void 0)&&s.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=Xi(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),a=>{this.error$.next({id:"GapWatchdog",category:I.WTF,message:"Error handling gaps",thrown:a})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new av({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Or.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){var t,s,r,a;D(this.element);const n=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&n===0,this.liveLastSeekOffset=n,this.isJumpGapAfterSeekLive=!0,this.manifestUrlString=Me(this.manifestUrlString,n,pe.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),this.manifest&&(await((t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((s=this.manifest)===null||s===void 0?void 0:s.representations.video)),await((r=this.audioBufferManager)===null||r===void 0?void 0:r.seekLive((a=this.manifest)===null||a===void 0?void 0:a.representations.audio)))}initBuffer(){D(this.element),this.state$.setState(De.RUNNING),this.subscription.add(N(...wn.map(e=>C(this.element,e)),C(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:I.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(C(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(C(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Lr(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime),this.waitingEventInterval&&window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=window.setInterval(this.waitingEventCallback.bind(this),this.tuning.dashMaxWaitingDuration)})),this.tick()}async switchRepresentation(e,t){const s={[ge.VIDEO]:this.videoBufferManager,[ge.AUDIO]:this.audioBufferManager,[ge.TEXT]:null}[e];return s==null?void 0:s.switchTo(t)}seek(e,t){var s,r,a,n,o;D(this.element),D(this.videoBufferManager);let l;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?l=e:l=Math.max((s=this.videoBufferManager.findSegmentStartTime(e))!==null&&s!==void 0?s:e,(a=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&a!==void 0?a:e),Lr(this.element.buffered,l)||(this.videoBufferManager.abort(),(n=this.audioBufferManager)===null||n===void 0||n.abort()),this.videoBufferManager.maintain(l),(o=this.audioBufferManager)===null||o===void 0||o.maintain(l),this.element.currentTime=l/1e3}stop(){var e,t,s;(e=this.element)===null||e===void 0||e.querySelectorAll("source").forEach(r=>r.remove()),this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(t=this.videoBufferManager)===null||t===void 0||t.destroy(),this.videoBufferManager=null,(s=this.audioBufferManager)===null||s===void 0||s.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(De.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),window.clearInterval(this.waitingEventInterval),this.stop(),((e=this.source)===null||e===void 0?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}async waitingEventCallback(){try{if(!this.element)return;this.isLive$.getValue()?await this.seekLive(this.liveLastSeekOffset):this.seek(this.element.currentTime*1e3,!0)}catch(e){this.error$.next({id:"WaitingEventCallback",category:I.WTF,message:"Error in seeking in waiting event callback",thrown:e})}}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)===null||e===void 0||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);const t=this.element.currentTime*1e3,s=[];for(const r of this.bufferManagers)for(const a of r.gaps)r.playingRepresentation$.getValue()===a.representation&&a.from<=t&&a.to>t&&(this.element.duration*1e3-a.to<this.tuning.endGapTolerance?s.push(1/0):s.push(a.to));if(s.length){const r=Math.max(...s);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):Math.trunc(this.element.currentTime*1e3)!==Math.trunc(r)&&(this.element.currentTime=r/1e3)}}};class pv{constructor(e,t){this.fov=e,this.orientation=t}}class mv{constructor(e,t){this.rotating=!1,this.fading=!1,this.lastTickTS=0,this.lastCameraTurnTS=0,this.fadeStartSpeed=null,this.fadeTime=0,this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,s=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+s)}pointCameraTo(e=0,t=0,s=0){t=this.limitCameraRotationY(t);const r=e-this.camera.orientation.x,a=t-this.camera.orientation.y,n=s-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=s,this.lastCameraTurn={x:r,y:a,z:n},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,s){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=s!=null?s:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){const e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){const t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,s){this.setRotationSpeed(e,t,s),this.fadeStartSpeed={...this.rotationSpeed},this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}const t=e-this.lastTickTS,s=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*s,this.rotationSpeed.y*this.options.rotationSpeedCorrection*s,this.rotationSpeed.z*this.options.rotationSpeedCorrection*s);else if(this.fading&&this.fadeStartSpeed){const r=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*s,this.rotationSpeed.y*this.options.rotationSpeedCorrection*s,this.rotationSpeed.z*this.options.rotationSpeedCorrection*s):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var vv=`#define GLSLIFY 1
|
|
38
38
|
attribute vec2 a_vertex;attribute vec2 a_texel;varying vec2 v_texel;void main(void){gl_Position=vec4(a_vertex,0.0,1.0);v_texel=a_texel;}`,gv=`#ifdef GL_ES
|
|
39
39
|
precision highp float;precision highp int;
|
|
40
40
|
#else
|
|
@@ -42,5 +42,5 @@ precision highp float;
|
|
|
42
42
|
#define GLSLIFY 1
|
|
43
43
|
#endif
|
|
44
44
|
#define PI 3.14159265358979323846264
|
|
45
|
-
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 Sv{constructor(e,t,s){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=s,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 pv(this.params.fov,this.params.orientation),this.cameraRotationManager=new mv(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"),s=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(s),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(s,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(s),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const s=this.gl.createShader(t);if(!s)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(s,e),this.gl.compileShader(s),!this.gl.getShaderParameter(s,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(s));return s}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(vv,this.gl.VERTEX_SHADER),s=this.createShader(gv,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,s),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,s=1;const r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:s=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-s,t,-s,t,s,-t,s]),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,s=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-s,n=t-r,o=e+s,l=t-r,d=e+s,u=t+r,c=e-s,h=t+r;return[a,n,o,l,d,u,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}}const bv=(i,e)=>new os(t=>{if(!window.IntersectionObserver)return;const s=()=>!!window.documentPictureInPicture.window||!!document.pictureInPictureElement,r={root:null},a=new IntersectionObserver((o,l)=>{o.forEach(d=>t.next(d.isIntersecting||s()))},{...r,...e});a.observe(i);const n=C(document,"visibilitychange").pipe(A(o=>!document.hidden||s())).subscribe(o=>t.next(o));return()=>{a.unobserve(i),n.unsubscribe}});class Ho{constructor(e){this.subscription=new ie,this.videoState=new le(ae.STOPPED),this.elementSize$=new b(void 0),this.elementVisible$=new b(!0),this.textTracksManager=new ft,this.droppedFramesManager=new Lo,this.videoTracks$=new b([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new dp,this.textTracks=[],this.syncPlayback=()=>{var t,s,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(l.state===q.Requested&&(o==null?void 0:o.to)!==p.PAUSED&&a!==ae.STOPPED&&n!==p.STOPPED){const u=(s=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&s!==void 0?s:0;this.seek(l.position-u,l.forcePrecise)}if(n===p.STOPPED){a!==ae.STOPPED&&(this.videoState.startTransitionTo(ae.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(ae.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}switch(a){case ae.STOPPED:this.videoState.startTransitionTo(ae.READY),this.prepare();return;case ae.READY:n===p.PAUSED?(this.videoState.setState(ae.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING?(this.videoState.startTransitionTo(ae.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.READY&&O(this.params.desiredState.playbackState,p.READY);return;case ae.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(ae.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case ae.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(ae.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&&O(this.params.desiredState.playbackState,p.PAUSED);return;default:return G(a)}}},this.init3DScene=t=>{var s,r,a;if(this.scene3D)return;this.scene3D=new Sv(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((s=t.projectionData)===null||s===void 0?void 0:s.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=Rt(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(Qe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new fv({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,s=xt(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:I.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:s,genericErrorListener:a,connect:(o,l)=>this.subscription.add(o.subscribe(l,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:s,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$:s.playing$,pause$:s.pause$,tracks$:this.videoTracks$.pipe(A(d=>d.map(({track:u})=>u)))}),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.playing$,e.firstFrameEvent$),a(s.canplay$,e.canplay$),a(s.inPiP$,e.inPiP$),a(s.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(ue(P),Ee()),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Ti(this.video,t.isLooped,r)),this.subscription.add(It(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ti(this.video,t.playbackRate,s.playbackRateState$,r)),a(Ap(this.video),this.elementSize$),a(bv(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),this.elementVisible$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(ae.PLAYING),O(t.playbackState,p.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(ae.PAUSED),O(t.playbackState,p.PAUSED)},r)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===ae.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var u;if(d===De.MANIFEST_READY){const c=[];this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();D(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((S,E)=>E.bitrate-S.bitrate),g=Array.from(h.video).sort((S,E)=>E.bitrate-S.bitrate),m=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const S of f){const E=tv(S);E&&this.audioTracks.push({track:E,representation:S})}for(const S of g){const E=ev(S);if(E){c.push({track:E,representation:S});const w=!this.params.tuning.isAudioDisabled&&iv(f,g,S);w&&this.audioRepresentations.set(S.id,w)}}this.videoTracks$.next(c);for(const S of m){const E=sv(S);E&&this.textTracks.push({track:E,representation:S})}this.params.output.availableVideoTracks$.next(c.map(({track:S})=>S)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:S})=>S)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:S})=>S));const v=this.selectVideoRepresentation();D(v),this.player.initRepresentations(v.id,(u=this.audioRepresentations.get(v.id))===null||u===void 0?void 0:u.id,this.params.sourceHls)}else d===De.REPRESENTATIOS_READY&&(this.videoState.setState(ae.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:I.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(N(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,C(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),u=this.player.state$.getTransition();if(d!==De.RUNNING||u||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation(),h=this.params.desiredState.autoVideoTrackLimits.getTransition();h&&this.params.output.autoVideoTrackLimits$.next(h.to);const f=this.params.desiredState.autoVideoTrackSwitching.getState(),g=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(c){let m=c.id;!this.elementVisible$.getValue()&&f&&(m=this.videoTracks$.getValue().map(S=>S.representation).sort((S,E)=>E.bitrate-S.bitrate).filter(S=>{const{width:E,height:w}=S,{width:$,height:k}=c,H=Math.min(E,w)+"p",Y=Math.min($,k)+"p";return Ji(H,Y)&&Ji(H,g)}).map(S=>S.id)[0]),this.player.switchRepresentation(ge.VIDEO,m).catch(n);const v=this.audioRepresentations.get(c.id);v&&this.player.switchRepresentation(ge.AUDIO,v.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(ce(),A(d=>{var u;return d&&((u=this.videoTracks$.getValue().find(({representation:{id:c}})=>c===d))===null||u===void 0?void 0:u.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var u,c;if(d!=null&&d.is3dVideo&&(!((u=this.params.tuning.spherical)===null||u===void 0)&&u.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider 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(A(({to:d})=>d===p.READY),ce());this.subscription.add(N(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(N(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===p.READY)));const l=N(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Le(["init"])).pipe(ze(0));this.subscription.add(l.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,s,r,a,n,o;const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id,u=(t=this.videoTracks$.getValue().find(({track:{id:E}})=>E===d))===null||t===void 0?void 0:t.track,c=this.params.output.currentVideoTrack$.getValue(),h=zt(this.video.buffered,this.video.currentTime*1e3),f=l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,g=Math.min(h/Math.min(f,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=Math.max(u&&!l&&(r=(s=this.audioRepresentations.get(u.id))===null||s===void 0?void 0:s.bitrate)!==null&&r!==void 0?r:0,c&&(n=(a=this.audioRepresentations.get(c.id))===null||a===void 0?void 0:a.bitrate)!==null&&n!==void 0?n:0),v=gs(this.videoTracks$.getValue().map(({track:E})=>E),{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:g,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),S=l?v!=null?v:u:u!=null?u:v;return S&&((o=this.videoTracks$.getValue().find(({track:E})=>E===S))===null||o===void 0?void 0:o.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){_t(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(ae.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:I.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),Lt(this.video)}}class yv extends Ho{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();s(t.timeUpdate$,e.position$),s(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}class Tv extends Ho{constructor(e){super(e),this.liveOffset=new Xr}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),s(t.timeUpdate$,e.liveBufferTime$),s(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(We({interval:Xi(Cr),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()===ae.PLAYING&&!this.player.isActiveLowLatency){const n=e.position$.getValue()+(r-1);e.position$.next(n),(a=this.liveOffset)===null||a===void 0||a.resetTo(-n*1e3)}})).add(We({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(A(({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(),s=this.videoState.getState(),r=t===p.PAUSED&&s===ae.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 He={};var z;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(z||(z={}));const di=(i,e)=>new os(t=>{const s=(r,a)=>t.next(a);return i.on(e,s),()=>i.off(e,s)});class Ev{constructor(e){this.subscription=new ie,this.videoState=new le(z.INITIALIZING),this.textTracksManager=new ft,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(t!==z.INITIALIZING)switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===q.Requested&&this.seek(a.position),s){case p.STOPPED:switch(t){case z.STOPPED:break;case z.READY:case z.PLAYING:case z.PAUSED:this.stop();break;default:G(t)}break;case p.READY:switch(t){case z.STOPPED:this.prepare();break;case z.READY:case z.PLAYING:case z.PAUSED:break;default:G(t)}break;case p.PLAYING:switch(t){case z.PLAYING:break;case z.STOPPED:this.prepare();break;case z.READY:case z.PAUSED:this.playIfAllowed();break;default:G(t)}break;case p.PAUSED:switch(t){case z.PAUSED:break;case z.STOPPED:this.prepare();break;case z.READY:this.videoState.setState(z.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED);break;case z.PLAYING:this.pause();break;default:G(t)}break;default:G(s)}},this.video=Rt(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(Qe(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),Lt(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:I.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(r=>{e||(He.Hls=r.default,He.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(s),e=!0})}init(){D(He.Hls,"hls.js not loaded"),this.hls=new He.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(z.STOPPED)}subscribe(){D(He.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=d=>{t.error$.next({id:"HlsJsProvider",category:I.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=xt(this.video),a=(d,u)=>this.subscription.add(d.subscribe(u,s));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(Ti(this.video,e.isLooped,s)),this.subscription.add(It(this.video,e.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ti(this.video,e.playbackRate,r.playbackRateState$,s)),this.subscription.add(di(this.hls,He.Events.ERROR).subscribe(d=>{var u;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:I.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${(u=d.err)===null||u===void 0?void 0:u.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(z.PLAYING),O(e.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED),O(e.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())===null||d===void 0?void 0:d.to)===z.READY&&this.videoState.setState(z.READY),this.videoState.getState()===z.PLAYING&&this.playIfAllowed()},s)),a(di(this.hls,He.Events.MANIFEST_PARSED).pipe(A(({levels:d})=>d.reduce((u,c)=>{var h,f;const g=c.name||c.height.toString(10),{width:m,height:v}=c,S=(f=vs((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:gi({width:m,height:v});if(!S)return u;const E=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,w={id:g.toString(),quality:S,bitrate:c.bitrate/1e3,size:{width:m,height:v},fps:E};return this.trackLevels.set(g,{track:w,level:c}),u.push(w),u},[]))),t.availableVideoTracks$),a(di(this.hls,He.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){const u=[];for(const c of d.subtitleTracks){const h=c.name,f=c.attrs.URI||"",g=c.lang,m="internal";u.push({id:h,url:f,language:g,type:m})}e.internalTextTracks.startTransitionTo(u)}}),a(di(this.hls,He.Events.LEVEL_LOADING).pipe(A(({url:d})=>Qe(d))),t.hostname$),this.subscription.add(Xe(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:s}));const n=d=>{var u;return(u=Array.from(this.trackLevels.values()).find(({level:c})=>c===d))===null||u===void 0?void 0:u.track},o=di(this.hls,He.Events.LEVEL_SWITCHED).pipe(A(({level:d})=>n(this.hls.levels[d])));o.pipe(ue(P)).subscribe(t.currentVideoTrack$,s),this.subscription.add(Xe(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),d=>{var u;if(Q(d))return;const c=(u=this.trackLevels.get(d.id))===null||u===void 0?void 0:u.level;if(!c)return;const h=this.hls.levels.indexOf(c),f=this.hls.currentLevel,g=this.hls.levels[f];!g||c.bitrate>g.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o,onError:s})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const l=N(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Le(["init"])).pipe(ze(0));this.subscription.add(l.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(z.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(z.PLAYING),await _t(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:I.DOM,thrown:t}))||(this.videoState.setState(z.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))}pause(){this.videoState.startTransitionTo(z.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(z.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0)}}const An="X-Playback-Duration";var kn=async i=>{var e;const t=await mi(i),s=await t.text(),r=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(s))===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 $v=i=>{let e=null;if(i.QUALITY&&(e=vs(i.QUALITY)),!e&&i.RESOLUTION){const[t,s]=i.RESOLUTION.split("x").map(r=>parseInt(r,10));e=gi({width:t,height:s})}return e!=null?e:null},wv=(i,e)=>{var t,s;const r=i.split(`
|
|
46
|
-
`),a=[],n=[];for(let o=0;o<r.length;o++){const l=r[o],d=l.match(/^#EXT-X-STREAM-INF:(.+)/),u=l.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!d&&!u)){if(d){const c=is(d[1].split(",").map(E=>E.split("="))),h=(t=c.QUALITY)!==null&&t!==void 0?t:`stream-${c.BANDWIDTH}`,f=$v(c);let g;c.BANDWIDTH&&(g=parseInt(c.BANDWIDTH,10)/1e3||void 0),!g&&c["AVERAGE-BANDWIDTH"]&&(g=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const m=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0;let v;if(c.RESOLUTION){const[E,w]=c.RESOLUTION.split("x").map($=>parseInt($,10));E&&w&&(v={width:E,height:w})}const S=new URL(r[++o],e).toString();f&&a.push({id:h,quality:f,url:S,bandwidth:g,size:v,fps:m})}if(u){const c=is(u[1].split(",").map(m=>m.split("=")).map(([m,v])=>[m,v.replace(/^"|"$/g,"")])),h=(s=c.URI)===null||s===void 0?void 0:s.replace(/playlist$/,"subtitles.vtt"),f=c.LANGUAGE,g=c.NAME;h&&f&&n.push({type:"internal",id:f,label:g,language:f,url:h,isAuto:!1})}}}if(!a.length)throw new Error("Empty manifest");return{qualityManifests:a,textTracks:n}},Av=i=>new Promise(e=>{setTimeout(()=>{e()},i)});let nr=0;const sa=async(i,e=i,t)=>{const r=await(await mi(i)).text();nr+=1;try{const{qualityManifests:a,textTracks:n}=wv(r,e);return{qualityManifests:a,textTracks:n}}catch(a){if(nr<=t.manifestRetryMaxCount)return await Av(ji(nr-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),sa(i,e,t)}return{qualityManifests:[],textTracks:[]}};var ee;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(ee||(ee={}));class kv{constructor(e){var t;this.subscription=new ie,this.videoState=new le(ee.STOPPED),this.textTracksManager=new ft,this.manifests$=new b([]),this.liveOffset=new Xr,this.manifestStartTime$=new b(void 0),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(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition(),d=this.params.desiredState.autoVideoTrackLimits.getTransition();if(a===p.STOPPED){r!==ee.STOPPED&&(this.videoState.startTransitionTo(ee.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(ee.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(r===ee.STOPPED){this.videoState.startTransitionTo(ee.READY),this.prepare();return}if(o||l||d){const h=this.videoState.getState();this.videoState.setState(ee.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),d&&this.params.output.autoVideoTrackLimits$.next(d.to),c.state===q.None&&this.params.desiredState.seekState.setState({state:q.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==p.PAUSED&&c.state===q.Requested){this.videoState.startTransitionTo(ee.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case ee.READY:a===p.READY?O(this.params.desiredState.playbackState,p.READY):a===p.PAUSED?(this.videoState.setState(ee.PAUSED),this.liveOffset.pause(),O(this.params.desiredState.playbackState,p.PAUSED)):a===p.PLAYING&&(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed());return;case ee.PLAYING:a===p.PAUSED?(this.videoState.startTransitionTo(ee.PAUSED),this.liveOffset.pause(),this.video.pause()):(n==null?void 0:n.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case ee.PAUSED:if(a===p.PLAYING)if(this.videoState.startTransitionTo(ee.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(n==null?void 0:n.to)===p.PAUSED&&(O(this.params.desiredState.playbackState,p.PAUSED),this.liveOffset.pause());return;case ee.CHANGING_MANIFEST:break;default:return G(r)}},this.params=e,this.video=Rt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Ae.INVARIANT,url:this.params.source.url},sa(Me(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:s})=>{s.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:I.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:I.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),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(Qe(this.params.source.url)),this.maxSeekBackTime$=new b((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t,s,r;const{autoVideoTrackSwitching:a,videoTrack:n}=this.params.desiredState,o=a.getState(),l=n.getTransition(),d=(r=(t=(e=l==null?void 0:l.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(s=n.getState())===null||s===void 0?void 0:s.id)!==null&&r!==void 0?r:"master",u=this.manifests$.getValue();if(!u.length)return;const c=o?"master":d;return o&&!l&&n.startTransitionTo(this.masterManifest),u.find(h=>h.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsLiveProvider",category:I.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=xt(this.video),a=(o,l)=>this.subscription.add(o.subscribe(l,s));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(It(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(ti(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ee.PLAYING),O(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(ee.PAUSED),O(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ee.READY&&this.videoState.setState(ee.READY),this.videoState.getState()===ee.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.maxSeekBackTime$.pipe(ce(),A(o=>-o/1e3)).subscribe(this.params.output.duration$,s)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&P(d.to)){const c=d.to.id;this.params.desiredState.videoTrack.setState(d.to);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Qe(h.url)))}u&&this.params.desiredState.autoVideoTrackSwitching.setState(u.to),l&&l.from===ee.CHANGING_MANIFEST&&this.videoState.setState(l.to),o&&o.state===q.Requested&&this.seek(o.position)},s)),this.subscription.add(r.loadedData$.subscribe(()=>{var o,l,d;const u=(d=(l=(o=this.video)===null||o===void 0?void 0:o.getStartDate)===null||l===void 0?void 0:l.call(o))===null||d===void 0?void 0:d.getTime();this.manifestStartTime$.next(u||void 0)},s)),this.subscription.add(We({startTime:this.manifestStartTime$.pipe(ue(P)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:l})=>this.params.output.liveTime$.next(o+l*1e3),s)),this.subscription.add(this.manifests$.pipe(A(o=>o.map(({id:l,quality:d,size:u,bandwidth:c,fps:h})=>({id:l,quality:d,size:u,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,s));const n=N(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Le(["init"])).pipe(ze(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Lt(this.video)}prepare(){var e,t;const s=this.selectManifest();if(Q(s))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URL(s.url);if((r||a)&&s.id===this.masterManifest.id){const{max:d,min:u}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:a)!==null&&t!==void 0?t:{};for(const[c,h]of[[d,"mq"],[u,"lq"]]){const f=String(parseFloat(c||""));h&&c&&n.searchParams.set(h,f)}}const o=this.params.format===y.HLS_LIVE_CMAF?pe.DASH_CMAF_OFFSET_P:pe.OFFSET_P,l=Me(n.toString(),this.liveOffset.getTotalOffset(),o);this.video.setAttribute("src",l),this.video.load(),kn(l).then(d=>{var u;if(!Q(d))this.maxSeekBackTime$.next(d);else{const c=(u=this.params.source.maxSeekBackTime)!==null&&u!==void 0?u:this.maxSeekBackTime$.getValue();if(Q(c)||!isFinite(c))try{mi(l).then(h=>h.text()).then(h=>{var f;const g=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))===null||f===void 0?void 0:f[1];if(g){const m=new URL(g,l).toString();kn(m).then(v=>{Q(v)||this.maxSeekBackTime$.next(v)})}})}catch(h){}}})}playIfAllowed(){_t(this.video).then(e=>{e||(this.videoState.setState(ee.PAUSED),this.liveOffset.pause(),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:I.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3),this.params.output.seekedEvent$.next()}}var re;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(re||(re={}));class Pv{constructor(e){this.subscription=new ie,this.videoState=new le(re.STOPPED),this.textTracksManager=new ft,this.manifests$=new b([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const s=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),l=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r===p.STOPPED){s!==re.STOPPED&&(this.videoState.startTransitionTo(re.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(re.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.seekState.getState();if(s===re.STOPPED){this.videoState.startTransitionTo(re.READY),this.prepare();return}if(n||o||l){const c=this.videoState.getState();this.videoState.setState(re.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),l&&this.params.output.autoVideoTrackLimits$.next(l.to),u.state===q.None&&this.params.desiredState.seekState.setState({state:q.Requested,position:h*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==p.PAUSED&&u.state===q.Requested&&this.seek(u.position),s){case re.READY:r===p.READY?O(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(re.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed());return;case re.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(re.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case re.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;case re.CHANGING_MANIFEST:break;default:return G(s)}},this.params=e,this.video=Rt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Ae.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(Qe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),sa(Me(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:s})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(s)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:I.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var e,t,s,r;const{autoVideoTrackSwitching:a,videoTrack:n}=this.params.desiredState,o=a.getState(),l=n.getTransition(),d=(r=(t=(e=l==null?void 0:l.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(s=n.getState())===null||s===void 0?void 0:s.id)!==null&&r!==void 0?r:"master",u=this.manifests$.getValue();if(!u.length)return;const c=o?"master":d;return o&&!l&&n.startTransitionTo(this.masterManifest),u.find(h=>h.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsProvider",category:I.WTF,message:"HlsProvider internal logic error",thrown:o})},r=xt(this.video),a=(o,l)=>this.subscription.add(o.subscribe(l));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(Ti(this.video,t.isLooped,s)),this.subscription.add(It(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(ti(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(re.PLAYING),O(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(re.PAUSED),O(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===re.READY&&this.videoState.setState(re.READY),this.videoState.getState()===re.PLAYING&&this.playIfAllowed()},s).add(r.loadedMetadata$.subscribe(()=>{var o;const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&P(u.to)){const h=u.to.id;this.params.desiredState.videoTrack.setState(u.to);const f=this.manifests$.getValue().find(g=>g.id===h);if(f){this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Qe(f.url));const g=this.params.desiredState.playbackRate.getState(),m=(o=this.params.output.element$.getValue())===null||o===void 0?void 0:o.playbackRate;if(g!==m){const v=this.params.output.element$.getValue();v&&(this.params.desiredState.playbackRate.setState(g),v.playbackRate=g)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===re.CHANGING_MANIFEST&&this.videoState.setState(d.to),l.state===q.Requested&&this.seek(l.position)},s))),this.subscription.add(this.manifests$.pipe(A(o=>o.map(({id:l,quality:d,size:u,bandwidth:c,fps:h})=>({id:l,quality:d,size:u,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,s)),!vd()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:o}=this.video;this.subscription.add(N(C(o,"addtrack"),C(o,"removetrack"),C(o,"change"),Le(["init"])).subscribe(()=>{for(let l=0;l<o.length;l++)o[l].mode="hidden"},s))}const n=N(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Le(["init"])).pipe(ze(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Lt(this.video)}prepare(){var e,t;const s=this.selectManifest();if(Q(s))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URL(s.url);if((r||a)&&s.id===this.masterManifest.id){const{max:o,min:l}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:a)!==null&&t!==void 0?t:{};for(const[d,u]of[[o,"mq"],[l,"lq"]]){const c=String(parseFloat(d||""));u&&d&&n.searchParams.set(u,c)}}this.video.setAttribute("src",n.toString()),this.video.load()}playIfAllowed(){_t(this.video).then(e=>{e||(this.videoState.setState(re.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:I.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var de;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(de||(de={}));class Dv{constructor(e){this.subscription=new ie,this.videoState=new le(de.STOPPED),this.trackUrls={},this.textTracksManager=new ft,this.syncPlayback=()=>{var t,s,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition();if(n===p.STOPPED){a!==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),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.autoVideoTrackLimits.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.seekState.getState();if(d&&a!==de.READY&&!u){this.handleQualityLimitTransition(d.to.max);return}if(a===de.STOPPED){this.videoState.startTransitionTo(de.READY),this.prepare();return}if(u){const{currentTime:h}=this.video;this.prepare(),c.state===q.None&&this.params.desiredState.seekState.setState({state:q.Requested,position:h*1e3,forcePrecise:!0}),u.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((r=(s=this.trackUrls[u.to.id])===null||s===void 0?void 0:s.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===q.Requested&&this.seek(c.position),a){case de.READY:n===p.READY?O(this.params.desiredState.playbackState,p.READY):n===p.PAUSED?(this.videoState.setState(de.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING&&(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed());return;case de.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(de.PAUSED),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case de.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;default:return G(a)}},this.params=e,this.video=Rt(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,s],r)=>{const a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:s}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"MpegProvider",category:I.WTF,message:"MpegProvider internal logic error",thrown:o})},r=xt(this.video),a=(o,l)=>this.subscription.add(o.subscribe(l,s));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(Ti(this.video,t.isLooped,s)),this.subscription.add(It(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(ti(this.video,t.playbackRate,r.playbackRateState$,s)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(de.PLAYING),O(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED),O(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o,l;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===de.READY&&this.videoState.setState(de.READY);const d=this.params.desiredState.videoTrack.getTransition();if(d&&P(d.to)){this.params.desiredState.videoTrack.setState(d.to),this.params.output.currentVideoTrack$.next(this.trackUrls[d.to.id].track);const u=this.params.desiredState.playbackRate.getState(),c=(l=this.params.output.element$.getValue())===null||l===void 0?void 0:l.playbackRate;if(u!==c){const h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(u),h.playbackRate=u)}}this.videoState.getState()===de.PLAYING&&this.playIfAllowed()},s)),this.textTracksManager.connect(this.video,t,e);const n=N(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Le(["init"])).pipe(ze(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Lt(this.video)}prepare(){var e;const t=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id;D(t,"MpegProvider: track is not selected");let{url:s}=this.trackUrls[t];D(s,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(s=_r(s)),this.video.setAttribute("src",s),this.video.load(),this.params.output.hostname$.next(Qe(s))}playIfAllowed(){_t(this.video).then(e=>{e||(this.videoState.setState(de.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:I.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,s,r,a;let n,o=e;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const l=(s=Object.values(this.trackUrls).find(c=>!At(c.track.quality)&&Ji(c.track.quality,e)))===null||s===void 0?void 0:s.track,d=(r=this.params.desiredState.videoTrack.getState())===null||r===void 0?void 0:r.id,u=(a=this.trackUrls[d!=null?d:"0"])===null||a===void 0?void 0:a.track;if(l&&u&&Sr(u.quality,l.quality)&&(n=l),!n){const c=Object.values(this.trackUrls).filter(f=>!At(f.track.quality)&&Qt(f.track.quality,e)),h=c.length;h&&(n=c[h-1].track)}n&&(o=n.quality)}else if(!e){const l=Object.values(this.trackUrls).map(d=>d.track);n=gs(l,{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})}n&&(this.params.output.currentVideoTrack$.next(n),this.params.desiredState.videoTrack.startTransitionTo(n)),this.params.output.autoVideoTrackLimits$.next({max:o})}}const Pn=["stun:videostun.mycdn.me:80"],Rv=1e3,Lv=3,or=()=>null;class Iv{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=or,this.externalStopCallback=or,this.externalErrorCallback=or,this.options=this.normalizeOptions(t);const s=e.split("/");this.serverUrl=s.slice(0,s.length-1).join("/"),this.streamKey=s[s.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}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:Pn}]};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:I.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),s=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(s))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),Rv)}normalizeOptions(e={}){const t={stunServerList:Pn,maxRetryNumber:Lv,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var te;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(te||(te={}));class xv{constructor(e){this.videoState=new le(te.STOPPED),this.maxSeekBackTime$=new b(0),this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(s===p.STOPPED){t!==te.STOPPED&&(this.videoState.startTransitionTo(te.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(te.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===te.STOPPED){this.videoState.startTransitionTo(te.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case te.READY:s===p.PAUSED?(this.videoState.setState(te.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):s===p.PLAYING&&(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed());return;case te.PLAYING:s===p.PAUSED?(this.videoState.startTransitionTo(te.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case te.PAUSED:s===p.PLAYING?(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;default:return G(t)}},this.subscription=new ie,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Rt(e.container),this.liveStreamClient=new Iv(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),Lt(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,s=n=>{e.error$.next({id:"WebRTCLiveProvider",category:I.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};N(this.videoState.stateChangeStarted$.pipe(A(n=>({transition:n,type:"start"}))),this.videoState.stateChangeEnded$.pipe(A(n=>({transition:n,type:"end"})))).subscribe(({transition:n,type:o})=>{this.log({message:`[videoState change] ${o}: ${JSON.stringify(n)}`})});const r=xt(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,s));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),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)===te.READY&&this.videoState.setState(te.READY)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(te.PAUSED)},s)).add(r.playing$.subscribe(()=>{this.videoState.setState(te.PLAYING)},s)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(It(this.video,t.volume,r.volumeState$,s)).add(r.volumeState$.subscribe(e.volume$,s)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case te.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(p.STOPPED);break;case te.READY:break;case te.PAUSED:t.playbackState.setState(p.PAUSED);break;case te.PLAYING:t.playbackState.setState(p.PLAYING);break;default:return G(n.to)}},s)).add(N(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Le(["init"])).pipe(ze(0)).subscribe(this.syncPlayback.bind(this),s)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),s))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Qe(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:Ae.INVARIANT}),this.video.srcObject=e,O(this.params.desiredState.playbackState,p.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(te.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:I.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){_t(this.video).then(e=>{e||(this.videoState.setState(te.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:I.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class Dn{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 dr,lr,ur,cr,Ni,hr,Fi,fr,Vi,pr,Ui,mr,Hi,vr,Gi,gr;const Go=Mr().device===gd.Android,ht=document.createElement("video"),_v='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Cv='video/mp4; codecs="hev1.1.6.L93.B0"',Yo='video/webm; codecs="vp09.00.10.08"',jo='video/webm; codecs="av01.0.00M.08"',Ov='audio/mp4; codecs="mp4a.40.2"',Mv='audio/webm; codecs="opus"',Tt={mms:Uo(),mse:cv(),hls:!!(!((dr=ht.canPlayType)===null||dr===void 0)&&dr.call(ht,"application/x-mpegurl")||!((lr=ht.canPlayType)===null||lr===void 0)&&lr.call(ht,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Pe={mp4:!!(!((ur=ht.canPlayType)===null||ur===void 0)&&ur.call(ht,"video/mp4")),webm:!!(!((cr=ht.canPlayType)===null||cr===void 0)&&cr.call(ht,"video/webm")),cmaf:!0},qe={h264:!!(!((hr=(Ni=yt())===null||Ni===void 0?void 0:Ni.isTypeSupported)===null||hr===void 0)&&hr.call(Ni,_v)),h265:!!(!((fr=(Fi=yt())===null||Fi===void 0?void 0:Fi.isTypeSupported)===null||fr===void 0)&&fr.call(Fi,Cv)),vp9:!!(!((pr=(Vi=yt())===null||Vi===void 0?void 0:Vi.isTypeSupported)===null||pr===void 0)&&pr.call(Vi,Yo)),av1:!!(!((mr=(Ui=yt())===null||Ui===void 0?void 0:Ui.isTypeSupported)===null||mr===void 0)&&mr.call(Ui,jo)),aac:!!(!((vr=(Hi=yt())===null||Hi===void 0?void 0:Hi.isTypeSupported)===null||vr===void 0)&&vr.call(Hi,Ov)),opus:!!(!((gr=(Gi=yt())===null||Gi===void 0?void 0:Gi.isTypeSupported)===null||gr===void 0)&&gr.call(Gi,Mv))},li=(qe.h264||qe.h265)&&qe.aac;var ct;(function(i){i.VP9="vp9",i.AV1="av1",i.NONE="none",i.SMOOTH="smooth",i.POWER_EFFICIENT="power_efficient"})(ct||(ct={}));var tt;(function(i){i.DASH="dash",i.HLS="hls",i.MPEG="mpeg"})(tt||(tt={}));let Et;const Bv=async()=>{if(!window.navigator.mediaCapabilities)return;const i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:jo}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:Yo}})]);Et={[y.DASH_WEBM_AV1]:e,[y.DASH_WEBM]:t}};try{Bv()}catch(i){console.error(i)}const vi=Tt.hls&&Pe.mp4,Nv=()=>Object.keys(qe).filter(i=>qe[i]),Fv=(i,e=!1,t=!1)=>{const s=Tt.mse||Tt.mms&&t;return i.filter(r=>{switch(r){case y.DASH_SEP:return s&&Pe.mp4&&li;case y.DASH_WEBM:return s&&Pe.webm&&qe.vp9&&qe.opus;case y.DASH_WEBM_AV1:return s&&Pe.webm&&qe.av1&&qe.opus;case y.DASH_LIVE:return Tt.mse&&Pe.mp4&&li;case y.DASH_LIVE_CMAF:return s&&Pe.mp4&&li&&Pe.cmaf;case y.DASH_ONDEMAND:return s&&Pe.mp4&&li;case y.HLS:case y.HLS_ONDEMAND:return vi||e&&Tt.mse&&Pe.mp4&&li;case y.HLS_LIVE:case y.HLS_LIVE_CMAF:return vi;case y.MPEG:return Pe.mp4;case y.DASH_LIVE_WEBM:return!1;case y.WEB_RTC_LIVE:return Tt.webrtc&&Tt.ws&&qe.h264&&(Pe.mp4||Pe.webm);default:return G(r)}})},ui=i=>{const e=y.DASH_WEBM,t=y.DASH_WEBM_AV1;switch(i){case ct.VP9:return[e,t];case ct.AV1:return[t,e];case ct.NONE:return[];case ct.SMOOTH:return Et?Et[t].smooth?[t,e]:Et[e].smooth?[e,t]:[t,e]:[e,t];case ct.POWER_EFFICIENT:return Et?Et[t].powerEfficient?[t,e]:Et[e].powerEfficient?[e,t]:[t,e]:[e,t];default:G(i)}return[e,t]},Vv=({webmCodec:i,androidPreferredFormat:e})=>{if(Go)switch(e){case tt.MPEG:return[y.MPEG,...ui(i),y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND];case tt.HLS:return[y.HLS,y.HLS_ONDEMAND,...ui(i),y.DASH_SEP,y.DASH_ONDEMAND,y.MPEG];case tt.DASH:return[...ui(i),y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG]}return vi?[...ui(i),y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG]:[...ui(i),y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG]},Uv=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{const s=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=[...s,...r],n=[...r,...s];let o;if(Go)switch(i){case tt.DASH:{o=a;break}case tt.HLS:case tt.MPEG:{o=n;break}}else vi?o=n:o=a;return t?[y.WEB_RTC_LIVE,...o]:[...o,y.WEB_RTC_LIVE]},Rn=i=>i?[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 Hv=i=>new os(e=>{const t=new ie,s=i.desiredPlaybackState$.stateChangeStarted$.pipe(A(({from:d,to:u})=>`${d}-${u}`)),r=i.desiredPlaybackState$.stateChangeEnded$,a=i.providerChanged$.pipe(A(({type:d})=>d!==void 0)),n=new x;let o=0,l="unknown";return t.add(s.subscribe(d=>{o&&window.clearTimeout(o),l=d,o=window.setTimeout(()=>n.next(d),i.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),l="unknown",o=0})),t.add(a.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>n.next(l),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const Gv={chunkDuration:5e3,maxParallelRequests:5};class Yv{constructor(e){this.current$=new b({type:void 0}),this.providerError$=new x,this.noAvailableProvidersError$=new x,this.providerOutput={position$:new b(0),duration$:new b(1/0),volume$:new b({muted:!1,volume:1}),currentVideoTrack$:new b(void 0),availableVideoTracks$:new b([]),availableAudioTracks$:new b([]),isAudioAvailable$:new b(!0),autoVideoTrackLimitingAvailable$:new b(!1),autoVideoTrackLimits$:new b(void 0),currentBuffer$:new b(void 0),isBuffering$:new b(!0),error$:new x,warning$:new x,willSeekEvent$:new x,seekedEvent$:new x,loopedEvent$:new x,endedEvent$:new x,firstBytesEvent$:new x,firstFrameEvent$:new x,canplay$:new x,isLive$:new b(void 0),isLowLatency$:new b(!1),canChangePlaybackSpeed$:new b(!0),liveTime$:new b(void 0),liveBufferTime$:new b(void 0),availableTextTracks$:new b([]),currentTextTrack$:new b(void 0),hostname$:new b(void 0),httpConnectionType$:new b(void 0),httpConnectionReused$:new b(void 0),inPiP$:new b(!1),inFullscreen$:new b(!1),element$:new b(void 0),availableSources$:new b(void 0),is3DVideo$:new b(!1)},this.subscription=new ie,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Fv([...Uv(this.params.tuning),...Vv(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>P(e.sources[o])),{forceFormat:s,formatsToAvoid:r}=this.params.tuning;let a=[];s?a=[s]: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 Dn(a);const n=[...Rn(!0),...Rn(!1)];this.chromecastFormatsIterator=new Dn(n.filter(o=>P(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(Q(t)){this.handleNoFormatsError(e);return}let s;try{s=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:I.WTF,message:"Failed to create provider",thrown:r})}s?this.current$.next({type:t,provider:s,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,s=this.params.desiredState.seekState.getState(),r=s.state!==q.None;if(this.params.desiredState.seekState.setState({state:q.Requested,position:r?s.position:t,forcePrecise:r?s.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 be.SCREEN:return this.createScreenProvider(t);case be.CHROMECAST:return this.createChromecastProvider(t);default:return G(e)}}createScreenProvider(e){const{sources:t,container:s,desiredState:r}=this.params,a=this.providerOutput,n={container:s,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case y.DASH_SEP:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t[y.HLS_ONDEMAND]||t[y.HLS]);return D(o),new yv({...n,source:o,sourceHls:l})}case y.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return D(o),new Tv({...n,source:o})}case y.HLS:case y.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return D(o),vi||!this.params.tuning.useHlsJs?new Pv({...n,source:o}):new Ev({...n,source:o})}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return D(o),new kv({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case y.MPEG:{const o=this.applyFailoverHost(t[e]);return D(o),new Dv({...n,source:o})}case y.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return D(o),new $p({...n,source:o,config:{...Gv,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case y.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return D(o),new xv({container:s,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 G(e)}}createChromecastProvider(e){const{sources:t,container:s,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return D(o),new Nf({connection:o,meta:a,container:s,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?be.CHROMECAST:be.SCREEN}chooseFormat(e){switch(e){case be.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case be.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return G(e)}}skipFormat(e){switch(e){case be.SCREEN:return this.screenFormatsIterator.next();case be.CHROMECAST:return this.chromecastFormatsIterator.next();default:return G(e)}}handleNoFormatsError(e){switch(e){case be.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case be.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return G(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const s=r=>{const a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:s(e.url)}}return is(Object.entries(e).map(([r,a])=>[r,s(a)]))}initProviderErrorHandling(){const e=new ie;let t=!1,s=0;return e.add(N(this.providerOutput.error$,Hv({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(A(r=>({id:`ProviderHangup:${r}`,category:I.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(ue(({to:a})=>a===p.PLAYING),Ee()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{const a=this.current$.getValue().destination;if(a===be.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(be.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=r.category===I.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=s<this.params.tuning.providerErrorLimit;o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(s++,this.reinitProvider()):this.switchToNextProvider(a!=null?a:be.SCREEN)}})),e}}const jv=5e3,Ln="one_video_throughput",In="one_video_rtt",it=window.navigator.connection,xn=()=>{const i=it==null?void 0:it.downlink;if(P(i)&&i!==10)return i*1e3},_n=()=>{const i=it==null?void 0:it.rtt;if(P(i)&&i!==3e3)return i},Cn=(i,e,t)=>{const s=t*8,r=s/i;return s/(r+e)};class hi{constructor(e){var t,s;this.subscription=new ie,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=hi.load(Ln)||(e.useBrowserEstimation?xn():void 0)||jv,a=(s=(t=hi.load(In))!==null&&t!==void 0?t:e.useBrowserEstimation?_n():void 0)!==null&&s!==void 0?s:0;if(this.throughput$=new b(r),this.rtt$=new b(a),this.rttAdjustedThroughput$=new b(Cn(r,a,e.rttPenaltyRequestSize)),this.throughput=Or.getSmoothedValue(r,-1,e),this.rtt=Or.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const l=xn();l&&this.throughput.next(l);const d=_n();P(d)&&this.rtt.next(d)};it&&"onchange"in it&&this.subscription.add(C(it,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{xs.set(Ln,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{xs.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(We({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(A(({throughput:n,rtt:o})=>Cn(n,o,e.rttPenaltyRequestSize)),ue(n=>{const o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,s=ne();const r=new ie;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(C(e,"progress").pipe(Ee()).subscribe(a=>{t=a.loaded,s=ne()}));break;case 1:case 0:r.add(C(e,"loadstart").subscribe(()=>{t=0,s=ne()}));break}r.add(C(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=ne(),l=n-t,d=o-s;this.addRawSpeed(l,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){const s=e.getReader();if(!s){e.cancel("Could not get reader");return}let r=0,a=ne(),n=0,o=ne();const l=u=>{this.concurrentDownloads.delete(e),s.releaseLock(),e.cancel(`Throughput Estimator error: ${u}`).catch(()=>{})},d=async({done:u,value:c})=>{if(u)!t&&this.addRawSpeed(r,ne()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){if(ne()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=c.byteLength;else{const f=o-a;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,a=ne()}o=ne()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&ne()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,ne()-o,this.concurrentDownloads.size),n=0,o=ne());await(s==null?void 0:s.read().then(d,l))}};this.concurrentDownloads.add(e),s==null||s.read().then(d,l)}addRawSpeed(e,t,s=1,r=!1){if(hi.sanityCheck(e,t,r)){const a=e*8/t;this.throughput.next(a*s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,s=!1){const r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||s&&e<1e4||!s&&e<10*1024||!s&&t<=20)}static load(e){var t;const s=xs.get(e);if(P(s))return(t=parseInt(s,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,lowLatency:{continuesByteSequenceInterval:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:Ae.Q_480P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Ae.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},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:ct.VP9,androidPreferredFormat:tt.MPEG,preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,dashMaxWaitingDuration:5e3,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},qv=i=>{var e;return{...Sd(i,On),configName:[...(e=i.configName)!==null&&e!==void 0?e:[],...On.configName]}};var Mn=({seekState:i,position$:e})=>N(i.stateChangeEnded$.pipe(A(({to:t})=>{var s;return t.state===q.None?void 0:((s=t.position)!==null&&s!==void 0?s:NaN)/1e3}),ue(P)),e.pipe(ue(()=>i.getState().state===q.None))),zv=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return D(e,`Wrong container or containerId {${i.container}}`),e};const Wv=(i,e,t,s)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(ue(r=>r.length>0),Ee()).subscribe(r=>{r.find(s)&&e.startTransitionTo(i)}):(i===void 0||t!=null&&t.getValue().find(s))&&e.startTransitionTo(i)};class Zv{constructor(e={configName:[]}){if(this.subscription=new ie,this.logger=new bd,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.desiredState={playbackState:new le(p.STOPPED),seekState:new le({state:q.None}),volume:new le({volume:1,muted:!1}),videoTrack:new le(void 0),autoVideoTrackSwitching:new le(!0),autoVideoTrackLimits:new le({}),isLooped:new le(!1),playbackRate:new le(1),externalTextTracks:new le([]),internalTextTracks:new le([]),currentTextTrack:new le(void 0),textTrackCuesSettings:new le({}),cameraOrientation:new le({x:0,y:0})},this.info={playbackState$:new b(p.STOPPED),position$:new b(0),duration$:new b(1/0),muted$:new b(!1),volume$:new b(1),availableQualities$:new b([]),availableQualitiesFps$:new b({}),availableAudioTracks$:new b([]),isAudioAvailable$:new b(!0),currentQuality$:new b(void 0),isAutoQualityEnabled$:new b(!0),autoQualityLimitingAvailable$:new b(!1),autoQualityLimits$:new b({}),currentPlaybackRate$:new b(1),currentBuffer$:new b({start:0,end:0}),isBuffering$:new b(!0),isStalled$:new b(!1),isEnded$:new b(!1),isLooped$:new b(!1),isLive$:new b(void 0),canChangePlaybackSpeed$:new b(void 0),atLiveEdge$:new b(void 0),atLiveDurationEdge$:new b(void 0),liveTime$:new b(void 0),liveBufferTime$:new b(void 0),currentFormat$:new b(void 0),availableTextTracks$:new b([]),currentTextTrack$:new b(void 0),throughputEstimation$:new b(void 0),rttEstimation$:new b(void 0),videoBitrate$:new b(void 0),hostname$:new b(void 0),httpConnectionType$:new b(void 0),httpConnectionReused$:new b(void 0),surface$:new b(ut.NONE),chromecastState$:new b(ve.NOT_AVAILABLE),chromecastDeviceName$:new b(void 0),intrinsicVideoSize$:new b(void 0),availableSources$:new b(void 0),is3DVideo$:new b(!1)},this.events={inited$:new x,ready$:new x,started$:new x,playing$:new x,paused$:new x,stopped$:new x,willStart$:new x,willResume$:new x,willPause$:new x,willStop$:new x,willDestruct$:new x,watchCoverageRecord$:new x,watchCoverageLive$:new x,managedError$:new x,fatalError$:new x,ended$:new x,looped$:new x,seeked$:new x,willSeek$:new x,firstBytes$:new x,firstFrame$:new x,canplay$:new x,log$:new x},this.experimental={element$:new b(void 0),tuningConfigName$:new b([]),enableDebugTelemetry$:new b(!1),dumpTelemetry:ap},this.initLogs(),this.tuning=qv(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 hi(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,s,r)=>{const a=Reflect.get(t,s,r);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const l=n.map(c=>JSON.stringify(c,(h,f)=>{const g=typeof f;return["number","string","boolean"].includes(g)?f:f===null?null:`<${g}>`})),d=`Player.${String(s)}`,u=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:I.WTF,message:u,thrown:o}),o}}}})}initVideo(e){var t,s,r;return this.config=e,this.domContainer=zv(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Yv({sources:e.sources,meta:(s=e.meta)!==null&&s!==void 0?s:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,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?C(document,"visibilitychange").pipe(Ee()).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 s=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=s&&!r&&(e=s-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:q.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()===ve.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()===ve.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){D(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(ue(s=>s.length>0),Ee()).subscribe(s=>{this.setVideoTrackIdByQuality(s,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var t;D(this.providerContainer);const s=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return s&&(this.desiredState.playbackRate.setState(e),s.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return Wv(e,this.desiredState.currentTextTrack,(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$,s=>s.id===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 s=this.getScene3D();return s&&s.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const s=this.getScene3D();if(s){const r=s.getCameraRotation(),a=s.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(){if(!this.providerContainer)return 0;const e=this.providerContainer.providerOutput.element$.getValue();if(Q(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),s=t.state===q.None?void 0:t.position;return P(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const s=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=s==null?void 0:s.provider)===null||t===void 0)&&t.scene3D)return s.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((s,{width:r})=>s||r||0,0),height:e.reduce((s,{height:r})=>s||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(N(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(A(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(A(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(A(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(A(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(A(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(ue(({from:e})=>e===p.STOPPED),Ee()).subscribe(()=>{this.initedAt=ne(),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===q.Requested?this.desiredState.seekState.setState({...n,state:q.Applying}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:I.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===q.Applying&&(this.desiredState.seekState.setState({state:q.None}),this.events.seeked$.next())})).add(e.current$.pipe(A(n=>n.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(A(n=>n.destination),ce()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(A(n=>n.map(({quality:o})=>o).sort((o,l)=>At(o)?1:At(l)?-1:Qt(l,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{const o={};for(const l of n)l.fps&&(o[l.quality]=l.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(ce()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(ce()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(ce()).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(A(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(We({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Mn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(A(({isLive:n,position:o,isLowLatency:l})=>{const d=l?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return n&&Math.abs(o)<d/1e3}),ce(),fi(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(We({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(A(({isLive:n,position:o,duration:l})=>n&&(Math.abs(l)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),ce(),fi(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(A(n=>n.muted),ce()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(A(n=>n.volume),ce()).subscribe(this.info.volume$)).add(Mn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(N(e.providerOutput.endedEvent$.pipe(Ki(!0)),e.providerOutput.seekedEvent$.pipe(Ki(!1))).pipe(ce()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(A(n=>({id:n?`No${n}`:"NoProviders",category:I.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(Ee(),A(n=>n!=null?n:ne()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(Ee(),A(()=>ne()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Ee(),A(()=>ne()-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 b(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const s=new b(!0);this.subscription.add(e.current$.subscribe(()=>s.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ue(({to:n})=>n===p.PLAYING),Ee()).subscribe(()=>s.next(!1)));let r=0;const a=N(e.providerOutput.isBuffering$,t,s).pipe(A(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||s.getValue();return n&&!o}),ce());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(N(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,l;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:(l=n==null?void 0:n.size)===null||l===void 0?void 0:l.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(N(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),l=e.providerOutput.element$.getValue(),d=this.chromecastInitializer.castState$.getValue();let u;d===ve.CONNECTED?u=ut.SECOND_SCREEN:l?n?u=ut.PIP:o?u=ut.FULLSCREEN:u=ut.INLINE:u=ut.NONE,this.info.surface$.getValue()!==u&&this.info.surface$.next(u)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(A(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 ie;this.subscription.add(t),this.subscription.add(e.current$.pipe(ce((s,r)=>s.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ue(s=>s.length>0),Ee()).subscribe(s=>{this.setStartingVideoTrack(s)}))}))}setStartingVideoTrack(e){var t;let s;const r=(t=this.desiredState.videoTrack.getState())===null||t===void 0?void 0:t.quality;r&&(s=e.find(({quality:a})=>a===r),s||this.setAutoQuality(!0)),s||(s=gs(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(s),this.info.currentQuality$.next(s.quality),this.info.videoBitrate$.next(s.bitrate)}initLogs(){this.subscription.add(N(this.desiredState.videoTrack.stateChangeStarted$.pipe(A(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(A(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(A(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(A(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(A(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(A(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(A(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(A(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(A(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;D(this.providerContainer),D(t),rp(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(s=>sp(s)),this.providerContainer.current$.subscribe(({type:s})=>Mi("provider",s)),t.duration$.subscribe(s=>Mi("duration",s)),t.availableVideoTracks$.pipe(ue(s=>!!s.length),Ee()).subscribe(s=>Mi("tracks",s)),this.events.fatalError$.subscribe(new Ye("fatalError")),this.events.managedError$.subscribe(new Ye("managedError")),t.position$.subscribe(new Ye("position")),t.currentVideoTrack$.pipe(A(s=>s==null?void 0:s.quality)).subscribe(new Ye("quality")),this.info.currentBuffer$.subscribe(new Ye("buffer")),t.isBuffering$.subscribe(new Ye("isBuffering"))].forEach(s=>this.subscription.add(s)),Mi("codecs",Nv())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},s=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:I.DOM,message:String(r)})})};this.subscription.add(N(C(document,"visibilitychange"),C(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||s():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const s=e.find(r=>r.quality===t);s?this.desiredState.videoTrack.startTransitionTo(s):this.setAutoQuality(!0)}}const eg=`@vkontakte/videoplayer-core@${yd}`;export{ve as ChromecastState,br as HttpConnectionType,sg as Observable,p as PlaybackState,Zv as Player,eg as SDK_VERSION,rg as Subject,ag as Subscription,ut as Surface,yd as VERSION,ng as ValueSubject,y as VideoFormat,og as VideoQuality};
|
|
45
|
+
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 Sv{constructor(e,t,s){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=s,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 pv(this.params.fov,this.params.orientation),this.cameraRotationManager=new mv(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"),s=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(s),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(s,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(s),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const s=this.gl.createShader(t);if(!s)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(s,e),this.gl.compileShader(s),!this.gl.getShaderParameter(s,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(s));return s}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(vv,this.gl.VERTEX_SHADER),s=this.createShader(gv,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,s),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,s=1;const r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:s=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-s,t,-s,t,s,-t,s]),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,s=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,a=e-s,n=t-r,o=e+s,l=t-r,d=e+s,u=t+r,c=e-s,h=t+r;return[a,n,o,l,d,u,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}}const bv=(i,e)=>new os(t=>{if(!window.IntersectionObserver)return;const s=()=>{var o;return!!(!((o=window.documentPictureInPicture)===null||o===void 0)&&o.window)||!!document.pictureInPictureElement},r={root:null},a=new IntersectionObserver((o,l)=>{o.forEach(d=>t.next(d.isIntersecting||s()))},{...r,...e});a.observe(i);const n=C(document,"visibilitychange").pipe(w(o=>!document.hidden||s())).subscribe(o=>t.next(o));return()=>{a.unobserve(i),n.unsubscribe}});class Ho{constructor(e){this.subscription=new ie,this.videoState=new le(ae.STOPPED),this.elementSize$=new b(void 0),this.elementVisible$=new b(!0),this.textTracksManager=new ft,this.droppedFramesManager=new Lo,this.videoTracks$=new b([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new dp,this.textTracks=[],this.syncPlayback=()=>{var t,s,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(l.state===Y.Requested&&(o==null?void 0:o.to)!==p.PAUSED&&a!==ae.STOPPED&&n!==p.STOPPED){const u=(s=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&s!==void 0?s:0;this.seek(l.position-u,l.forcePrecise)}if(n===p.STOPPED){a!==ae.STOPPED&&(this.videoState.startTransitionTo(ae.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(ae.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}switch(a){case ae.STOPPED:this.videoState.startTransitionTo(ae.READY),this.prepare();return;case ae.READY:n===p.PAUSED?(this.videoState.setState(ae.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING?(this.videoState.startTransitionTo(ae.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.READY&&O(this.params.desiredState.playbackState,p.READY);return;case ae.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(ae.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case ae.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(ae.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&&O(this.params.desiredState.playbackState,p.PAUSED);return;default:return H(a)}}},this.init3DScene=t=>{var s,r,a;if(this.scene3D)return;this.scene3D=new Sv(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((s=t.projectionData)===null||s===void 0?void 0:s.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=Lt(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(Qe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new fv({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,s=_t(this.video),r=this.constructor.name,a=o=>{e.error$.next({id:r,category:I.WTF,message:`${r} internal logic error`,thrown:o})};return{output:e,desiredState:t,observableVideo:s,genericErrorListener:a,connect:(o,l)=>this.subscription.add(o.subscribe(l,a))}}subscribe(){const{output:e,desiredState:t,observableVideo:s,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$:s.playing$,pause$:s.pause$,tracks$:this.videoTracks$.pipe(w(d=>d.map(({track:u})=>u)))}),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.playing$,e.firstFrameEvent$),a(s.canplay$,e.canplay$),a(s.inPiP$,e.inPiP$),a(s.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(ue(k),Ee()),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Ti(this.video,t.isLooped,r)),this.subscription.add(xt(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(ii(this.video,t.playbackRate,s.playbackRateState$,r)),a(Ap(this.video),this.elementSize$),a(bv(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),this.elementVisible$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(ae.PLAYING),O(t.playbackState,p.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(ae.PAUSED),O(t.playbackState,p.PAUSED)},r)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===ae.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:d})=>{var u;if(d===De.MANIFEST_READY){const c=[];this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();D(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((S,E)=>E.bitrate-S.bitrate),g=Array.from(h.video).sort((S,E)=>E.bitrate-S.bitrate),m=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const S of f){const E=tv(S);E&&this.audioTracks.push({track:E,representation:S})}for(const S of g){const E=ev(S);if(E){c.push({track:E,representation:S});const $=!this.params.tuning.isAudioDisabled&&iv(f,g,S);$&&this.audioRepresentations.set(S.id,$)}}this.videoTracks$.next(c);for(const S of m){const E=sv(S);E&&this.textTracks.push({track:E,representation:S})}this.params.output.availableVideoTracks$.next(c.map(({track:S})=>S)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:S})=>S)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:S})=>S));const v=this.selectVideoRepresentation();D(v),this.player.initRepresentations(v.id,(u=this.audioRepresentations.get(v.id))===null||u===void 0?void 0:u.id,this.params.sourceHls)}else d===De.REPRESENTATIOS_READY&&(this.videoState.setState(ae.READY),this.player.initBuffer())},r));const n=d=>e.error$.next({id:"RepresentationSwitch",category:I.WTF,message:"Switching representations threw",thrown:d});this.subscription.add(N(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,C(this.video,"progress")).subscribe(()=>{const d=this.player.state$.getState(),u=this.player.state$.getTransition();if(d!==De.RUNNING||u||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const c=this.selectVideoRepresentation(),h=this.params.desiredState.autoVideoTrackLimits.getTransition();h&&this.params.output.autoVideoTrackLimits$.next(h.to);const f=this.params.desiredState.autoVideoTrackSwitching.getState(),g=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(c){let m=c.id;!this.elementVisible$.getValue()&&f&&(m=this.videoTracks$.getValue().map(S=>S.representation).sort((S,E)=>E.bitrate-S.bitrate).filter(S=>{const E=At(S),$=At(c);if(E&&$)return Ji(E,$)&&Ji(E,g)}).map(S=>S.id)[0]),this.player.switchRepresentation(ge.VIDEO,m).catch(n);const v=this.audioRepresentations.get(c.id);v&&this.player.switchRepresentation(ge.AUDIO,v.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(ce(),w(d=>{var u;return d&&((u=this.videoTracks$.getValue().find(({representation:{id:c}})=>c===d))===null||u===void 0?void 0:u.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(d=>{var u,c;if(d!=null&&d.is3dVideo&&(!((u=this.params.tuning.spherical)===null||u===void 0)&&u.enabled))try{this.init3DScene(d),e.is3DVideo$.next(!0)}catch(h){e.warning$.next({id:"DashProvider",message:`DashProvider 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),ce());this.subscription.add(N(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(N(o,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===p.READY)));const l=N(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Le(["init"])).pipe(ze(0));this.subscription.add(l.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,s,r,a,n,o;const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id,u=(t=this.videoTracks$.getValue().find(({track:{id:E}})=>E===d))===null||t===void 0?void 0:t.track,c=this.params.output.currentVideoTrack$.getValue(),h=Wt(this.video.buffered,this.video.currentTime*1e3),f=l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,g=Math.min(h/Math.min(f,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=Math.max(u&&!l&&(r=(s=this.audioRepresentations.get(u.id))===null||s===void 0?void 0:s.bitrate)!==null&&r!==void 0?r:0,c&&(n=(a=this.audioRepresentations.get(c.id))===null||a===void 0?void 0:a.bitrate)!==null&&n!==void 0?n:0),v=gs(this.videoTracks$.getValue().map(({track:E})=>E),{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:g,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),S=l?v!=null?v:u:u!=null?u:v;return S&&((o=this.videoTracks$.getValue().find(({track:E})=>E===S))===null||o===void 0?void 0:o.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ct(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(ae.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:I.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),It(this.video)}}class yv extends Ho{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();s(t.timeUpdate$,e.position$),s(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}class Tv extends Ho{constructor(e){super(e),this.liveOffset=new Xr}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),s(t.timeUpdate$,e.liveBufferTime$),s(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(We({interval:Xi(Cr),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var a;if(this.videoState.getState()===ae.PLAYING&&!this.player.isActiveLowLatency){const n=e.position$.getValue()+(r-1);e.position$.next(n),(a=this.liveOffset)===null||a===void 0||a.resetTo(-n*1e3)}})).add(We({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(),s=this.videoState.getState(),r=t===p.PAUSED&&s===ae.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 He={};var z;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(z||(z={}));const li=(i,e)=>new os(t=>{const s=(r,a)=>t.next(a);return i.on(e,s),()=>i.off(e,s)});class Ev{constructor(e){this.subscription=new ie,this.videoState=new le(z.INITIALIZING),this.textTracksManager=new ft,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(t!==z.INITIALIZING)switch((r==null?void 0:r.to)!==p.PAUSED&&a.state===Y.Requested&&this.seek(a.position),s){case p.STOPPED:switch(t){case z.STOPPED:break;case z.READY:case z.PLAYING:case z.PAUSED:this.stop();break;default:H(t)}break;case p.READY:switch(t){case z.STOPPED:this.prepare();break;case z.READY:case z.PLAYING:case z.PAUSED:break;default:H(t)}break;case p.PLAYING:switch(t){case z.PLAYING:break;case z.STOPPED:this.prepare();break;case z.READY:case z.PAUSED:this.playIfAllowed();break;default:H(t)}break;case p.PAUSED:switch(t){case z.PAUSED:break;case z.STOPPED:this.prepare();break;case z.READY:this.videoState.setState(z.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED);break;case z.PLAYING:this.pause();break;default:H(t)}break;default:H(s)}},this.video=Lt(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(Qe(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),It(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:I.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(r=>{e||(He.Hls=r.default,He.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(s),e=!0})}init(){D(He.Hls,"hls.js not loaded"),this.hls=new He.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(z.STOPPED)}subscribe(){D(He.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=d=>{t.error$.next({id:"HlsJsProvider",category:I.WTF,message:"HlsJsProvider internal logic error",thrown:d})},r=_t(this.video),a=(d,u)=>this.subscription.add(d.subscribe(u,s));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadStart$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),a(r.inPiP$,t.inPiP$),a(r.inFullscreen$,t.inFullscreen$),this.subscription.add(Ti(this.video,e.isLooped,s)),this.subscription.add(xt(this.video,e.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ii(this.video,e.playbackRate,r.playbackRateState$,s)),this.subscription.add(li(this.hls,He.Events.ERROR).subscribe(d=>{var u;d.fatal&&t.error$.next({id:["HlsJsFatal",d.type,d.details].join("_"),category:I.WTF,message:`HlsJs fatal ${d.type} ${d.details}, ${(u=d.err)===null||u===void 0?void 0:u.message} ${d.reason}`,thrown:d.error})})),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(z.PLAYING),O(e.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED),O(e.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var d;((d=this.videoState.getTransition())===null||d===void 0?void 0:d.to)===z.READY&&this.videoState.setState(z.READY),this.videoState.getState()===z.PLAYING&&this.playIfAllowed()},s)),a(li(this.hls,He.Events.MANIFEST_PARSED).pipe(w(({levels:d})=>d.reduce((u,c)=>{var h,f;const g=c.name||c.height.toString(10),{width:m,height:v}=c,S=(f=vs((h=c.attrs.QUALITY)!==null&&h!==void 0?h:""))!==null&&f!==void 0?f:At({width:m,height:v});if(!S)return u;const E=c.attrs["FRAME-RATE"]?parseFloat(c.attrs["FRAME-RATE"]):void 0,$={id:g.toString(),quality:S,bitrate:c.bitrate/1e3,size:{width:m,height:v},fps:E};return this.trackLevels.set(g,{track:$,level:c}),u.push($),u},[]))),t.availableVideoTracks$),a(li(this.hls,He.Events.MANIFEST_PARSED),d=>{if(d.subtitleTracks.length>0){const u=[];for(const c of d.subtitleTracks){const h=c.name,f=c.attrs.URI||"",g=c.lang,m="internal";u.push({id:h,url:f,language:g,type:m})}e.internalTextTracks.startTransitionTo(u)}}),a(li(this.hls,He.Events.LEVEL_LOADING).pipe(w(({url:d})=>Qe(d))),t.hostname$),this.subscription.add(Xe(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,d=>{this.hls.nextLevel=d?-1:this.hls.currentLevel,this.hls.loadLevel=d?-1:this.hls.loadLevel},{onError:s}));const n=d=>{var u;return(u=Array.from(this.trackLevels.values()).find(({level:c})=>c===d))===null||u===void 0?void 0:u.track},o=li(this.hls,He.Events.LEVEL_SWITCHED).pipe(w(({level:d})=>n(this.hls.levels[d])));o.pipe(ue(k)).subscribe(t.currentVideoTrack$,s),this.subscription.add(Xe(e.videoTrack,()=>n(this.hls.levels[this.hls.currentLevel]),d=>{var u;if(Q(d))return;const c=(u=this.trackLevels.get(d.id))===null||u===void 0?void 0:u.level;if(!c)return;const h=this.hls.levels.indexOf(c),f=this.hls.currentLevel,g=this.hls.levels[f];!g||c.bitrate>g.bitrate?this.hls.nextLevel=h:(this.hls.loadLevel=h,this.hls.loadLevel=h)},{changed$:o,onError:s})),a(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const l=N(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,Le(["init"])).pipe(ze(0));this.subscription.add(l.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(z.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(z.PLAYING),await Ct(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:I.DOM,thrown:t}))||(this.videoState.setState(z.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))}pause(){this.videoState.startTransitionTo(z.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(z.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0)}}const An="X-Playback-Duration";var kn=async i=>{var e;const t=await vi(i),s=await t.text(),r=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(s))===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 $v=i=>{let e=null;if(i.QUALITY&&(e=vs(i.QUALITY)),!e&&i.RESOLUTION){const[t,s]=i.RESOLUTION.split("x").map(r=>parseInt(r,10));e=At({width:t,height:s})}return e!=null?e:null},wv=(i,e)=>{var t,s;const r=i.split(`
|
|
46
|
+
`),a=[],n=[];for(let o=0;o<r.length;o++){const l=r[o],d=l.match(/^#EXT-X-STREAM-INF:(.+)/),u=l.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!d&&!u)){if(d){const c=is(d[1].split(",").map(E=>E.split("="))),h=(t=c.QUALITY)!==null&&t!==void 0?t:`stream-${c.BANDWIDTH}`,f=$v(c);let g;c.BANDWIDTH&&(g=parseInt(c.BANDWIDTH,10)/1e3||void 0),!g&&c["AVERAGE-BANDWIDTH"]&&(g=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const m=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0;let v;if(c.RESOLUTION){const[E,$]=c.RESOLUTION.split("x").map(A=>parseInt(A,10));E&&$&&(v={width:E,height:$})}const S=new URL(r[++o],e).toString();f&&a.push({id:h,quality:f,url:S,bandwidth:g,size:v,fps:m})}if(u){const c=is(u[1].split(",").map(m=>m.split("=")).map(([m,v])=>[m,v.replace(/^"|"$/g,"")])),h=(s=c.URI)===null||s===void 0?void 0:s.replace(/playlist$/,"subtitles.vtt"),f=c.LANGUAGE,g=c.NAME;h&&f&&n.push({type:"internal",id:f,label:g,language:f,url:h,isAuto:!1})}}}if(!a.length)throw new Error("Empty manifest");return{qualityManifests:a,textTracks:n}},Av=i=>new Promise(e=>{setTimeout(()=>{e()},i)});let nr=0;const sa=async(i,e=i,t)=>{const r=await(await vi(i)).text();nr+=1;try{const{qualityManifests:a,textTracks:n}=wv(r,e);return{qualityManifests:a,textTracks:n}}catch(a){if(nr<=t.manifestRetryMaxCount)return await Av(qi(nr-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),sa(i,e,t)}return{qualityManifests:[],textTracks:[]}};var ee;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(ee||(ee={}));class kv{constructor(e){var t;this.subscription=new ie,this.videoState=new le(ee.STOPPED),this.textTracksManager=new ft,this.manifests$=new b([]),this.liveOffset=new Xr,this.manifestStartTime$=new b(void 0),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(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition(),d=this.params.desiredState.autoVideoTrackLimits.getTransition();if(a===p.STOPPED){r!==ee.STOPPED&&(this.videoState.startTransitionTo(ee.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(ee.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(r===ee.STOPPED){this.videoState.startTransitionTo(ee.READY),this.prepare();return}if(o||l||d){const h=this.videoState.getState();this.videoState.setState(ee.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),d&&this.params.output.autoVideoTrackLimits$.next(d.to),c.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((n==null?void 0:n.to)!==p.PAUSED&&c.state===Y.Requested){this.videoState.startTransitionTo(ee.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case ee.READY:a===p.READY?O(this.params.desiredState.playbackState,p.READY):a===p.PAUSED?(this.videoState.setState(ee.PAUSED),this.liveOffset.pause(),O(this.params.desiredState.playbackState,p.PAUSED)):a===p.PLAYING&&(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed());return;case ee.PLAYING:a===p.PAUSED?(this.videoState.startTransitionTo(ee.PAUSED),this.liveOffset.pause(),this.video.pause()):(n==null?void 0:n.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case ee.PAUSED:if(a===p.PLAYING)if(this.videoState.startTransitionTo(ee.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(n==null?void 0:n.to)===p.PAUSED&&(O(this.params.desiredState.playbackState,p.PAUSED),this.liveOffset.pause());return;case ee.CHANGING_MANIFEST:break;default:return H(r)}},this.params=e,this.video=Lt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Ae.INVARIANT,url:this.params.source.url},sa(Me(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:s})=>{s.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:I.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:I.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),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(Qe(this.params.source.url)),this.maxSeekBackTime$=new b((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t,s,r;const{autoVideoTrackSwitching:a,videoTrack:n}=this.params.desiredState,o=a.getState(),l=n.getTransition(),d=(r=(t=(e=l==null?void 0:l.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(s=n.getState())===null||s===void 0?void 0:s.id)!==null&&r!==void 0?r:"master",u=this.manifests$.getValue();if(!u.length)return;const c=o?"master":d;return o&&!l&&n.startTransitionTo(this.masterManifest),u.find(h=>h.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsLiveProvider",category:I.WTF,message:"HlsLiveProvider internal logic error",thrown:o})},r=_t(this.video),a=(o,l)=>this.subscription.add(o.subscribe(l,s));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(xt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(ii(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ee.PLAYING),O(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(ee.PAUSED),O(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ee.READY&&this.videoState.setState(ee.READY),this.videoState.getState()===ee.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.maxSeekBackTime$.pipe(ce(),w(o=>-o/1e3)).subscribe(this.params.output.duration$,s)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const o=this.params.desiredState.seekState.getState(),l=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&k(d.to)){const c=d.to.id;this.params.desiredState.videoTrack.setState(d.to);const h=this.manifests$.getValue().find(f=>f.id===c);h&&(this.params.output.currentVideoTrack$.next(h),this.params.output.hostname$.next(Qe(h.url)))}u&&this.params.desiredState.autoVideoTrackSwitching.setState(u.to),l&&l.from===ee.CHANGING_MANIFEST&&this.videoState.setState(l.to),o&&o.state===Y.Requested&&this.seek(o.position)},s)),this.subscription.add(r.loadedData$.subscribe(()=>{var o,l,d;const u=(d=(l=(o=this.video)===null||o===void 0?void 0:o.getStartDate)===null||l===void 0?void 0:l.call(o))===null||d===void 0?void 0:d.getTime();this.manifestStartTime$.next(u||void 0)},s)),this.subscription.add(We({startTime:this.manifestStartTime$.pipe(ue(k)),currentTime:r.timeUpdate$}).subscribe(({startTime:o,currentTime:l})=>this.params.output.liveTime$.next(o+l*1e3),s)),this.subscription.add(this.manifests$.pipe(w(o=>o.map(({id:l,quality:d,size:u,bandwidth:c,fps:h})=>({id:l,quality:d,size:u,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,s));const n=N(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Le(["init"])).pipe(ze(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),It(this.video)}prepare(){var e,t;const s=this.selectManifest();if(Q(s))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URL(s.url);if((r||a)&&s.id===this.masterManifest.id){const{max:d,min:u}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:a)!==null&&t!==void 0?t:{};for(const[c,h]of[[d,"mq"],[u,"lq"]]){const f=String(parseFloat(c||""));h&&c&&n.searchParams.set(h,f)}}const o=this.params.format===y.HLS_LIVE_CMAF?pe.DASH_CMAF_OFFSET_P:pe.OFFSET_P,l=Me(n.toString(),this.liveOffset.getTotalOffset(),o);this.video.setAttribute("src",l),this.video.load(),kn(l).then(d=>{var u;if(!Q(d))this.maxSeekBackTime$.next(d);else{const c=(u=this.params.source.maxSeekBackTime)!==null&&u!==void 0?u:this.maxSeekBackTime$.getValue();if(Q(c)||!isFinite(c))try{vi(l).then(h=>h.text()).then(h=>{var f;const g=(f=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(h))===null||f===void 0?void 0:f[1];if(g){const m=new URL(g,l).toString();kn(m).then(v=>{Q(v)||this.maxSeekBackTime$.next(v)})}})}catch(h){}}})}playIfAllowed(){Ct(this.video).then(e=>{e||(this.videoState.setState(ee.PAUSED),this.liveOffset.pause(),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:I.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3),this.params.output.seekedEvent$.next()}}var re;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(re||(re={}));class Pv{constructor(e){this.subscription=new ie,this.videoState=new le(re.STOPPED),this.textTracksManager=new ft,this.manifests$=new b([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const s=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),l=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r===p.STOPPED){s!==re.STOPPED&&(this.videoState.startTransitionTo(re.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(re.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.seekState.getState();if(s===re.STOPPED){this.videoState.startTransitionTo(re.READY),this.prepare();return}if(n||o||l){const c=this.videoState.getState();this.videoState.setState(re.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),l&&this.params.output.autoVideoTrackLimits$.next(l.to),u.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:h*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==p.PAUSED&&u.state===Y.Requested&&this.seek(u.position),s){case re.READY:r===p.READY?O(this.params.desiredState.playbackState,p.READY):r===p.PAUSED?(this.videoState.setState(re.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):r===p.PLAYING&&(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed());return;case re.PLAYING:r===p.PAUSED?(this.videoState.startTransitionTo(re.PAUSED),this.video.pause()):(a==null?void 0:a.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case re.PAUSED:r===p.PLAYING?(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;case re.CHANGING_MANIFEST:break;default:return H(s)}},this.params=e,this.video=Lt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:Ae.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(Qe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),sa(Me(this.params.source.url),this.params.source.url,{manifestRetryInterval:this.params.tuning.manifestRetryInterval,manifestRetryMaxInterval:this.params.tuning.manifestRetryMaxInterval,manifestRetryMaxCount:this.params.tuning.manifestRetryMaxCount}).then(({qualityManifests:t,textTracks:s})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(s)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:I.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var e,t,s,r;const{autoVideoTrackSwitching:a,videoTrack:n}=this.params.desiredState,o=a.getState(),l=n.getTransition(),d=(r=(t=(e=l==null?void 0:l.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(s=n.getState())===null||s===void 0?void 0:s.id)!==null&&r!==void 0?r:"master",u=this.manifests$.getValue();if(!u.length)return;const c=o?"master":d;return o&&!l&&n.startTransitionTo(this.masterManifest),u.find(h=>h.id===c)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"HlsProvider",category:I.WTF,message:"HlsProvider internal logic error",thrown:o})},r=_t(this.video),a=(o,l)=>this.subscription.add(o.subscribe(l));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(Ti(this.video,t.isLooped,s)),this.subscription.add(xt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(ii(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(re.PLAYING),O(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(re.PAUSED),O(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===re.READY&&this.videoState.setState(re.READY),this.videoState.getState()===re.PLAYING&&this.playIfAllowed()},s).add(r.loadedMetadata$.subscribe(()=>{var o;const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&k(u.to)){const h=u.to.id;this.params.desiredState.videoTrack.setState(u.to);const f=this.manifests$.getValue().find(g=>g.id===h);if(f){this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Qe(f.url));const g=this.params.desiredState.playbackRate.getState(),m=(o=this.params.output.element$.getValue())===null||o===void 0?void 0:o.playbackRate;if(g!==m){const v=this.params.output.element$.getValue();v&&(this.params.desiredState.playbackRate.setState(g),v.playbackRate=g)}}}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===re.CHANGING_MANIFEST&&this.videoState.setState(d.to),l.state===Y.Requested&&this.seek(l.position)},s))),this.subscription.add(this.manifests$.pipe(w(o=>o.map(({id:l,quality:d,size:u,bandwidth:c,fps:h})=>({id:l,quality:d,size:u,fps:h,bitrate:c})))).subscribe(this.params.output.availableVideoTracks$,s)),!vd()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:o}=this.video;this.subscription.add(N(C(o,"addtrack"),C(o,"removetrack"),C(o,"change"),Le(["init"])).subscribe(()=>{for(let l=0;l<o.length;l++)o[l].mode="hidden"},s))}const n=N(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,Le(["init"])).pipe(ze(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),It(this.video)}prepare(){var e,t;const s=this.selectManifest();if(Q(s))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),a=this.params.desiredState.autoVideoTrackLimits.getState(),n=new URL(s.url);if((r||a)&&s.id===this.masterManifest.id){const{max:o,min:l}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:a)!==null&&t!==void 0?t:{};for(const[d,u]of[[o,"mq"],[l,"lq"]]){const c=String(parseFloat(d||""));u&&d&&n.searchParams.set(u,c)}}this.video.setAttribute("src",n.toString()),this.video.load()}playIfAllowed(){Ct(this.video).then(e=>{e||(this.videoState.setState(re.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:I.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var de;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(de||(de={}));class Dv{constructor(e){this.subscription=new ie,this.videoState=new le(de.STOPPED),this.trackUrls={},this.textTracksManager=new ft,this.syncPlayback=()=>{var t,s,r;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition();if(n===p.STOPPED){a!==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),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.autoVideoTrackLimits.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.seekState.getState();if(d&&a!==de.READY&&!u){this.handleQualityLimitTransition(d.to.max);return}if(a===de.STOPPED){this.videoState.startTransitionTo(de.READY),this.prepare();return}if(u){const{currentTime:h}=this.video;this.prepare(),c.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:h*1e3,forcePrecise:!0}),u.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((r=(s=this.trackUrls[u.to.id])===null||s===void 0?void 0:s.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===Y.Requested&&this.seek(c.position),a){case de.READY:n===p.READY?O(this.params.desiredState.playbackState,p.READY):n===p.PAUSED?(this.videoState.setState(de.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):n===p.PLAYING&&(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed());return;case de.PLAYING:n===p.PAUSED?(this.videoState.startTransitionTo(de.PAUSED),this.video.pause()):(o==null?void 0:o.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case de.PAUSED:n===p.PLAYING?(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;default:return H(a)}},this.params=e,this.video=Lt(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,s],r)=>{const a=r.toString(10);this.trackUrls[a]={track:{quality:t,id:a},url:s}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"MpegProvider",category:I.WTF,message:"MpegProvider internal logic error",thrown:o})},r=_t(this.video),a=(o,l)=>this.subscription.add(o.subscribe(l,s));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.loadedMetadata$,e.firstBytesEvent$),a(r.playing$,e.firstFrameEvent$),a(r.canplay$,e.canplay$),a(r.seeked$,e.seekedEvent$),a(r.inPiP$,e.inPiP$),a(r.inFullscreen$,e.inFullscreen$),this.subscription.add(Ti(this.video,t.isLooped,s)),this.subscription.add(xt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(ii(this.video,t.playbackRate,r.playbackRateState$,s)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(de.PLAYING),O(t.playbackState,p.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED),O(t.playbackState,p.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var o,l;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===de.READY&&this.videoState.setState(de.READY);const d=this.params.desiredState.videoTrack.getTransition();if(d&&k(d.to)){this.params.desiredState.videoTrack.setState(d.to),this.params.output.currentVideoTrack$.next(this.trackUrls[d.to.id].track);const u=this.params.desiredState.playbackRate.getState(),c=(l=this.params.output.element$.getValue())===null||l===void 0?void 0:l.playbackRate;if(u!==c){const h=this.params.output.element$.getValue();h&&(this.params.desiredState.playbackRate.setState(u),h.playbackRate=u)}}this.videoState.getState()===de.PLAYING&&this.playIfAllowed()},s)),this.textTracksManager.connect(this.video,t,e);const n=N(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,Le(["init"])).pipe(ze(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),It(this.video)}prepare(){var e;const t=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id;D(t,"MpegProvider: track is not selected");let{url:s}=this.trackUrls[t];D(s,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(s=_r(s)),this.video.setAttribute("src",s),this.video.load(),this.params.output.hostname$.next(Qe(s))}playIfAllowed(){Ct(this.video).then(e=>{e||(this.videoState.setState(de.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:I.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,s,r,a;let n,o=e;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const l=(s=Object.values(this.trackUrls).find(c=>!kt(c.track.quality)&&Ji(c.track.quality,e)))===null||s===void 0?void 0:s.track,d=(r=this.params.desiredState.videoTrack.getState())===null||r===void 0?void 0:r.id,u=(a=this.trackUrls[d!=null?d:"0"])===null||a===void 0?void 0:a.track;if(l&&u&&Sr(u.quality,l.quality)&&(n=l),!n){const c=Object.values(this.trackUrls).filter(f=>!kt(f.track.quality)&&Kt(f.track.quality,e)),h=c.length;h&&(n=c[h-1].track)}n&&(o=n.quality)}else if(!e){const l=Object.values(this.trackUrls).map(d=>d.track);n=gs(l,{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})}n&&(this.params.output.currentVideoTrack$.next(n),this.params.desiredState.videoTrack.startTransitionTo(n)),this.params.output.autoVideoTrackLimits$.next({max:o})}}const Pn=["stun:videostun.mycdn.me:80"],Rv=1e3,Lv=3,or=()=>null;class Iv{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=or,this.externalStopCallback=or,this.externalErrorCallback=or,this.options=this.normalizeOptions(t);const s=e.split("/");this.serverUrl=s.slice(0,s.length-1).join("/"),this.streamKey=s[s.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}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:Pn}]};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:I.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),s=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(s))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),Rv)}normalizeOptions(e={}){const t={stunServerList:Pn,maxRetryNumber:Lv,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var te;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(te||(te={}));class xv{constructor(e){this.videoState=new le(te.STOPPED),this.maxSeekBackTime$=new b(0),this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(s===p.STOPPED){t!==te.STOPPED&&(this.videoState.startTransitionTo(te.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(te.STOPPED),O(this.params.desiredState.playbackState,p.STOPPED,!0));return}if(this.videoState.getTransition())return;const n=this.params.desiredState.videoTrack.getTransition();if(t===te.STOPPED){this.videoState.startTransitionTo(te.READY),this.prepare();return}if(n){this.prepare();return}switch(t){case te.READY:s===p.PAUSED?(this.videoState.setState(te.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED)):s===p.PLAYING&&(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed());return;case te.PLAYING:s===p.PAUSED?(this.videoState.startTransitionTo(te.PAUSED),this.video.pause()):(r==null?void 0:r.to)===p.PLAYING&&O(this.params.desiredState.playbackState,p.PLAYING);return;case te.PAUSED:s===p.PLAYING?(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===p.PAUSED&&O(this.params.desiredState.playbackState,p.PAUSED);return;default:return H(t)}},this.subscription=new ie,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=Lt(e.container),this.liveStreamClient=new Iv(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),It(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,s=n=>{e.error$.next({id:"WebRTCLiveProvider",category:I.WTF,message:"WebRTCLiveProvider internal logic error",thrown:n})};N(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=_t(this.video),a=(n,o)=>this.subscription.add(n.subscribe(o,s));a(r.timeUpdate$,e.liveTime$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),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)===te.READY&&this.videoState.setState(te.READY)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(te.PAUSED)},s)).add(r.playing$.subscribe(()=>{this.videoState.setState(te.PLAYING)},s)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(xt(this.video,t.volume,r.volumeState$,s)).add(r.volumeState$.subscribe(e.volume$,s)).add(this.videoState.stateChangeEnded$.subscribe(n=>{switch(n.to){case te.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(p.STOPPED);break;case te.READY:break;case te.PAUSED:t.playbackState.setState(p.PAUSED);break;case te.PLAYING:t.playbackState.setState(p.PLAYING);break;default:return H(n.to)}},s)).add(N(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,Le(["init"])).pipe(ze(0)).subscribe(this.syncPlayback.bind(this),s)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),s))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Qe(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:Ae.INVARIANT}),this.video.srcObject=e,O(this.params.desiredState.playbackState,p.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(te.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:I.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ct(this.video).then(e=>{e||(this.videoState.setState(te.PAUSED),O(this.params.desiredState.playbackState,p.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:I.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class Dn{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 dr,lr,ur,cr,Ni,hr,Fi,fr,Vi,pr,Ui,mr,Hi,vr,Gi,gr;const Go=Mr().device===gd.Android,ht=document.createElement("video"),_v='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Cv='video/mp4; codecs="hev1.1.6.L93.B0"',Yo='video/webm; codecs="vp09.00.10.08"',qo='video/webm; codecs="av01.0.00M.08"',Ov='audio/mp4; codecs="mp4a.40.2"',Mv='audio/webm; codecs="opus"',Tt={mms:Uo(),mse:cv(),hls:!!(!((dr=ht.canPlayType)===null||dr===void 0)&&dr.call(ht,"application/x-mpegurl")||!((lr=ht.canPlayType)===null||lr===void 0)&&lr.call(ht,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Pe={mp4:!!(!((ur=ht.canPlayType)===null||ur===void 0)&&ur.call(ht,"video/mp4")),webm:!!(!((cr=ht.canPlayType)===null||cr===void 0)&&cr.call(ht,"video/webm")),cmaf:!0},je={h264:!!(!((hr=(Ni=yt())===null||Ni===void 0?void 0:Ni.isTypeSupported)===null||hr===void 0)&&hr.call(Ni,_v)),h265:!!(!((fr=(Fi=yt())===null||Fi===void 0?void 0:Fi.isTypeSupported)===null||fr===void 0)&&fr.call(Fi,Cv)),vp9:!!(!((pr=(Vi=yt())===null||Vi===void 0?void 0:Vi.isTypeSupported)===null||pr===void 0)&&pr.call(Vi,Yo)),av1:!!(!((mr=(Ui=yt())===null||Ui===void 0?void 0:Ui.isTypeSupported)===null||mr===void 0)&&mr.call(Ui,qo)),aac:!!(!((vr=(Hi=yt())===null||Hi===void 0?void 0:Hi.isTypeSupported)===null||vr===void 0)&&vr.call(Hi,Ov)),opus:!!(!((gr=(Gi=yt())===null||Gi===void 0?void 0:Gi.isTypeSupported)===null||gr===void 0)&&gr.call(Gi,Mv))},ui=(je.h264||je.h265)&&je.aac;var ct;(function(i){i.VP9="vp9",i.AV1="av1",i.NONE="none",i.SMOOTH="smooth",i.POWER_EFFICIENT="power_efficient"})(ct||(ct={}));var tt;(function(i){i.DASH="dash",i.HLS="hls",i.MPEG="mpeg"})(tt||(tt={}));let Et;const Bv=async()=>{if(!window.navigator.mediaCapabilities)return;const i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:qo}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:Yo}})]);Et={[y.DASH_WEBM_AV1]:e,[y.DASH_WEBM]:t}};try{Bv()}catch(i){console.error(i)}const gi=Tt.hls&&Pe.mp4,Nv=()=>Object.keys(je).filter(i=>je[i]),Fv=(i,e=!1,t=!1)=>{const s=Tt.mse||Tt.mms&&t;return i.filter(r=>{switch(r){case y.DASH_SEP:return s&&Pe.mp4&&ui;case y.DASH_WEBM:return s&&Pe.webm&&je.vp9&&je.opus;case y.DASH_WEBM_AV1:return s&&Pe.webm&&je.av1&&je.opus;case y.DASH_LIVE:return Tt.mse&&Pe.mp4&&ui;case y.DASH_LIVE_CMAF:return s&&Pe.mp4&&ui&&Pe.cmaf;case y.DASH_ONDEMAND:return s&&Pe.mp4&&ui;case y.HLS:case y.HLS_ONDEMAND:return gi||e&&Tt.mse&&Pe.mp4&&ui;case y.HLS_LIVE:case y.HLS_LIVE_CMAF:return gi;case y.MPEG:return Pe.mp4;case y.DASH_LIVE_WEBM:return!1;case y.WEB_RTC_LIVE:return Tt.webrtc&&Tt.ws&&je.h264&&(Pe.mp4||Pe.webm);default:return H(r)}})},ci=i=>{const e=y.DASH_WEBM,t=y.DASH_WEBM_AV1;switch(i){case ct.VP9:return[e,t];case ct.AV1:return[t,e];case ct.NONE:return[];case ct.SMOOTH:return Et?Et[t].smooth?[t,e]:Et[e].smooth?[e,t]:[t,e]:[e,t];case ct.POWER_EFFICIENT:return Et?Et[t].powerEfficient?[t,e]:Et[e].powerEfficient?[e,t]:[t,e]:[e,t];default:H(i)}return[e,t]},Vv=({webmCodec:i,androidPreferredFormat:e})=>{if(Go)switch(e){case tt.MPEG:return[y.MPEG,...ci(i),y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND];case tt.HLS:return[y.HLS,y.HLS_ONDEMAND,...ci(i),y.DASH_SEP,y.DASH_ONDEMAND,y.MPEG];case tt.DASH:return[...ci(i),y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG]}return gi?[...ci(i),y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG]:[...ci(i),y.DASH_SEP,y.DASH_ONDEMAND,y.HLS,y.HLS_ONDEMAND,y.MPEG]},Uv=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{const s=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=[...s,...r],n=[...r,...s];let o;if(Go)switch(i){case tt.DASH:{o=a;break}case tt.HLS:case tt.MPEG:{o=n;break}}else gi?o=n:o=a;return t?[y.WEB_RTC_LIVE,...o]:[...o,y.WEB_RTC_LIVE]},Rn=i=>i?[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 Hv=i=>new os(e=>{const t=new ie,s=i.desiredPlaybackState$.stateChangeStarted$.pipe(w(({from:d,to:u})=>`${d}-${u}`)),r=i.desiredPlaybackState$.stateChangeEnded$,a=i.providerChanged$.pipe(w(({type:d})=>d!==void 0)),n=new x;let o=0,l="unknown";return t.add(s.subscribe(d=>{o&&window.clearTimeout(o),l=d,o=window.setTimeout(()=>n.next(d),i.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(o),l="unknown",o=0})),t.add(a.subscribe(d=>{o&&(window.clearTimeout(o),o=0,d&&(o=window.setTimeout(()=>n.next(l),i.maxTransitionInterval)))})),t.add(n.subscribe(e)),()=>{window.clearTimeout(o),t.unsubscribe()}});const Gv={chunkDuration:5e3,maxParallelRequests:5};class Yv{constructor(e){this.current$=new b({type:void 0}),this.providerError$=new x,this.noAvailableProvidersError$=new x,this.providerOutput={position$:new b(0),duration$:new b(1/0),volume$:new b({muted:!1,volume:1}),currentVideoTrack$:new b(void 0),availableVideoTracks$:new b([]),availableAudioTracks$:new b([]),isAudioAvailable$:new b(!0),autoVideoTrackLimitingAvailable$:new b(!1),autoVideoTrackLimits$:new b(void 0),currentBuffer$:new b(void 0),isBuffering$:new b(!0),error$:new x,warning$:new x,willSeekEvent$:new x,seekedEvent$:new x,loopedEvent$:new x,endedEvent$:new x,firstBytesEvent$:new x,firstFrameEvent$:new x,canplay$:new x,isLive$:new b(void 0),isLowLatency$:new b(!1),canChangePlaybackSpeed$:new b(!0),liveTime$:new b(void 0),liveBufferTime$:new b(void 0),availableTextTracks$:new b([]),currentTextTrack$:new b(void 0),hostname$:new b(void 0),httpConnectionType$:new b(void 0),httpConnectionReused$:new b(void 0),inPiP$:new b(!1),inFullscreen$:new b(!1),element$:new b(void 0),availableSources$:new b(void 0),is3DVideo$:new b(!1)},this.subscription=new ie,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Fv([...Uv(this.params.tuning),...Vv(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(o=>k(e.sources[o])),{forceFormat:s,formatsToAvoid:r}=this.params.tuning;let a=[];s?a=[s]: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 Dn(a);const n=[...Rn(!0),...Rn(!1)];this.chromecastFormatsIterator=new Dn(n.filter(o=>k(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(Q(t)){this.handleNoFormatsError(e);return}let s;try{s=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:I.WTF,message:"Failed to create provider",thrown:r})}s?this.current$.next({type:t,provider:s,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,s=this.params.desiredState.seekState.getState(),r=s.state!==Y.None;if(this.params.desiredState.seekState.setState({state:Y.Requested,position:r?s.position:t,forcePrecise:r?s.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 be.SCREEN:return this.createScreenProvider(t);case be.CHROMECAST:return this.createChromecastProvider(t);default:return H(e)}}createScreenProvider(e){const{sources:t,container:s,desiredState:r}=this.params,a=this.providerOutput,n={container:s,source:null,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case y.DASH_SEP:case y.DASH_WEBM:case y.DASH_WEBM_AV1:case y.DASH_ONDEMAND:{const o=this.applyFailoverHost(t[e]),l=this.applyFailoverHost(t[y.HLS_ONDEMAND]||t[y.HLS]);return D(o),new yv({...n,source:o,sourceHls:l})}case y.DASH_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return D(o),new Tv({...n,source:o})}case y.HLS:case y.HLS_ONDEMAND:{const o=this.applyFailoverHost(t[e]);return D(o),gi||!this.params.tuning.useHlsJs?new Pv({...n,source:o}):new Ev({...n,source:o})}case y.HLS_LIVE:case y.HLS_LIVE_CMAF:{const o=this.applyFailoverHost(t[e]);return D(o),new kv({...n,source:o,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case y.MPEG:{const o=this.applyFailoverHost(t[e]);return D(o),new Dv({...n,source:o})}case y.DASH_LIVE:{const o=this.applyFailoverHost(t[e]);return D(o),new $p({...n,source:o,config:{...Gv,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case y.WEB_RTC_LIVE:{const o=this.applyFailoverHost(t[e]);return D(o),new xv({container:s,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 H(e)}}createChromecastProvider(e){const{sources:t,container:s,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return D(o),new Nf({connection:o,meta:a,container:s,source:t,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?be.CHROMECAST:be.SCREEN}chooseFormat(e){switch(e){case be.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case be.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return H(e)}}skipFormat(e){switch(e){case be.SCREEN:return this.screenFormatsIterator.next();case be.CHROMECAST:return this.chromecastFormatsIterator.next();default:return H(e)}}handleNoFormatsError(e){switch(e){case be.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case be.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return H(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const s=r=>{const a=new URL(r);return a.host=t,a.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:s(e.url)}}return is(Object.entries(e).map(([r,a])=>[r,s(a)]))}initProviderErrorHandling(){const e=new ie;let t=!1,s=0;return e.add(N(this.providerOutput.error$,Hv({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(w(r=>({id:`ProviderHangup:${r}`,category:I.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(ue(({to:a})=>a===p.PLAYING),Ee()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{const a=this.current$.getValue().destination;if(a===be.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(be.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=r.category===I.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=s<this.params.tuning.providerErrorLimit;o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(s++,this.reinitProvider()):this.switchToNextProvider(a!=null?a:be.SCREEN)}})),e}}const qv=5e3,Ln="one_video_throughput",In="one_video_rtt",it=window.navigator.connection,xn=()=>{const i=it==null?void 0:it.downlink;if(k(i)&&i!==10)return i*1e3},_n=()=>{const i=it==null?void 0:it.rtt;if(k(i)&&i!==3e3)return i},Cn=(i,e,t)=>{const s=t*8,r=s/i;return s/(r+e)};class fi{constructor(e){var t,s;this.subscription=new ie,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=fi.load(Ln)||(e.useBrowserEstimation?xn():void 0)||qv,a=(s=(t=fi.load(In))!==null&&t!==void 0?t:e.useBrowserEstimation?_n():void 0)!==null&&s!==void 0?s:0;if(this.throughput$=new b(r),this.rtt$=new b(a),this.rttAdjustedThroughput$=new b(Cn(r,a,e.rttPenaltyRequestSize)),this.throughput=Or.getSmoothedValue(r,-1,e),this.rtt=Or.getSmoothedValue(a,1,e),e.useBrowserEstimation){const n=()=>{const l=xn();l&&this.throughput.next(l);const d=_n();k(d)&&this.rtt.next(d)};it&&"onchange"in it&&this.subscription.add(C(it,"change").subscribe(n)),n()}this.subscription.add(this.throughput.smoothed$.subscribe(n=>{xs.set(Ln,n.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(n=>{xs.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(We({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(w(({throughput:n,rtt:o})=>Cn(n,o,e.rttPenaltyRequestSize)),ue(n=>{const o=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(n-o)/o>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,s=ne();const r=new ie;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(C(e,"progress").pipe(Ee()).subscribe(a=>{t=a.loaded,s=ne()}));break;case 1:case 0:r.add(C(e,"loadstart").subscribe(()=>{t=0,s=ne()}));break}r.add(C(e,"loadend").subscribe(a=>{if(e.status===200){const n=a.loaded,o=ne(),l=n-t,d=o-s;this.addRawSpeed(l,d,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){const s=e.getReader();if(!s){e.cancel("Could not get reader");return}let r=0,a=ne(),n=0,o=ne();const l=u=>{this.concurrentDownloads.delete(e),s.releaseLock(),e.cancel(`Throughput Estimator error: ${u}`).catch(()=>{})},d=async({done:u,value:c})=>{if(u)!t&&this.addRawSpeed(r,ne()-a,1),this.concurrentDownloads.delete(e);else if(c){if(t){if(ne()-o<this.tuningConfig.lowLatency.continuesByteSequenceInterval)n+=c.byteLength;else{const f=o-a;f&&this.addRawSpeed(n,f,1,t),n=c.byteLength,a=ne()}o=ne()}else r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&ne()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,ne()-o,this.concurrentDownloads.size),n=0,o=ne());await(s==null?void 0:s.read().then(d,l))}};this.concurrentDownloads.add(e),s==null||s.read().then(d,l)}addRawSpeed(e,t,s=1,r=!1){if(fi.sanityCheck(e,t,r)){const a=e*8/t;this.throughput.next(a*s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,s=!1){const r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||s&&e<1e4||!s&&e<10*1024||!s&&t<=20)}static load(e){var t;const s=xs.get(e);if(k(s))return(t=parseInt(s,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,lowLatency:{continuesByteSequenceInterval:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3,backgroundVideoQualityLimit:Ae.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:Ae.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},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:ct.VP9,androidPreferredFormat:tt.MPEG,preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,dashMaxWaitingDuration:5e3,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,manifestRetryInterval:300,manifestRetryMaxInterval:1e4,manifestRetryMaxCount:10,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},jv=i=>{var e;return{...Sd(i,On),configName:[...(e=i.configName)!==null&&e!==void 0?e:[],...On.configName]}};var Mn=({seekState:i,position$:e})=>N(i.stateChangeEnded$.pipe(w(({to:t})=>{var s;return t.state===Y.None?void 0:((s=t.position)!==null&&s!==void 0?s:NaN)/1e3}),ue(k)),e.pipe(ue(()=>i.getState().state===Y.None))),zv=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return D(e,`Wrong container or containerId {${i.container}}`),e};const Wv=(i,e,t,s)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(ue(r=>r.length>0),Ee()).subscribe(r=>{r.find(s)&&e.startTransitionTo(i)}):(i===void 0||t!=null&&t.getValue().find(s))&&e.startTransitionTo(i)};class Zv{constructor(e={configName:[]}){if(this.subscription=new ie,this.logger=new bd,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.desiredState={playbackState:new le(p.STOPPED),seekState:new le({state:Y.None}),volume:new le({volume:1,muted:!1}),videoTrack:new le(void 0),autoVideoTrackSwitching:new le(!0),autoVideoTrackLimits:new le({}),isLooped:new le(!1),playbackRate:new le(1),externalTextTracks:new le([]),internalTextTracks:new le([]),currentTextTrack:new le(void 0),textTrackCuesSettings:new le({}),cameraOrientation:new le({x:0,y:0})},this.info={playbackState$:new b(p.STOPPED),position$:new b(0),duration$:new b(1/0),muted$:new b(!1),volume$:new b(1),availableQualities$:new b([]),availableQualitiesFps$:new b({}),availableAudioTracks$:new b([]),isAudioAvailable$:new b(!0),currentQuality$:new b(void 0),isAutoQualityEnabled$:new b(!0),autoQualityLimitingAvailable$:new b(!1),autoQualityLimits$:new b({}),currentPlaybackRate$:new b(1),currentBuffer$:new b({start:0,end:0}),isBuffering$:new b(!0),isStalled$:new b(!1),isEnded$:new b(!1),isLooped$:new b(!1),isLive$:new b(void 0),canChangePlaybackSpeed$:new b(void 0),atLiveEdge$:new b(void 0),atLiveDurationEdge$:new b(void 0),liveTime$:new b(void 0),liveBufferTime$:new b(void 0),currentFormat$:new b(void 0),availableTextTracks$:new b([]),currentTextTrack$:new b(void 0),throughputEstimation$:new b(void 0),rttEstimation$:new b(void 0),videoBitrate$:new b(void 0),hostname$:new b(void 0),httpConnectionType$:new b(void 0),httpConnectionReused$:new b(void 0),surface$:new b(ut.NONE),chromecastState$:new b(ve.NOT_AVAILABLE),chromecastDeviceName$:new b(void 0),intrinsicVideoSize$:new b(void 0),availableSources$:new b(void 0),is3DVideo$:new b(!1)},this.events={inited$:new x,ready$:new x,started$:new x,playing$:new x,paused$:new x,stopped$:new x,willStart$:new x,willResume$:new x,willPause$:new x,willStop$:new x,willDestruct$:new x,watchCoverageRecord$:new x,watchCoverageLive$:new x,managedError$:new x,fatalError$:new x,ended$:new x,looped$:new x,seeked$:new x,willSeek$:new x,firstBytes$:new x,firstFrame$:new x,canplay$:new x,log$:new x},this.experimental={element$:new b(void 0),tuningConfigName$:new b([]),enableDebugTelemetry$:new b(!1),dumpTelemetry:ap},this.initLogs(),this.tuning=jv(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 fi(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,s,r)=>{const a=Reflect.get(t,s,r);return typeof a!="function"?a:(...n)=>{try{return a.apply(t,n)}catch(o){const l=n.map(c=>JSON.stringify(c,(h,f)=>{const g=typeof f;return["number","string","boolean"].includes(g)?f:f===null?null:`<${g}>`})),d=`Player.${String(s)}`,u=`Exception calling ${d} (${l.join(", ")})`;throw this.events.fatalError$.next({id:d,category:I.WTF,message:u,thrown:o}),o}}}})}initVideo(e){var t,s,r;return this.config=e,this.domContainer=zv(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Yv({sources:e.sources,meta:(s=e.meta)!==null&&s!==void 0?s:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,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?C(document,"visibilitychange").pipe(Ee()).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 s=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=s&&!r&&(e=s-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:Y.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()===ve.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()===ve.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){D(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(ue(s=>s.length>0),Ee()).subscribe(s=>{this.setVideoTrackIdByQuality(s,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var t;D(this.providerContainer);const s=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return s&&(this.desiredState.playbackRate.setState(e),s.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return Wv(e,this.desiredState.currentTextTrack,(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$,s=>s.id===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 s=this.getScene3D();return s&&s.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const s=this.getScene3D();if(s){const r=s.getCameraRotation(),a=s.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(){if(!this.providerContainer)return 0;const e=this.providerContainer.providerOutput.element$.getValue();if(Q(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),s=t.state===Y.None?void 0:t.position;return k(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const s=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=s==null?void 0:s.provider)===null||t===void 0)&&t.scene3D)return s.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((s,{width:r})=>s||r||0,0),height:e.reduce((s,{height:r})=>s||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(N(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(ue(({from:e})=>e===p.STOPPED),Ee()).subscribe(()=>{this.initedAt=ne(),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===Y.Requested?this.desiredState.seekState.setState({...n,state:Y.Applying}):this.events.managedError$.next({id:`WillSeekIn${n.state}`,category:I.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===Y.Applying&&(this.desiredState.seekState.setState({state:Y.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),ce()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(w(n=>n.map(({quality:o})=>o).sort((o,l)=>kt(o)?1:kt(l)?-1:Kt(l,o)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(n=>{const o={};for(const l of n)l.fps&&(o[l.quality]=l.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(ce()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(ce()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(ce()).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(We({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Mn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(w(({isLive:n,position:o,isLowLatency:l})=>{const d=l?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return n&&Math.abs(o)<d/1e3}),ce(),pi(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(We({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(w(({isLive:n,position:o,duration:l})=>n&&(Math.abs(l)-Math.abs(o))*1e3<this.tuning.live.activeLiveDelay),ce(),pi(n=>n&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(w(n=>n.muted),ce()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(w(n=>n.volume),ce()).subscribe(this.info.volume$)).add(Mn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(N(e.providerOutput.endedEvent$.pipe(Ki(!0)),e.providerOutput.seekedEvent$.pipe(Ki(!1))).pipe(ce()).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:I.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(Ee(),w(n=>n!=null?n:ne()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(Ee(),w(()=>ne()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(Ee(),w(()=>ne()-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 b(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const s=new b(!0);this.subscription.add(e.current$.subscribe(()=>s.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(ue(({to:n})=>n===p.PLAYING),Ee()).subscribe(()=>s.next(!1)));let r=0;const a=N(e.providerOutput.isBuffering$,t,s).pipe(w(()=>{const n=e.providerOutput.isBuffering$.getValue(),o=t.getValue()||s.getValue();return n&&!o}),ce());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(N(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,l;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:(l=n==null?void 0:n.size)===null||l===void 0?void 0:l.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(N(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const n=e.providerOutput.inPiP$.getValue(),o=e.providerOutput.inFullscreen$.getValue(),l=e.providerOutput.element$.getValue(),d=this.chromecastInitializer.castState$.getValue();let u;d===ve.CONNECTED?u=ut.SECOND_SCREEN:l?n?u=ut.PIP:o?u=ut.FULLSCREEN:u=ut.INLINE:u=ut.NONE,this.info.surface$.getValue()!==u&&this.info.surface$.next(u)}))}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 ie;this.subscription.add(t),this.subscription.add(e.current$.pipe(ce((s,r)=>s.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(ue(s=>s.length>0),Ee()).subscribe(s=>{this.setStartingVideoTrack(s)}))}))}setStartingVideoTrack(e){var t;let s;const r=(t=this.desiredState.videoTrack.getState())===null||t===void 0?void 0:t.quality;r&&(s=e.find(({quality:a})=>a===r),s||this.setAutoQuality(!0)),s||(s=gs(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(s),this.info.currentQuality$.next(s.quality),this.info.videoBitrate$.next(s.bitrate)}initLogs(){this.subscription.add(N(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;D(this.providerContainer),D(t),rp(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(s=>sp(s)),this.providerContainer.current$.subscribe(({type:s})=>Mi("provider",s)),t.duration$.subscribe(s=>Mi("duration",s)),t.availableVideoTracks$.pipe(ue(s=>!!s.length),Ee()).subscribe(s=>Mi("tracks",s)),this.events.fatalError$.subscribe(new Ye("fatalError")),this.events.managedError$.subscribe(new Ye("managedError")),t.position$.subscribe(new Ye("position")),t.currentVideoTrack$.pipe(w(s=>s==null?void 0:s.quality)).subscribe(new Ye("quality")),this.info.currentBuffer$.subscribe(new Ye("buffer")),t.isBuffering$.subscribe(new Ye("isBuffering"))].forEach(s=>this.subscription.add(s)),Mi("codecs",Nv())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},s=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:I.DOM,message:String(r)})})};this.subscription.add(N(C(document,"visibilitychange"),C(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||s():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const s=e.find(r=>r.quality===t);s?this.desiredState.videoTrack.startTransitionTo(s):this.setAutoQuality(!0)}}const eg=`@vkontakte/videoplayer-core@${yd}`;export{ve as ChromecastState,br as HttpConnectionType,sg as Observable,p as PlaybackState,Zv as Player,eg as SDK_VERSION,rg as Subject,ag as Subscription,ut as Surface,yd as VERSION,ng as ValueSubject,y as VideoFormat,og as VideoQuality};
|